import React, { useEffect, useState } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { Input, InputNumber, Button, Switch, Select, Tabs, message, Spin, ColorPicker, Tooltip } from 'antd';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faFloppyDisk, faGear, faEnvelope, faCommentDots, faShieldHalved, faUserShield, faSliders,
  faCreditCard, faPlug, faPalette, faPaperPlane, faCircleInfo, faWandMagicSparkles,
} from '@fortawesome/free-solid-svg-icons';
import Header from '../components/Header';
import * as api from '../services/api';
import { applyFilters } from '../extend';

message.config({ duration: 3, maxCount: 3, top: 24, placement: 'top' });

/** The built-in accent color (FormGlut_Settings::DEFAULT_ACCENT). */
const DEFAULT_ACCENT = '#e94560';

const DEFAULTS = {
  formglut_default_status: 'active',
  formglut_store_entries: true,
  formglut_honeypot: true,
  formglut_admin_email: '',
  formglut_sender_name: 'FormGlut',
  formglut_sender_email: '',
  formglut_email_subject: 'New form submission: {form_name}',
  formglut_success_message: 'Thank you! Your submission has been received.',
  formglut_error_message: 'Something went wrong. Please try again.',
  formglut_recaptcha_version: 'v3',
  formglut_recaptcha_site_key: '',
  formglut_recaptcha_secret_key: '',
  formglut_recaptcha_score: 0.5,
  formglut_recaptcha_enabled: false,
  formglut_hcaptcha_site_key: '',
  formglut_hcaptcha_secret_key: '',
  formglut_turnstile_site_key: '',
  formglut_turnstile_secret_key: '',
  formglut_delete_on_uninstall: false,
  formglut_currency: 'USD',
  formglut_stripe_mode: 'test',
  formglut_stripe_test_publishable: '',
  formglut_stripe_test_secret: '',
  formglut_stripe_live_publishable: '',
  formglut_stripe_live_secret: '',
  formglut_mailchimp_api_key: '',
  formglut_ai_key: '',
  formglut_ai_model: 'claude-sonnet-5-5',
  formglut_accent_color: DEFAULT_ACCENT,
  formglut_admin_accent_color: DEFAULT_ACCENT,
  formglut_smtp_enabled: false,
  formglut_smtp_provider: 'gmail',
  formglut_smtp_host: 'smtp.gmail.com',
  formglut_smtp_port: 587,
  formglut_smtp_encryption: 'tls',
  formglut_smtp_auth: true,
  formglut_smtp_username: '',
  formglut_smtp_password: '',
  formglut_smtp_password_set: false,
  formglut_smtp_password_const: false,
  formglut_smtp_from_email: '',
  formglut_smtp_from_name: '',
  formglut_smtp_force_from: true,
};

/**
 * SMTP providers with a free plan. Host, port and encryption are filled in when one is picked.
 * user/pass: what to type in Username and Password. link: where to get them.
 */
// The site's own domain, for the web host's mail server (mail.example.com).
const SITE_DOMAIN = String(window.location.hostname || 'example.com').replace(/^www\./, '');

