/* global React, Icon */
const { useState, useEffect } = React;

/* ============================================================
   WHATSAPP BUSINESS CLOUD API — Settings panel
   Shown inside Settings → Channels.
   Mirrors GHL's WhatsApp page: setup wizard, status, profile, templates.
   ============================================================ */

function WhatsAppCloudSettings() {
  const [status, setStatus] = useState(null);   // { connected, channel? }
  const [error, setError] = useState(null);
  const [busy, setBusy] = useState(false);

  const load = () => {
    fetch('/api/whatsapp-cloud/status', { credentials: 'include' })
      .then((r) => (r.ok ? r.json() : Promise.reject(r.statusText)))
      .then(setStatus)
      .catch((e) => setError(String(e)));
  };

  useEffect(() => { load(); }, []);

  return (
    <div style={{ marginBottom: 32 }}>
      <h3 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 700, fontSize: 18, margin: '0 0 4px' }}>
        WhatsApp Business Cloud API
      </h3>
      <p style={{ color: 'var(--text-secondary)', fontSize: 13, marginTop: 0 }}>
        Connect your WhatsApp number through Meta's official API. Required for templates, broadcasts, and 24h-window replies.
      </p>

      {status === null && !error && (
        <div className="card" style={{ padding: 24, textAlign: 'center', color: 'var(--text-dim)', fontSize: 12 }}>Loading…</div>
      )}
      {error && (
        <div className="card" style={{ padding: 16, color: 'var(--red)', fontSize: 12 }}>Failed to load: {error}</div>
      )}

      {status && !status.connected && (
        <WhatsAppCloudWizard onDone={load} />
      )}
      {status && status.connected && (
        <WhatsAppCloudConnected
          channel={status.channel}
          onUpdate={load}
          busy={busy}
          setBusy={setBusy}
        />
      )}
    </div>
  );
}

/* ============================================================
   SETUP WIZARD — paste creds → list phones → pick → connect
   ============================================================ */