const SMTP_PROVIDERS = [
  { value: 'webhost', label: __( 'My web host’s mail server', 'formglut' ), host: 'mail.' + SITE_DOMAIN, port: 465, enc: 'ssl',
    user: sprintf(__( 'The full mailbox address, e.g. noreply@%s', 'formglut' ), SITE_DOMAIN), pass: __( 'That mailbox’s password', 'formglut' ),
    steps: __( 'Free with most hosting plans, and works even when your host blocks outside mail servers like Gmail. In your hosting panel (e.g. cPanel › Email Accounts) create a mailbox such as noreply@ your domain, then enter its address and password here. Your host’s “Connect Devices” page lists the exact server name and port.', 'formglut' ) },
  { value: 'gmail', label: 'Gmail / Google Workspace', host: 'smtp.gmail.com', port: 587, enc: 'tls',
    user: __( 'Your full Gmail address', 'formglut' ), pass: __( 'An App Password (not your normal password)', 'formglut' ),
    steps: __( 'Free with any Google account. Turn on 2-Step Verification, then open myaccount.google.com/apppasswords, create an App Password and paste the 16 characters here. Emails are sent from your Gmail address.', 'formglut' ), link: 'https://myaccount.google.com/apppasswords' },
  { value: 'yahoo', label: 'Yahoo Mail', host: 'smtp.mail.yahoo.com', port: 465, enc: 'ssl',
    user: __( 'Your full Yahoo address', 'formglut' ), pass: __( 'An app password', 'formglut' ),
    steps: __( 'Free with a Yahoo account. In Account Security, choose “Generate app password” and paste it here.', 'formglut' ), link: 'https://login.yahoo.com/account/security' },
  { value: 'brevo', label: 'Brevo (Sendinblue)', host: 'smtp-relay.brevo.com', port: 587, enc: 'tls',
    user: __( 'Your SMTP login (shown on the SMTP & API page)', 'formglut' ), pass: __( 'An SMTP key', 'formglut' ),
    steps: __( 'Free plan with a daily sending limit. In Brevo open SMTP & API › SMTP, generate an SMTP key, and add your sender address under Senders & IPs.', 'formglut' ), link: 'https://app.brevo.com/settings/keys/smtp' },
  { value: 'mailjet', label: 'Mailjet', host: 'in-v3.mailjet.com', port: 587, enc: 'tls',
    user: __( 'Your API key', 'formglut' ), pass: __( 'Your secret key', 'formglut' ),
    steps: __( 'Free plan with a daily sending limit. Copy the API key and secret key from Account settings › SMTP and SEND API settings, and verify your sender address.', 'formglut' ), link: 'https://app.mailjet.com/account/relay' },
  { value: 'smtp2go', label: 'SMTP2GO', host: 'mail.smtp2go.com', port: 587, enc: 'tls',
    user: __( 'The SMTP username you created', 'formglut' ), pass: __( 'That user’s password', 'formglut' ),
    steps: __( 'Free plan with a monthly sending limit. In SMTP2GO go to Sending › SMTP Users, add a user, and verify your sender domain or address. Port 2525 works when 587 is blocked.', 'formglut' ), link: 'https://app.smtp2go.com/' },
  { value: 'mailgun', label: 'Mailgun', host: 'smtp.mailgun.org', port: 587, enc: 'tls',
    user: __( 'SMTP login, e.g. postmaster@mg.yourdomain.com', 'formglut' ), pass: __( 'The SMTP password of that login', 'formglut' ),
    steps: __( 'Free plan with a daily sending limit. Add and verify your domain, then open Domain settings › SMTP credentials. EU accounts use smtp.eu.mailgun.org.', 'formglut' ), link: 'https://app.mailgun.com/' },
  { value: 'resend', label: 'Resend', host: 'smtp.resend.com', port: 465, enc: 'ssl',
    user: 'resend', pass: __( 'An API key (starts with re_)', 'formglut' ),
    steps: __( 'Free plan with a monthly sending limit. Verify your domain, create an API key, and use “resend” as the username.', 'formglut' ), link: 'https://resend.com/api-keys' },
  { value: 'mailersend', label: 'MailerSend', host: 'smtp.mailersend.net', port: 587, enc: 'tls',
    user: __( 'The SMTP username of your domain', 'formglut' ), pass: __( 'The SMTP password', 'formglut' ),
    steps: __( 'Free plan with a monthly sending limit. Verify your domain, then open Domains › Manage › SMTP and create an SMTP user.', 'formglut' ), link: 'https://app.mailersend.com/domains' },
  { value: 'other', label: __( 'Other SMTP server', 'formglut' ), host: '', port: 587, enc: 'tls',
    user: __( 'Usually your email address', 'formglut' ), pass: __( 'Your email or SMTP password', 'formglut' ),
    steps: __( 'Any SMTP server, e.g. the mailbox from your web host. Find the host, port and encryption in your host’s email settings.', 'formglut' ) },
];

const EMAIL_OK = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

/** ⓘ icon that explains an option on hover or focus. */
function Info({ text }) {
  if (!text) return null;
  return (
    <Tooltip title={text} placement="topLeft" overlayStyle={{ maxWidth: 340 }}>
      <span className="fg-fs-info" tabIndex={0} role="img" aria-label={text}><FontAwesomeIcon icon={faCircleInfo} /></span>
    </Tooltip>
  );
}