function WhatsAppCloudWizard({ onDone }) {
  const [step, setStep] = useState(1);
  const [appId, setAppId] = useState('');
  const [appSecret, setAppSecret] = useState('');
  const [accessToken, setAccessToken] = useState('');
  const [wabaId, setWabaId] = useState('');
  const [phones, setPhones] = useState([]);
  const [selectedPhoneId, setSelectedPhoneId] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');

  const verifyAndList = async () => {
    setErr('');
    setBusy(true);
    try {
      const r = await fetch('/api/whatsapp-cloud/verify-creds', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ app_id: appId, app_secret: appSecret, access_token: accessToken, waba_id: wabaId }),
      });
      const d = await r.json();
      if (!d.ok) {
        setErr(d.error || 'Verification failed');
        return;
      }
      setPhones(d.phones || []);
      setStep(2);
    } catch (e) {
      setErr(String(e));
    } finally {
      setBusy(false);
    }
  };

  const connect = async () => {
    setErr('');
    setBusy(true);
    try {
      const r = await fetch('/api/whatsapp-cloud/connect', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          app_id: appId,
          app_secret: appSecret,
          access_token: accessToken,
          waba_id: wabaId,
          phone_number_id: selectedPhoneId,
        }),
      });
      const d = await r.json();
      if (!r.ok || !d.ok) {
        setErr(d.detail || 'Connect failed');
        return;
      }
      onDone();
    } catch (e) {
      setErr(String(e));
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="card" style={{ padding: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
        <div style={{
          width: 28, height: 28, borderRadius: 6,
          background: '#25d366', color: '#0a0a0a',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 14, fontWeight: 700,
        }}>
          <Icon name="whatsappIcon" size={16} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Setup wizard</div>
          <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>Step {step} of 2</div>
        </div>
      </div>

      {step === 1 && (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 12 }}>
            <CredField label="Meta App ID" value={appId} onChange={setAppId} placeholder="e.g. 1234567890123456" />
            <CredField label="App Secret" value={appSecret} onChange={setAppSecret} type="password" placeholder="32-char hex string" />
          </div>
          <CredField label="System User Access Token" value={accessToken} onChange={setAccessToken} type="password" placeholder="EAAxxxx... (long-lived token)" />
          <CredField label="WhatsApp Business Account ID (WABA)" value={wabaId} onChange={setWabaId} placeholder="Numeric ID from WhatsApp Manager" />

          {err && (
            <div style={{ marginTop: 12, padding: 10, background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.4)', color: '#ef4444', fontSize: 12 }}>
              {err}
            </div>
          )}

          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 16 }}>
            <button
              className="btn btn-primary"
              onClick={verifyAndList}
              disabled={busy || !appId || !appSecret || !accessToken || !wabaId}
            >
              {busy ? 'Verifying…' : 'Verify and load phones'}
            </button>
          </div>

          <details style={{ marginTop: 18 }}>
            <summary style={{ fontSize: 11, color: 'var(--text-dim)', cursor: 'pointer' }}>Where do I find these?</summary>
            <div style={{ fontSize: 11, color: 'var(--text-secondary)', lineHeight: 1.6, marginTop: 8 }}>
              <strong>App ID + App Secret:</strong> developers.facebook.com → your app → Settings → Basic.<br />
              <strong>System User Access Token:</strong> business.facebook.com → Business Settings → System Users → generate token with permissions <code>whatsapp_business_messaging</code> + <code>whatsapp_business_management</code>. Pick "Never" for expiry.<br />
              <strong>WABA ID:</strong> business.facebook.com → WhatsApp Accounts → click the account → ID in the URL or top header.
            </div>
          </details>
        </>
      )}

      {step === 2 && (
        <>
          <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 12 }}>
            Found {phones.length} phone {phones.length === 1 ? 'number' : 'numbers'} on this WABA. Pick one to connect.
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 16 }}>
            {phones.map((p) => (
              <label
                key={p.id}
                className="card"
                style={{
                  padding: 12,
                  cursor: 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  gap: 12,
                  border: selectedPhoneId === p.id ? '1px solid var(--accent)' : undefined,
                  background: selectedPhoneId === p.id ? 'rgba(34,197,94,0.06)' : undefined,
                }}
              >
                <input
                  type="radio"
                  name="phone"
                  value={p.id}
                  checked={selectedPhoneId === p.id}
                  onChange={() => setSelectedPhoneId(p.id)}
                  style={{ accentColor: 'var(--accent)' }}
                />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{p.display_phone_number}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>
                    {p.verified_name || '(no display name)'}
                    {p.code_verification_status ? ` · ${p.code_verification_status}` : ''}
                  </div>
                </div>
                {p.quality_rating && (
                  <QualityChip rating={p.quality_rating} />
                )}
              </label>
            ))}
          </div>

          {err && (
            <div style={{ padding: 10, background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.4)', color: '#ef4444', fontSize: 12, marginBottom: 12 }}>
              {err}
            </div>
          )}

          <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
            <button className="btn" onClick={() => setStep(1)} disabled={busy}>Back</button>
            <button className="btn btn-primary" onClick={connect} disabled={busy || !selectedPhoneId}>
              {busy ? 'Connecting…' : 'Connect'}
            </button>
          </div>
        </>
      )}
    </div>
  );
}

function CredField({ label, value, onChange, type = 'text', placeholder }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginTop: 12 }}>
      <label style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)' }}>{label}</label>
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        className="input"
        style={{ fontFamily: type === 'password' ? 'var(--font-mono)' : undefined }}
      />
    </div>
  );
}

function QualityChip({ rating }) {
  const palette = {
    GREEN: { bg: 'rgba(34,197,94,0.12)', fg: '#22c55e', label: 'Green' },
    YELLOW: { bg: 'rgba(234,179,8,0.12)', fg: '#eab308', label: 'Yellow' },
    RED: { bg: 'rgba(239,68,68,0.12)', fg: '#ef4444', label: 'Red' },
    UNKNOWN: { bg: 'rgba(140,140,140,0.12)', fg: '#8d8d8d', label: '—' },
  };
  const p = palette[rating] || palette.UNKNOWN;
  return (
    <span style={{ padding: '4px 10px', borderRadius: 4, background: p.bg, color: p.fg, fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
      {p.label}
    </span>
  );
}

/* ============================================================
   CONNECTED STATE — status, profile, templates, disconnect
   ============================================================ */

function WhatsAppCloudConnected({ channel, onUpdate, busy, setBusy }) {
  const webhookUrl = `${window.location.origin}/api/whatsapp-cloud/webhook`;

  const sync = async () => {
    setBusy(true);
    try {
      const r = await fetch('/api/whatsapp-cloud/sync', { method: 'POST', credentials: 'include' });
      const d = await r.json();
      if (!d.ok) {
        window.alert('Sync failed');
      }
      onUpdate();
    } finally {
      setBusy(false);
    }
  };

  const disconnect = async () => {
    if (!window.confirm('Disconnect WhatsApp Cloud API? Outbound messages will stop until reconnected. (Existing inbound history is kept.)')) return;
    setBusy(true);
    try {
      await fetch('/api/whatsapp-cloud/disconnect', { method: 'POST', credentials: 'include' });
      onUpdate();
    } finally {
      setBusy(false);
    }
  };

  const copy = (text) => {
    navigator.clipboard.writeText(text);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Top status card */}
      <div className="card" style={{ padding: 18, display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{
          width: 40, height: 40, borderRadius: 6,
          background: '#25d366', color: '#0a0a0a',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="whatsappIcon" size={22} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 700 }}>{channel.meta_phone_display || '(unverified)'}</div>
          <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>
            {channel.meta_verified_name || channel.name}
            {channel.meta_messaging_limit ? ` · ${channel.meta_messaging_limit.replace('TIER_', 'Tier ')}` : ''}
          </div>
        </div>
        {channel.meta_quality_rating && <QualityChip rating={channel.meta_quality_rating} />}
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: 'var(--green)' }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'currentColor' }}></span>
          <span>Active</span>
        </div>
      </div>

      {/* Identifier row */}
      <div className="card" style={{ padding: 14 }}>
        <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)', marginBottom: 8 }}>Meta IDs</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, fontSize: 12 }}>
          <div>
            <div style={{ fontSize: 10, color: 'var(--text-dim)' }}>WABA ID</div>
            <code className="mono" style={{ fontSize: 11 }}>{channel.meta_waba_id}</code>
          </div>
          <div>
            <div style={{ fontSize: 10, color: 'var(--text-dim)' }}>Phone Number ID</div>
            <code className="mono" style={{ fontSize: 11 }}>{channel.meta_phone_number_id}</code>
          </div>
          <div>
            <div style={{ fontSize: 10, color: 'var(--text-dim)' }}>App ID</div>
            <code className="mono" style={{ fontSize: 11 }}>{channel.meta_app_id}</code>
          </div>
          <div>
            <div style={{ fontSize: 10, color: 'var(--text-dim)' }}>Last sync</div>
            <span>{channel.meta_last_synced_at ? new Date(channel.meta_last_synced_at).toLocaleString() : '—'}</span>
          </div>
        </div>
      </div>

      {/* Webhook config */}
      <div className="card" style={{ padding: 14 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
          <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)' }}>Webhook configuration</div>
          <span style={{ fontSize: 11, color: channel.meta_webhook_subscribed ? 'var(--green)' : '#eab308' }}>
            {channel.meta_webhook_subscribed ? '● Subscribed to WABA' : '● Not subscribed'}
          </span>
        </div>
        <p style={{ fontSize: 12, color: 'var(--text-secondary)', marginTop: 0 }}>
          In Meta App → WhatsApp → Configuration, paste these into the Webhook fields:
        </p>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
          <span style={{ fontSize: 10, color: 'var(--text-dim)', width: 110 }}>Callback URL</span>
          <code className="mono" style={{ fontSize: 11, flex: 1, padding: '6px 8px', background: 'var(--surface-2, rgba(255,255,255,0.04))' }}>{webhookUrl}</code>
          <button className="btn btn-sm" onClick={() => copy(webhookUrl)}>Copy</button>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ fontSize: 10, color: 'var(--text-dim)', width: 110 }}>Verify token</span>
          <code className="mono" style={{ fontSize: 11, flex: 1, padding: '6px 8px', background: 'var(--surface-2, rgba(255,255,255,0.04))' }}>{channel.meta_webhook_verify_token}</code>
          <button className="btn btn-sm" onClick={() => copy(channel.meta_webhook_verify_token)}>Copy</button>
        </div>
        <div style={{ marginTop: 10, fontSize: 11, color: 'var(--text-dim)' }}>
          Subscribe to webhook fields: <code>messages</code>. Then click "Verify and Save" in Meta. After it's green, refresh status here.
        </div>
      </div>

      {/* Profile editor */}
      <ProfileEditor profile={channel.meta_business_profile || {}} onSaved={onUpdate} />

      {/* Templates */}
      <TemplatesPanel onSync={sync} busy={busy} />

      {/* Bottom actions */}
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, marginTop: 4 }}>
        <button className="btn btn-sm" onClick={sync} disabled={busy}>{busy ? 'Syncing…' : 'Sync now'}</button>
        <button className="btn btn-sm" onClick={disconnect} disabled={busy} style={{ color: '#ef4444' }}>Disconnect</button>
      </div>
    </div>
  );
}