/** Global Settings › Email delivery (SMTP). */
function SmtpSection({ values, update }) {
  const v = (k) => values['formglut_smtp_' + k];
  const set = (k, val) => update('formglut_smtp_' + k, val);
  const provider = SMTP_PROVIDERS.find((p) => p.value === v('provider')) || SMTP_PROVIDERS[SMTP_PROVIDERS.length - 1];
  const conflicts = (window.formglut_admin && window.formglut_admin.smtp_conflicts) || [];
  const [to, setTo] = useState((window.formglut_admin && window.formglut_admin.admin_email) || '');
  const [busy, setBusy] = useState(false);
  const [result, setResult] = useState(null);

  const pick = (key) => {
    const p = SMTP_PROVIDERS.find((x) => x.value === key);
    set('provider', key);
    if (p && p.value !== 'other') { set('host', p.host); set('port', p.port); set('encryption', p.enc); set('auth', true); }
    if (key === 'resend') set('username', 'resend');
  };

  const test = async () => {
    setBusy(true);
    setResult(null);
    try {
      const r = await api.request('formglut_smtp_test', { to: to.trim(), settings: values }, 'POST');
      setResult({ ok: true, message: r.message });
    } catch (e) {
      setResult({ ok: false, message: e.message, hint: e.data && e.data.hint, log: e.data && e.data.log });
    } finally { setBusy(false); }
  };

  const row = (label, control, info, note) => (
    <div className="fg-fs-row">
      <div className="fg-fs-label">
        <div className="fg-fs-label-line"><label>{label}</label><Info text={info} /></div>
        {note && <div className="fg-fs-help fg-fs-warn">{note}</div>}
      </div>
      <div className="fg-fs-control">{control}</div>
    </div>
  );

  const fromEmail = (v('from_email') || '').trim();

  return (
    <div>
      {conflicts.length > 0 && (
        <div className="fg-fs-note fg-fs-warn" style={{ margin: '0 0 14px' }}>
          {sprintf(__( '%s is active. It takes over your site’s emails, so these settings are not used until you deactivate it.', 'formglut' ), conflicts.join(', '))}
        </div>
      )}
      <div className="fg-fs-row is-switch">
        <div className="fg-fs-label">
          <div className="fg-fs-label-line"><label>{__( 'Send emails through SMTP', 'formglut' )}</label><Info text={__( 'Emails from your site (form notifications, password resets and others) are sent through the mail server below instead of the web server. They reach the inbox far more often. No other plugin needed.', 'formglut' )} /></div>
        </div>
        <div className="fg-fs-control"><Switch checked={!!v('enabled')} onChange={(x) => set('enabled', x)} /></div>
      </div>

      {v('enabled') && (
        <>
          {row(__( 'Email service', 'formglut' ),
            <Select value={provider.value} onChange={pick} style={{ width: '100%' }} options={SMTP_PROVIDERS.map((p) => ({ value: p.value, label: p.label }))} />,
            __( 'All of these have a free plan. Picking one fills in the server details for you.', 'formglut' ))}

          <div className="fg-fs-note" style={{ margin: '0 0 14px' }}>
            {provider.steps}{' '}
            {provider.link && <a href={provider.link} target="_blank" rel="noopener noreferrer">{__( 'Open the page', 'formglut' )} ↗</a>}
          </div>

          {row(__( 'SMTP host', 'formglut' ), <Input value={v('host')} placeholder="smtp.example.com" onChange={(e) => set('host', e.target.value.trim())} />, __( 'The address of the mail server, e.g. smtp.gmail.com. Filled in for you when you pick a service.', 'formglut' ), !v('host') ? __( 'Enter the server address.', 'formglut' ) : '')}
          {row(__( 'Encryption', 'formglut' ),
            <Select value={v('encryption')} onChange={(x) => { set('encryption', x); set('port', x === 'ssl' ? 465 : 587); }} style={{ width: '100%' }} options={[
              { value: 'tls', label: __( 'TLS (port 587, recommended)', 'formglut' ) },
              { value: 'ssl', label: __( 'SSL (port 465)', 'formglut' ) },
              { value: 'none', label: __( 'None (not secure)', 'formglut' ) },
            ]} />,
            __( 'How the connection to the mail server is protected. TLS on port 587 works for most services; SSL uses port 465. Choosing one sets the usual port. Use what your provider lists.', 'formglut' ))}
          {row(__( 'Port', 'formglut' ), <InputNumber min={1} max={65535} value={v('port')} onChange={(x) => set('port', x || 587)} style={{ width: 140 }} />, __( 'The door on the mail server: usually 587 (TLS) or 465 (SSL). If your web host blocks these, many services also accept 2525.', 'formglut' ))}
          <div className="fg-fs-row is-switch">
            <div className="fg-fs-label">
              <div className="fg-fs-label-line"><label>{__( 'Server needs a login', 'formglut' )}</label><Info text={__( 'Almost every service does. Turn off only for a local relay that needs no password.', 'formglut' )} /></div>
            </div>
            <div className="fg-fs-control"><Switch checked={!!v('auth')} onChange={(x) => set('auth', x)} /></div>
          </div>
          {v('auth') && row(__( 'Username', 'formglut' ), <Input value={v('username')} placeholder={provider.user} autoComplete="off" onChange={(e) => set('username', e.target.value)} />, sprintf(__( 'The login for the mail server. For %1$s: %2$s.', 'formglut' ), provider.label, provider.user))}
          {v('auth') && row(__( 'Password', 'formglut' ),
            v('password_const')
              ? <Input value={__( 'Set in wp-config.php (FORMGLUT_SMTP_PASSWORD)', 'formglut' )} disabled />
              : <Input.Password value={v('password')} autoComplete="new-password" placeholder={v('password_set') ? __( 'Saved. Type a new one to change it.', 'formglut' ) : provider.pass} onChange={(e) => set('password', e.target.value)} />,
            sprintf(__( '%s. It is stored encrypted and never shown again.', 'formglut' ), provider.pass),
            !v('password_set') && !v('password') && !v('password_const') ? __( 'Enter the password, or the emails cannot be sent.', 'formglut' ) : '')}
          {row(__( 'From email', 'formglut' ), <Input value={v('from_email')} placeholder={EMAIL_OK.test(v('username') || '') ? v('username') : 'noreply@yoursite.com'} onChange={(e) => set('from_email', e.target.value.trim())} />,
            __( 'The address emails come from. Use your account address, or one you verified with the service. Empty uses the username when it is an email address.', 'formglut' ),
            fromEmail && !EMAIL_OK.test(fromEmail) ? __( 'This is not a valid email address.', 'formglut' ) : '')}
          {row(__( 'From name', 'formglut' ), <Input value={v('from_name')} placeholder={__( 'Your site name', 'formglut' )} onChange={(e) => set('from_name', e.target.value)} />, __( 'Empty keeps the name each email already has (for FormGlut, the sender name from Email notifications).', 'formglut' ))}
          <div className="fg-fs-row is-switch">
            <div className="fg-fs-label">
              <div className="fg-fs-label-line"><label>{__( 'Always send from this address', 'formglut' )}</label><Info text={__( 'Recommended. Every email uses the From email above, even when a plugin sets another one. Most services refuse emails from addresses you have not verified.', 'formglut' )} /></div>
            </div>
            <div className="fg-fs-control"><Switch checked={!!v('force_from')} onChange={(x) => set('force_from', x)} /></div>
          </div>

          <div className="fg-fs-row has-divider">
            <div className="fg-fs-label">
              <div className="fg-fs-label-line"><label>{__( 'Send a test email', 'formglut' )}</label><Info text={__( 'Uses the settings on screen, so you can test before saving.', 'formglut' )} /></div>
            </div>
            <div className="fg-fs-control">
              <div style={{ display: 'flex', gap: 8 }}>
                <Input value={to} onChange={(e) => setTo(e.target.value)} placeholder="you@example.com" onPressEnter={test} />
                <Button type="primary" loading={busy} disabled={!EMAIL_OK.test(to.trim())} onClick={test}>{__( 'Send test', 'formglut' )}</Button>
              </div>
              {result && (
                <div className={result.ok ? 'fg-fs-help' : 'fg-fs-help fg-fs-warn'} style={{ marginTop: 8, color: result.ok ? '#15803d' : undefined }}>
                  <div>{result.message}</div>
                  {result.hint && <div style={{ marginTop: 4, fontWeight: 600 }}>{result.hint}</div>}
                  {result.log && (
                    <details style={{ marginTop: 6 }}>
                      <summary style={{ cursor: 'pointer' }}>{__( 'Server conversation', 'formglut' )}</summary>
                      <pre style={{ whiteSpace: 'pre-wrap', fontSize: 11, maxHeight: 220, overflow: 'auto', background: '#f8fafc', padding: 8, borderRadius: 6 }}>{result.log}</pre>
                    </details>
                  )}
                </div>
              )}
            </div>
          </div>
        </>
      )}
    </div>
  );
}