function ProfileEditor({ profile, onSaved }) {
  const [open, setOpen] = useState(false);
  const [draft, setDraft] = useState({
    about: profile.about || '',
    description: profile.description || '',
    address: profile.address || '',
    email: profile.email || '',
    vertical: profile.vertical || '',
    websites: (profile.websites || []).join('\n'),
  });
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');

  useEffect(() => {
    setDraft({
      about: profile.about || '',
      description: profile.description || '',
      address: profile.address || '',
      email: profile.email || '',
      vertical: profile.vertical || '',
      websites: (profile.websites || []).join('\n'),
    });
  }, [profile]);

  const save = async () => {
    setErr('');
    setBusy(true);
    try {
      const websites = draft.websites.split('\n').map((s) => s.trim()).filter(Boolean).slice(0, 2);
      const body = { ...draft, websites };
      const r = await fetch('/api/whatsapp-cloud/profile', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify(body),
      });
      const d = await r.json();
      if (!r.ok) {
        setErr(d.detail || 'Save failed');
        return;
      }
      setOpen(false);
      onSaved();
    } catch (e) {
      setErr(String(e));
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="card" style={{ padding: 14 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: open ? 12 : 0 }}>
        <div>
          <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)' }}>Business profile</div>
          {!open && (
            <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginTop: 4 }}>
              {profile.about ? `"${profile.about}"` : 'No "about" text yet'}
              {profile.vertical ? ` · ${profile.vertical}` : ''}
            </div>
          )}
        </div>
        <button className="btn btn-sm" onClick={() => setOpen((v) => !v)}>{open ? 'Cancel' : 'Edit'}</button>
      </div>

      {open && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <CredField label="About (max 139 chars)" value={draft.about} onChange={(v) => setDraft({ ...draft, about: v.slice(0, 139) })} />
          <CredField label="Description (max 256 chars)" value={draft.description} onChange={(v) => setDraft({ ...draft, description: v.slice(0, 256) })} />
          <CredField label="Address" value={draft.address} onChange={(v) => setDraft({ ...draft, address: v })} />
          <CredField label="Email" value={draft.email} onChange={(v) => setDraft({ ...draft, email: v })} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <label style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)' }}>Vertical</label>
            <select className="input" value={draft.vertical} onChange={(e) => setDraft({ ...draft, vertical: e.target.value })}>
              <option value="">—</option>
              {['AUTO','BEAUTY','APPAREL','EDU','ENTERTAIN','EVENT_PLAN','FINANCE','GROCERY','GOVT','HOTEL','HEALTH','NONPROFIT','PROF_SERVICES','RETAIL','TRAVEL','RESTAURANT','OTHER'].map((v) => (
                <option key={v} value={v}>{v}</option>
              ))}
            </select>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <label style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)' }}>Websites (max 2, one per line)</label>
            <textarea
              rows={2}
              className="input"
              value={draft.websites}
              onChange={(e) => setDraft({ ...draft, websites: e.target.value })}
              placeholder="https://lineagroup.ae"
            />
          </div>

          {err && (
            <div style={{ padding: 10, background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.4)', color: '#ef4444', fontSize: 12 }}>{err}</div>
          )}

          <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <button className="btn btn-primary" onClick={save} disabled={busy}>{busy ? 'Saving…' : 'Save profile'}</button>
          </div>
        </div>
      )}
    </div>
  );
}