const BOOL_KEYS = ['formglut_store_entries', 'formglut_honeypot', 'formglut_recaptcha_enabled', 'formglut_delete_on_uninstall'];

/** Defaults with add-on options (formglut.globalSettings.defaults; save them in PHP with formglut_save_settings). */
const getDefaults = () => applyFilters('formglut.globalSettings.defaults', DEFAULTS);

/** The server returns booleans as '1' / '' strings; turn everything into the types the form uses. */
function normalize(server) {
  const defaults = getDefaults();
  const out = { ...defaults };
  Object.keys(defaults).forEach((k) => {
    const v = server[k];
    if (v === undefined || v === null) return;
    if (BOOL_KEYS.includes(k) || typeof defaults[k] === 'boolean') out[k] = v === true || v === '1' || v === 1;
    else if (k === 'formglut_recaptcha_score') out[k] = v === '' ? 0.5 : Number(v);
    else if (typeof v === 'string' && v === '' && ['formglut_default_status', 'formglut_recaptcha_version'].includes(k)) out[k] = DEFAULTS[k];
    else out[k] = v;
  });
  return out;
}

const KEYS_HELP = __( 'Create keys in the provider’s dashboard and paste them here.', 'formglut' );

// Sections hidden until their features are checked for release (see RELEASING_HIDDEN_FIELDS.md).
const HIDDEN_SECTIONS = [];

const ALL_SECTIONS = [
  {
    key: 'general', title: __( 'General', 'formglut' ), icon: faGear, desc: __( 'Defaults that apply to every form.', 'formglut' ), fields: [
      { key: 'formglut_default_status', type: 'select', label: __( 'Default form status', 'formglut' ), tip: __( 'Status given to a new form. Only Active forms are shown on the site; change a form’s status from All Forms.', 'formglut' ), options: [{ value: 'active', label: __( 'Active', 'formglut' ) }, { value: 'draft', label: __( 'Draft', 'formglut' ) }, { value: 'closed', label: __( 'Closed', 'formglut' ) }] },
      { key: 'formglut_store_entries', type: 'switch', label: __( 'Store form submissions', 'formglut' ), tip: __( 'Save every submission in the Entries list. A form can override this in its own settings.', 'formglut' ) },
    ],
  },
  {
    key: 'email', title: __( 'Email notifications', 'formglut' ), icon: faEnvelope, desc: __( 'Who receives submissions, and how the emails look. Each form can override these.', 'formglut' ), fields: [
      { key: 'formglut_admin_email', type: 'text', label: __( 'Admin notification email', 'formglut' ), tip: __( 'Receives every submission. Separate several addresses with commas. Empty uses the WordPress admin email. A form can send elsewhere in its Notifications settings.', 'formglut' ), placeholder: 'admin@yoursite.com, sales@yoursite.com' },
      { key: 'formglut_sender_name', type: 'text', label: __( 'Sender name', 'formglut' ), tip: __( 'The “From” name on notification emails. Empty uses the site title.', 'formglut' ), placeholder: 'FormGlut' },
      { key: 'formglut_sender_email', type: 'text', label: __( 'Sender email', 'formglut' ), tip: __( 'The “From” address. Use an address on your own domain. Empty lets WordPress choose.', 'formglut' ), placeholder: 'noreply@yoursite.com' },
      { key: 'formglut_email_subject', type: 'text', label: __( 'Email subject template', 'formglut' ), tip: __( 'Smart tags work here, e.g. {form_name}, {entry_id} or {field:FIELD_ID}.', 'formglut' ), placeholder: 'New form submission: {form_name}' },
    ],
  },
  {
    key: 'smtp', title: __( 'Email delivery (SMTP)', 'formglut' ), icon: faPaperPlane, desc: __( 'Send emails through Gmail, Brevo, Mailjet or another free SMTP service so they do not land in spam.', 'formglut' ), render: SmtpSection,
  },
  {
    key: 'messages', title: __( 'Messages', 'formglut' ), icon: faCommentDots, desc: __( 'What visitors see after they submit. Each form can use its own text.', 'formglut' ), fields: [
      { key: 'formglut_success_message', type: 'textarea', label: __( 'Success message', 'formglut' ), tip: __( 'Shown after a successful submission. Smart tags such as {form_name} or {field:FIELD_ID} work here. A form can set its own message in Form Settings › Confirmation.', 'formglut' ) },
      { key: 'formglut_error_message', type: 'textarea', label: __( 'Error message', 'formglut' ), tip: __( 'Shown when a submission cannot be saved or a captcha check fails. A form can set its own in Form Settings › Confirmation (Failure message).', 'formglut' ) },
    ],
  },
  {
    key: 'spam', title: __( 'Spam protection', 'formglut' ), icon: faShieldHalved, desc: __( 'Basic protection that needs no account.', 'formglut' ), fields: [
      { key: 'formglut_honeypot', type: 'switch', label: __( 'Enable honeypot', 'formglut' ), tip: __( 'Adds a hidden field that bots fill in; those submissions are dropped quietly. Each form can turn it on or off, and add more checks (blocked words, rate limit, minimum fill time, Akismet) in Form Settings › Spam & privacy.', 'formglut' ) },
    ],
  },
  {
    key: 'captcha', title: __( 'Captcha', 'formglut' ), icon: faUserShield, desc: KEYS_HELP, subs: [
      {
        key: 'recaptcha', title: __( 'Google reCAPTCHA', 'formglut' ), fields: [
      { key: 'formglut_recaptcha_version', type: 'select', label: __( 'Version', 'formglut' ), tip: __( 'Keys are tied to a version — use keys created for the version you pick.', 'formglut' ), options: [{ value: 'v3', label: __( 'reCAPTCHA v3 (invisible, score based)', 'formglut' ) }, { value: 'v2', label: __( 'reCAPTCHA v2 (“I’m not a robot” checkbox)', 'formglut' ) }] },
      { key: 'formglut_recaptcha_site_key', type: 'text', label: __( 'Site key', 'formglut' ), placeholder: __( 'Enter your site key', 'formglut' ) },
      { key: 'formglut_recaptcha_secret_key', type: 'password', label: __( 'Secret key', 'formglut' ), placeholder: __( 'Enter your secret key', 'formglut' ) },
      { key: 'formglut_recaptcha_score', type: 'score', label: __( 'Minimum score', 'formglut' ), tip: __( '0.0 (likely bot) to 1.0 (likely human). Submissions below this score are rejected.', 'formglut' ), show: (s) => s.formglut_recaptcha_version !== 'v2' },
      { key: 'formglut_recaptcha_enabled', type: 'switch', label: __( 'Protect every form', 'formglut' ), tip: __( 'Run reCAPTCHA v3 on all forms, even those without a reCAPTCHA field.', 'formglut' ), show: (s) => s.formglut_recaptcha_version !== 'v2' },
        ],
      },
      {
        key: 'hcaptcha', title: __( 'hCaptcha', 'formglut' ), fields: [
      { key: 'formglut_hcaptcha_site_key', type: 'text', label: __( 'Site key', 'formglut' ), placeholder: __( 'Enter your site key', 'formglut' ) },
      { key: 'formglut_hcaptcha_secret_key', type: 'password', label: __( 'Secret key', 'formglut' ), placeholder: __( 'Enter your secret key', 'formglut' ) },
        ],
      },
      {
        key: 'turnstile', title: __( 'Cloudflare Turnstile', 'formglut' ), fields: [
      { key: 'formglut_turnstile_site_key', type: 'text', label: __( 'Site key', 'formglut' ), placeholder: __( 'Enter your site key', 'formglut' ) },
      { key: 'formglut_turnstile_secret_key', type: 'password', label: __( 'Secret key', 'formglut' ), placeholder: __( 'Enter your secret key', 'formglut' ) },
        ],
      },
    ],
  },
  {
    key: 'payments', title: __( 'Payments', 'formglut' ), icon: faCreditCard, desc: __( 'Payment gateways used by the Payment fields. More gateways can be added here later.', 'formglut' ), subs: [
      {
        key: 'stripe', title: __( 'Stripe', 'formglut' ), desc: __( 'Stripe card payments. Find your keys in the Stripe Dashboard → Developers → API keys.', 'formglut' ), fields: [

      { key: 'formglut_stripe_mode', type: 'select', label: __( 'Stripe mode', 'formglut' ), tip: __( 'Test is the default: use it while you try things out, no real money moves. Switch to Live to take real payments.', 'formglut' ), options: [{ value: 'test', label: __( 'Test', 'formglut' ) }, { value: 'live', label: __( 'Live', 'formglut' ) }] },
      { key: 'formglut_currency', type: 'select', label: __( 'Stripe currency', 'formglut' ), tip: __( 'Default is USD. The currency used for Stripe charges.', 'formglut' ), options: ['USD', 'EUR', 'GBP', 'CAD', 'AUD', 'NZD', 'CHF', 'SEK', 'NOK', 'DKK', 'PLN', 'CZK', 'INR', 'BDT', 'PKR', 'SGD', 'HKD', 'MYR', 'ZAR', 'BRL', 'MXN', 'AED', 'SAR', 'TRY', 'JPY', 'KRW'].map((c) => ({ value: c, label: c })) },
      { key: 'formglut_stripe_test_publishable', type: 'text', label: __( 'Test publishable key', 'formglut' ), placeholder: 'pk_test_…', show: (s) => s.formglut_stripe_mode === 'test' },
      { key: 'formglut_stripe_test_secret', type: 'password', label: __( 'Test secret key', 'formglut' ), placeholder: 'sk_test_…', show: (s) => s.formglut_stripe_mode === 'test' },
      { key: 'formglut_stripe_live_publishable', type: 'text', label: __( 'Live publishable key', 'formglut' ), placeholder: 'pk_live_…', show: (s) => s.formglut_stripe_mode === 'live' },
      { key: 'formglut_stripe_live_secret', type: 'password', label: __( 'Live secret key', 'formglut' ), placeholder: 'sk_live_…', show: (s) => s.formglut_stripe_mode === 'live' },
        ],
      },
    ],
  },
  {
    key: 'integrations', title: __( 'Integrations', 'formglut' ), icon: faPlug, desc: __( 'Accounts used by the forms. Turn each one on per form in Form Settings.', 'formglut' ), subs: [
      {
        key: 'mailchimp', title: __( 'Mailchimp', 'formglut' ), desc: __( 'In Mailchimp: Profile › Extras › API keys › Create A Key. Then pick the audience in Form Settings › Mailchimp.', 'formglut' ), fields: [
      { key: 'formglut_mailchimp_api_key', type: 'password', label: __( 'API key', 'formglut' ), placeholder: '0123456789abcdef0123456789abcdef-us21' },
        ],
      },
    ],
  },
  {
    key: 'ai', title: __( 'AI', 'formglut' ), icon: faWandMagicSparkles, desc: __( 'Build a form from a short description with Claude. Uses your own Anthropic API key; only the description you type is sent.', 'formglut' ), fields: [
      { key: 'formglut_ai_key', type: 'password', label: __( 'Claude API key', 'formglut' ), placeholder: 'sk-ant-…', tip: __( 'Create one at console.anthropic.com › API keys. Anthropic bills the usage to your account.', 'formglut' ) },
      { key: 'formglut_ai_model', type: 'select', label: __( 'Model', 'formglut' ), options: ((window.formglut_admin || {}).ai || {}).models || [{ value: 'claude-sonnet-5-5', label: 'Claude Sonnet 5.5' }] },
    ],
  },
  {
    key: 'appearance', title: __( 'Appearance', 'formglut' ), icon: faPalette, desc: __( 'The accent color used for buttons, the glow around a field you click into, and active states.', 'formglut' ), fields: [
      { key: 'formglut_accent_color', type: 'color', label: __( 'Form accent color', 'formglut' ), tip: __( 'Used by the forms on your site: submit and step buttons, field focus glow, checked choices, progress bars and toggles. A submit button with its own color keeps it.', 'formglut' ) },
      { key: 'formglut_admin_accent_color', type: 'color', label: __( 'Admin accent color', 'formglut' ), tip: __( 'Used by the FormGlut admin screens: buttons, menus, tabs and highlights.', 'formglut' ) },
    ],
  },
  {
    key: 'advanced', title: __( 'Advanced', 'formglut' ), icon: faSliders, desc: __( 'Data handling for the whole plugin.', 'formglut' ), fields: [
      { key: 'formglut_delete_on_uninstall', type: 'switch', label: __( 'Delete data on uninstall', 'formglut' ), tip: __( 'When the plugin is deleted (not just deactivated), remove all forms, entries, uploaded files, logs and settings. This cannot be undone; export your forms and entries first from Data & Logs.', 'formglut' ) },
    ],
  },
];