function TemplatesPanel({ onSync, busy }) {
  const [templates, setTemplates] = useState(null);
  const [creating, setCreating] = useState(false);

  const load = () => {
    fetch('/api/whatsapp-cloud/templates', { credentials: 'include' })
      .then((r) => (r.ok ? r.json() : { items: [] }))
      .then((d) => setTemplates(d.items || []));
  };

  useEffect(() => { load(); }, []);

  const STATUS_COLORS = {
    APPROVED: { bg: 'rgba(34,197,94,0.12)', fg: '#22c55e' },
    PENDING:  { bg: 'rgba(234,179,8,0.12)', fg: '#eab308' },
    REJECTED: { bg: 'rgba(239,68,68,0.12)', fg: '#ef4444' },
    DISABLED: { bg: 'rgba(140,140,140,0.12)', fg: '#8d8d8d' },
    PAUSED:   { bg: 'rgba(140,140,140,0.12)', fg: '#8d8d8d' },
    IN_APPEAL:{ bg: 'rgba(234,179,8,0.12)', fg: '#eab308' },
  };

  return (
    <div className="card" style={{ padding: 14 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
        <div>
          <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)' }}>Templates</div>
          <div style={{ fontSize: 12, color: 'var(--text-secondary)' }}>
            {templates === null ? 'Loading…' : `${templates.length} synced from Meta`}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button className="btn btn-sm" onClick={() => { onSync(); setTimeout(load, 1500); }} disabled={busy}>
            {busy ? 'Syncing…' : 'Sync templates'}
          </button>
          <button className="btn btn-primary btn-sm" onClick={() => setCreating(true)}>
            + Create template
          </button>
        </div>
      </div>
      {templates && templates.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {templates.map((t) => {
            const s = STATUS_COLORS[t.status] || STATUS_COLORS.PENDING;
            return (
              <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderTop: '1px solid var(--divider)' }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12, fontWeight: 600 }}>{t.name}</div>
                  <div style={{ fontSize: 10, color: 'var(--text-dim)' }}>
                    {t.category} · {t.language}
                    {t.rejection_reason ? ` · ${t.rejection_reason}` : ''}
                  </div>
                </div>
                <span style={{
                  padding: '3px 8px', borderRadius: 4,
                  background: s.bg, color: s.fg,
                  fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em',
                }}>
                  {t.status}
                </span>
              </div>
            );
          })}
        </div>
      )}
      {templates && templates.length === 0 && (
        <div style={{ padding: 16, textAlign: 'center', color: 'var(--text-dim)', fontSize: 12 }}>
          No templates yet. Click "Create template" above. Meta reviews in 24-48h.
        </div>
      )}
      {creating && (
        <CreateTemplateModal
          onClose={() => setCreating(false)}
          onCreated={() => { setCreating(false); load(); }}
        />
      )}
    </div>
  );
}