/**
 * Sections with add-on ones (formglut.globalSettings.sections). A section: { key, title, icon, desc, fields }
 * or { …, subs: [ { key, title, fields } ] }, or { …, render: Component } to draw it yourself.
 * A field: { key, type, label, tip, show(values) }; type 'component' draws field.render({ value, onChange, values }).
 */
const getSections = () => applyFilters('formglut.globalSettings.sections', ALL_SECTIONS.filter((s) => !HIDDEN_SECTIONS.includes(s.key)));

function Input1({ f, value, onChange, values }) {
  switch (f.type) {
    case 'component': return f.render ? f.render({ value, onChange, values }) : null;
    case 'switch': return <Switch checked={!!value} onChange={onChange} />;
    case 'select': return <Select value={value} onChange={onChange} options={f.options} style={{ width: '100%' }} />;
    case 'textarea': return <Input.TextArea rows={3} value={value} onChange={(e) => onChange(e.target.value)} />;
    case 'password': return <Input.Password value={value} placeholder={f.placeholder} autoComplete="new-password" onChange={(e) => onChange(e.target.value)} />;
    case 'color': return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <ColorPicker value={value || DEFAULT_ACCENT} showText disabledAlpha format="hex" onChangeComplete={(c) => onChange(c.toHexString())} />
        {String(value || '').toLowerCase() !== DEFAULT_ACCENT && <Button type="link" size="small" onClick={() => onChange(DEFAULT_ACCENT)}>{__( 'Reset to default', 'formglut' )}</Button>}
      </div>
    );
    case 'score': return <InputNumber min={0} max={1} step={0.1} value={value} onChange={(v) => onChange(v ?? 0)} style={{ width: 140 }} />;
    default: return <Input value={value} placeholder={f.placeholder} onChange={(e) => onChange(e.target.value)} />;
  }
}