function CreateTemplateModal({ onClose, onCreated }) {
  const [name, setName] = useState('');
  const [language, setLanguage] = useState('en');
  const [category, setCategory] = useState('MARKETING');
  const [headerType, setHeaderType] = useState('NONE'); // NONE | TEXT
  const [headerText, setHeaderText] = useState('');
  const [body, setBody] = useState('');
  const [footer, setFooter] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');

  const variableCount = (body.match(/\{\{\d+\}\}/g) || []).length;
  const sortedVars = Array.from({ length: variableCount }, (_, i) => `{{${i + 1}}}`);
  const sampleValues = sortedVars.map((_, i) => `Sample${i + 1}`);

  const submit = async () => {
    setErr('');
    if (!/^[a-z0-9_]+$/.test(name)) {
      setErr('Name must be lowercase letters, numbers, underscores only (e.g. discovery_call_v1)');
      return;
    }
    if (!body.trim()) {
      setErr('Body required');
      return;
    }
    const components = [];
    if (headerType === 'TEXT' && headerText.trim()) {
      components.push({ type: 'HEADER', format: 'TEXT', text: headerText.trim() });
    }
    const bodyComponent = { type: 'BODY', text: body.trim() };
    if (variableCount > 0) {
      bodyComponent.example = { body_text: [sampleValues] };
    }
    components.push(bodyComponent);
    if (footer.trim()) {
      components.push({ type: 'FOOTER', text: footer.trim() });
    }
    setBusy(true);
    try {
      const r = await fetch('/api/whatsapp-cloud/templates', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ name, language, category, components }),
      });
      const d = await r.json();
      if (!r.ok) {
        setErr(d.detail || 'Create failed');
        return;
      }
      onCreated();
    } catch (e) {
      setErr(String(e));
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{
      position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
      background: 'rgba(0,0,0,0.65)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      zIndex: 200,
    }}
      onClick={onClose}
    >
      <div onClick={(e) => e.stopPropagation()} style={{
        background: 'var(--surface)', border: '1px solid var(--divider)',
        width: 640, maxHeight: '90vh', overflowY: 'auto', padding: 24,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
          <div>
            <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 700, fontSize: 20 }}>Create WhatsApp template</h3>
            <p style={{ margin: '4px 0 0', fontSize: 12, color: 'var(--text-dim)' }}>
              Submitted to Meta for review. APPROVED in 24-48h, then usable from the inbox.
            </p>
          </div>
          <button className="btn btn-sm" onClick={onClose}>×</button>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 10, marginBottom: 12 }}>
          <div>
            <Label>Name (snake_case, no spaces)</Label>
            <input className="input" value={name} onChange={(e) => setName(e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, ''))} placeholder="discovery_call_v1" />
          </div>
          <div>
            <Label>Language</Label>
            <select className="input" value={language} onChange={(e) => setLanguage(e.target.value)}>
              <option value="en">en</option>
              <option value="en_US">en_US</option>
              <option value="ar">ar</option>
              <option value="it">it</option>
            </select>
          </div>
          <div>
            <Label>Category</Label>
            <select className="input" value={category} onChange={(e) => setCategory(e.target.value)}>
              <option value="MARKETING">MARKETING</option>
              <option value="UTILITY">UTILITY</option>
              <option value="AUTHENTICATION">AUTHENTICATION</option>
            </select>
          </div>
        </div>

        <div style={{ marginBottom: 12 }}>
          <Label>Header (optional)</Label>
          <div style={{ display: 'flex', gap: 8 }}>
            <select className="input" value={headerType} onChange={(e) => setHeaderType(e.target.value)} style={{ width: 140 }}>
              <option value="NONE">None</option>
              <option value="TEXT">Text</option>
            </select>
            {headerType === 'TEXT' && (
              <input className="input" value={headerText} onChange={(e) => setHeaderText(e.target.value)} placeholder="Header text (60 char max)" maxLength={60} style={{ flex: 1 }} />
            )}
          </div>
        </div>

        <div style={{ marginBottom: 12 }}>
          <Label>Body * (use {`{{1}}`}, {`{{2}}`} for variables, max 1024 chars)</Label>
          <textarea
            className="textarea"
            value={body}
            onChange={(e) => setBody(e.target.value)}
            placeholder={`Hi {{1}}, I'm Sebastiano from Linea Group. I help GCC brands grow online sales. Open for a 15-min chat next week?`}
            maxLength={1024}
            rows={6}
            style={{ width: '100%', fontFamily: 'var(--font-body)', fontSize: 13 }}
          />
          <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 4 }}>
            {body.length} / 1024 chars · {variableCount} variable{variableCount === 1 ? '' : 's'} detected
          </div>
        </div>

        <div style={{ marginBottom: 12 }}>
          <Label>Footer (optional, 60 char max)</Label>
          <input className="input" value={footer} onChange={(e) => setFooter(e.target.value)} placeholder="Linea Group · lineagroup.ae" maxLength={60} />
        </div>

        <div style={{ background: 'var(--bg)', border: '1px solid var(--divider)', padding: 12, marginBottom: 12 }}>
          <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)', marginBottom: 6 }}>Preview</div>
          {headerType === 'TEXT' && headerText && (
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text)', marginBottom: 6 }}>{headerText}</div>
          )}
          <div style={{ fontSize: 13, color: 'var(--text)', whiteSpace: 'pre-wrap', marginBottom: footer ? 6 : 0 }}>
            {body || <span style={{ color: 'var(--text-dim)' }}>(body)</span>}
          </div>
          {footer && <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{footer}</div>}
        </div>

        {err && (
          <div style={{ padding: 10, background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.4)', color: '#ef4444', fontSize: 12, marginBottom: 12 }}>
            {err}
          </div>
        )}

        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <button className="btn" onClick={onClose} disabled={busy}>Cancel</button>
          <button className="btn btn-primary" onClick={submit} disabled={busy || !name || !body}>
            {busy ? 'Submitting…' : 'Submit for review'}
          </button>
        </div>
      </div>
    </div>
  );
}

function Label({ children }) {
  return (
    <label style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)', display: 'block', marginBottom: 4 }}>
      {children}
    </label>
  );
}

Object.assign(window, { WhatsAppCloudSettings });