export default function Settings() {
  const [values, setValues] = useState(getDefaults);
  const SECTIONS = React.useMemo(getSections, []);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [dirty, setDirty] = useState(false);
  // ?section=<key> opens that section (e.g. the AI builder's "Open settings" link).
  const [active, setActive] = useState(() => new URLSearchParams(window.location.search).get('section') || 'general');
  const [subs, setSubs] = useState({});

  useEffect(() => {
    const { ajax_url, nonce } = window.formglut_admin || {};
    fetch(`${ajax_url}?${new URLSearchParams({ action: 'formglut_get_settings', nonce }).toString()}`)
      .then((r) => r.json())
      .then((result) => { if (result.success && result.data.settings) setValues(normalize(result.data.settings)); })
      .catch(() => message.error(__( 'Failed to load settings.', 'formglut' )))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    const warn = (e) => { if (dirty) { e.preventDefault(); e.returnValue = ''; } };
    window.addEventListener('beforeunload', warn);
    return () => window.removeEventListener('beforeunload', warn);
  }, [dirty]);

  const update = (key, value) => {
    setValues((v) => ({ ...v, [key]: value }));
    setDirty(true);
    // Preview the admin accent right away; it is kept once saved.
    if (key === 'formglut_admin_accent_color') document.documentElement.style.setProperty('--formglut-admin-accent', value || DEFAULT_ACCENT);
  };

  const save = () => {
    const { ajax_url, nonce } = window.formglut_admin || {};
    for (const key of ['formglut_admin_email', 'formglut_sender_email']) {
      if (values[key] && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values[key])) {
        message.error(__( 'Enter a valid email address.', 'formglut' ));
        setActive('email');
        return;
      }
    }
    setSaving(true);
    fetch(ajax_url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ action: 'formglut_save_settings', nonce, settings: JSON.stringify(values) }).toString(),
      credentials: 'same-origin',
    })
      .then((r) => r.json())
      .then((result) => {
        if (result.success) {
          setDirty(false);
          // The SMTP password is never sent back: clear the box and remember that one is saved.
          if (values.formglut_smtp_password) setValues((v) => ({ ...v, formglut_smtp_password: '', formglut_smtp_password_set: true }));
          message.success(__( 'Global settings saved.', 'formglut' ));
        }
        else message.error(result.data?.message || __( 'Failed to save settings.', 'formglut' ));
      })
      .catch(() => message.error(__( 'Network error. Please try again.', 'formglut' )))
      .finally(() => setSaving(false));
  };

  const title = __( 'Global Settings', 'formglut' );

  if (loading) {
    return (
      <div className="fg-fs-page">
        <Header activePage={title} />
        <div className="fg-fs-body" style={{ textAlign: 'center', paddingTop: 80 }}><Spin size="large" /></div>
      </div>
    );
  }

  const section = SECTIONS.find((s) => s.key === active) || SECTIONS[0];
  const subSection = section.subs ? (section.subs.find((x) => x.key === subs[section.key]) || section.subs[0]) : null;
  const rows = ((subSection || section).fields || []).filter((f) => !f.show || f.show(values));
  const SectionBody = (subSection && subSection.render) || section.render;

  return (
    <div className="fg-fs-page">
      <Header activePage={title} />
      <div className="fg-fs-body">
        <div className="fg-fs-top">
          <div className="fg-fs-titlebar">
            <div>
              <div className="fg-page-title">{title}</div>
              <div className="fg-page-subtitle">{__( 'Options that apply to every form. Each form can override many of them in its own Form Settings.', 'formglut' )}</div>
            </div>
            <div className="fg-fs-actions">
              {dirty && <span className="fg-fs-unsaved">{__( 'Unsaved changes', 'formglut' )}</span>}
              <Button type="primary" size="large" loading={saving} disabled={!dirty} icon={<FontAwesomeIcon icon={faFloppyDisk} />} onClick={save} style={{ background: dirty ? 'var(--fg-accent)' : undefined, borderColor: dirty ? 'var(--fg-accent)' : undefined, borderRadius: 8, fontWeight: 600 }}>
                {__( 'Save settings', 'formglut' )}
              </Button>
            </div>
          </div>
        </div>

        <div className="fg-fs-layout">
          <nav className="fg-fs-nav">
            {SECTIONS.map((s) => (
              <button key={s.key} type="button" className={s.key === section.key ? 'active' : ''} onClick={() => setActive(s.key)}>
                <span className="ic"><FontAwesomeIcon icon={s.icon} /></span>
                <span>{s.title}</span>
              </button>
            ))}
          </nav>

          <section className="fg-fs-card">
            <div className="fg-fs-card-head">
              <span className="ic"><FontAwesomeIcon icon={section.icon} /></span>
              <div>
                <h2>{section.title}</h2>
                <p>{section.desc}</p>
              </div>
            </div>

            {section.subs && <Tabs activeKey={subSection.key} onChange={(k) => setSubs((p) => ({ ...p, [section.key]: k }))} items={section.subs.map((x) => ({ key: x.key, label: x.title }))} />}

            {subSection && subSection.desc && <div className="fg-fs-note" style={{ margin: '0 0 14px' }}>{subSection.desc}</div>}

            {SectionBody && <SectionBody values={values} update={update} />}
            {rows.map((f) => (
              <div key={f.key} className={`fg-fs-row ${f.type === 'switch' ? 'is-switch' : ''} ${f.type === 'textarea' ? 'is-wide' : ''}`}>
                <div className="fg-fs-label">
                  <div className="fg-fs-label-line"><label>{f.label}</label></div>
                  {f.tip && <div className="fg-fs-help">{f.tip}</div>}
                </div>
                <div className="fg-fs-control">
                  <Input1 f={f} value={values[f.key]} onChange={(v) => update(f.key, v)} values={values} />
                </div>
              </div>
            ))}

            {section.hint && <div className="fg-fs-note" style={{ margin: '4px 0 18px' }}>{section.hint}</div>}
          </section>
        </div>
      </div>
    </div>
  );
}
