// ─── WhatsApp Inbox Page ─────────────────────────────────────────────────────

const WA_STATUS_DOT = {
  connected: '#22c55e', qr_pending: '#f59e0b', connecting: '#3b82f6',
  degraded: '#ef4444', disconnected: '#ef4444', disabled: '#6b7280',
  external: '#a78bfa', unknown: '#94a3b8',
};

function WhatsAppPage() {
  const [waTab, setWaTab] = React.useState('Connector');
  const [convos, setConvos] = React.useState([]);
  const [selected, setSelected] = React.useState(null);
  const [thread, setThread] = React.useState([]);
  const [msgInput, setMsgInput] = React.useState('');
  const [templates, setTemplates] = React.useState([]);
  const [autoJobs, setAutoJobs] = React.useState([]);
  const [tplName, setTplName] = React.useState('');
  const [loading, setLoading] = React.useState(true);
  const [sending, setSending] = React.useState(false);

  // ── Config state ──
  const [cfg, setCfg] = React.useState({
    whatsapp_provider: 'baileys', whatsapp_service_url: 'http://127.0.0.1:3010', whatsapp_session_name: 'primary',
    whatsapp_webhook_secret: '', whatsapp_enabled: true,
    twilio_account_sid: '', twilio_auth_token: '', twilio_whatsapp_number: ''
  });
  const setConfig = k => v => setCfg(p => ({ ...p, [k]: v }));

  // ── Connector state ──
  const [waStatus, setWaStatus] = React.useState(null);
  const [waLoading, setWaLoading] = React.useState(true);
  const [waActionBusy, setWaActionBusy] = React.useState(false);
  const [qrData, setQrData] = React.useState(null);
  const [qrOpen, setQrOpen] = React.useState(false);
  const [qrMsg, setQrMsg] = React.useState('');
  const { toasts, addToast } = C.useToast();

  // ── Fetch WA status ──
  const loadStatus = async () => {
    setWaLoading(true);
    try {
      const res = await fetch('/api/whatsapp/status');
      const data = await res.json();
      setWaStatus(data);
    } catch { setWaStatus({ connection_status: 'degraded', message: 'Could not reach WhatsApp service' }); }
    setWaLoading(false);
  };

  React.useEffect(() => {
    loadStatus();
    Promise.all([
      fetch('/api/whatsapp/conversations').then(r => r.json()).catch(() => []),
      fetch('/api/whatsapp/templates').then(r => r.json()).catch(() => []),
      fetch('/api/automation/jobs').then(r => r.json()).catch(() => []),
      fetch('/api/config').then(r => r.json()).catch(() => ({})),
    ]).then(([c, t, j, configData]) => {
      const cv = Array.isArray(c) ? c : (Array.isArray(c?.items) ? c.items : []);
      const tp = Array.isArray(t) ? t : (Array.isArray(t?.items) ? t.items : []);
      const jb = Array.isArray(j) ? j : (Array.isArray(j?.items) ? j.items : []);
      setConvos(cv);
      setTemplates(tp);
      setAutoJobs(jb.filter(x => x.channel === 'whatsapp'));
      if (cv.length > 0 && !selected) { setSelected(cv[0].phone_number); }
      if (tp.length > 0) setTplName(tp[0].name);
      if (Object.keys(configData).length > 0) {
        setCfg(p => ({ ...p, ...configData }));
      }
      setLoading(false);
    });
  }, []);

  React.useEffect(() => {
    if (!selected) return;
    fetch(`/api/whatsapp/conversations/${encodeURIComponent(selected)}`)
      .then(r => r.json())
      .then(data => setThread(Array.isArray(data.messages) ? data.messages : []))
      .catch(() => setThread([]));
  }, [selected]);

  const send = async () => {
    if (!msgInput.trim() || !selected || sending) return;
    setSending(true);
    try {
      await fetch('/api/whatsapp/messages/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone_number: selected, body_text: msgInput, template_name: null }),
      });
      setThread(p => [...p, { role: 'agent', direction: 'outbound', body_text: msgInput, created_at: new Date().toISOString() }]);
      setMsgInput('');
      fetch(`/api/whatsapp/conversations/${encodeURIComponent(selected)}/read`, { method: 'POST' }).catch(() => {});
    } finally { setSending(false); }
  };

  // ── Connector actions ──
  const handleConnect = async () => {
    setWaActionBusy(true);
    try {
      const res = await fetch('/api/whatsapp/connect', { method: 'POST' });
      const data = await res.json();
      if (res.ok) addToast('WhatsApp connect initiated', 'success');
      else addToast(data.message || 'Connect failed', 'error');
      await loadStatus();
    } catch (e) { addToast('Connect error: ' + e.message, 'error'); }
    setWaActionBusy(false);
  };

  const handleDisconnect = async () => {
    setWaActionBusy(true);
    try {
      const res = await fetch('/api/whatsapp/disconnect', { method: 'POST' });
      const data = await res.json();
      if (res.ok) addToast('WhatsApp disconnected', 'success');
      else addToast(data.message || 'Disconnect failed', 'error');
      await loadStatus();
    } catch (e) { addToast('Disconnect error: ' + e.message, 'error'); }
    setWaActionBusy(false);
  };

  const handleFetchQR = async () => {
    setQrMsg('Loading QR code…');
    setQrData(null);
    setQrOpen(true);
    try {
      const res = await fetch('/api/whatsapp/qr');
      const data = await res.json();
      if (data.status === 'connected') {
        setQrMsg('WhatsApp is already connected!');
        setQrData(null);
        addToast('Already connected', 'success');
      } else if (data.qr_data_url) {
        setQrData(data.qr_data_url);
        setQrMsg('Scan this QR with WhatsApp → Linked Devices → Link a Device');
      } else if (data.qr) {
        setQrData(data.qr);
        setQrMsg('Scan this QR with WhatsApp → Linked Devices → Link a Device');
      } else {
        setQrMsg(data.message || 'QR code not available. Try clicking Connect first.');
      }
    } catch (e) {
      setQrMsg('Failed to fetch QR: ' + e.message);
    }
  };

  // Auto-poll status while QR modal is open
  React.useEffect(() => {
    if (!qrOpen) return;
    const iv = setInterval(async () => {
      try {
        const res = await fetch('/api/whatsapp/status');
        const data = await res.json();
        setWaStatus(data);
        if (data.connection_status === 'connected') {
          setQrOpen(false);
          addToast('WhatsApp connected successfully!', 'success');
        }
      } catch {}
    }, 4000);
    return () => clearInterval(iv);
  }, [qrOpen]);

  const selectedConvo = convos.find(c => c.phone_number === selected);
  const selectedTpl = templates.find(t => t.name === tplName);

  const msgBody = m => m.body_text || m.body || m.message || m.text || m.content || '';
  const msgRole = m => (m.direction === 'outbound' || m.role === 'agent') ? 'agent' : 'user';
  const msgTime = m => {
    const t = m.created_at || m.timestamp;
    if (!t) return '';
    return new Date(t).toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit', hour12: true });
  };

  const connStatus = waStatus?.connection_status || 'unknown';
  const dotColor = WA_STATUS_DOT[connStatus] || WA_STATUS_DOT.unknown;

  return (
    <div>
      <C.ToastContainer toasts={toasts} />
      <C.PageHeader title="WhatsApp Inbox" sub="Manage connections, conversations, follow-ups, and templates" />
      <C.Tabs tabs={['Connector','Messages','Follow-up Jobs','Templates']} active={waTab} onChange={setWaTab} />
      <div style={{ marginTop: 16 }}>

        {/* ─── CONNECTOR TAB ─── */}
        {waTab === 'Connector' && (
          <div style={{ display: 'grid', gap: 20 }}>
            {/* Status overview */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16 }}>
              <C.Stat label="Connection" value={
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ width: 10, height: 10, borderRadius: '50%', background: dotColor, display: 'inline-block', flexShrink: 0, boxShadow: connStatus === 'connected' ? '0 0 8px #22c55e' : 'none' }} />
                  {connStatus.replace(/_/g, ' ')}
                </span>
              } />
              <C.Stat label="Provider" value={waStatus?.provider || '—'} />
              <C.Stat label="Session" value={waStatus?.session_name || '—'} />
              <C.Stat label="Service URL" value={
                <span style={{ fontSize: 11, fontFamily: 'monospace', wordBreak: 'break-all' }}>{waStatus?.service_url || '—'}</span>
              } />
            </div>

            {/* Connection actions */}
            <C.Card title="Connection Management" action={
              <C.Btn variant="ghost" size="sm" onClick={loadStatus} disabled={waLoading}>
                {waLoading ? 'Checking…' : 'Refresh Status'}
              </C.Btn>
            }>
              <div style={{ padding: '16px 20px' }}>
                <div style={{ fontSize: 13, color: '#c8cdd8', marginBottom: 16, lineHeight: 1.6 }}>
                  {connStatus === 'connected' && `✅ WhatsApp is linked and ready on session "${waStatus?.session_name || 'primary'}".`}
                  {connStatus === 'qr_pending' && '⏳ QR is ready. Click "Show QR" and scan it from WhatsApp → Linked Devices.'}
                  {connStatus === 'connecting' && '🔄 Trying to establish the WhatsApp Web session right now…'}
                  {connStatus === 'disabled' && '⛔ WhatsApp automations are disabled in config.'}
                  {connStatus === 'external' && '🔗 Using an external provider instead of the local Baileys sidecar.'}
                  {connStatus === 'degraded' && `⚠️ ${waStatus?.message || 'WhatsApp service is not reachable.'}`}
                  {connStatus === 'disconnected' && '❌ Not connected. Click Connect, then Show QR to scan.'}
                  {connStatus === 'unknown' && 'Click "Refresh Status" to check the current state.'}
                </div>

                <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                  <C.Btn variant="primary" onClick={handleConnect} disabled={waActionBusy || connStatus === 'connected'}>
                    {waActionBusy ? 'Working…' : 'Connect'}
                  </C.Btn>
                  <C.Btn variant="primary" onClick={handleFetchQR} disabled={waActionBusy}
                    style={{ background: 'linear-gradient(135deg, #25D366, #128C7E)', border: 'none' }}>
                    📱 Show QR Code
                  </C.Btn>
                  <C.Btn variant="danger" onClick={handleDisconnect} disabled={waActionBusy || connStatus === 'disconnected' || connStatus === 'disabled'}>
                    Disconnect
                  </C.Btn>
                </div>
              </div>
            </C.Card>

            {/* Quick-start guide */}
            <C.Card title="Setup Guide">
              <div style={{ padding: '16px 20px' }}>
                <ol style={{ margin: 0, paddingLeft: 20, fontSize: 13, color: '#c8cdd8', lineHeight: 2 }}>
                  <li>Make sure the Baileys WhatsApp sidecar service is running (default: <code style={{ color: '#a78bfa', background: 'rgba(167,139,250,0.1)', padding: '2px 6px', borderRadius: 4 }}>http://127.0.0.1:3010</code>)</li>
                  <li>Click <strong style={{ color: '#e8eaef' }}>Connect</strong> to initialize a session</li>
                  <li>Click <strong style={{ color: '#25D366' }}>Show QR Code</strong> — a QR code will appear</li>
                  <li>Open WhatsApp on your phone → <strong style={{ color: '#e8eaef' }}>Settings → Linked Devices → Link a Device</strong></li>
                  <li>Scan the QR code. The status will automatically update to <span style={{ color: '#22c55e', fontWeight: 600 }}>Connected</span></li>
                  <li>You're ready! The agent can now send WhatsApp messages and process follow-ups.</li>
                </ol>
              </div>
            </C.Card>

            {/* WhatsApp Settings */}
            <C.Card title="Service Settings">
              <div style={{ padding: '16px 20px' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 16 }}>
                  <C.Select label="Provider" value={cfg.whatsapp_provider} onChange={setConfig('whatsapp_provider')} options={[{value:'baileys', label:'Baileys QR'}, {value:'twilio', label:'Twilio WhatsApp'}]} />
                  <div style={{ display: 'flex', alignItems: 'flex-end', paddingBottom: 8 }}>
                    <label style={{ display: 'flex', gap: 8, alignItems: 'center', cursor: 'pointer', color: '#e8eaef', fontSize: 13 }}>
                      <input type="checkbox" checked={cfg.whatsapp_enabled} onChange={e => setConfig('whatsapp_enabled')(e.target.checked)} />
                      WhatsApp automations enabled
                    </label>
                  </div>
                  
                  <div style={{ gridColumn: '1 / -1', fontSize: 14, fontWeight: 600, color: '#e8eaef', marginTop: 8 }}>Baileys Config</div>
                  <C.Input label="Service URL" value={cfg.whatsapp_service_url} onChange={setConfig('whatsapp_service_url')} />
                  <C.Input label="Session Name" value={cfg.whatsapp_session_name} onChange={setConfig('whatsapp_session_name')} />
                  <C.Input label="Webhook Secret" type="password" value={cfg.whatsapp_webhook_secret} onChange={setConfig('whatsapp_webhook_secret')} />
                  <div />

                  <div style={{ gridColumn: '1 / -1', fontSize: 14, fontWeight: 600, color: '#e8eaef', marginTop: 8 }}>Twilio Config</div>
                  <C.Input label="Account SID" value={cfg.twilio_account_sid} onChange={setConfig('twilio_account_sid')} />
                  <C.Input label="Auth Token" type="password" value={cfg.twilio_auth_token} onChange={setConfig('twilio_auth_token')} />
                  <C.Input label="WhatsApp Number" value={cfg.twilio_whatsapp_number} onChange={setConfig('twilio_whatsapp_number')} />
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <C.Btn variant="primary" size="sm" onClick={async () => {
                    try {
                      addToast('Saving settings…', 'info');
                      await fetch('/api/config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(cfg) });
                      addToast('Settings saved successfully', 'success');
                      loadStatus();
                    } catch(e) { addToast('Save failed: ' + e.message, 'error'); }
                  }}>Save Settings</C.Btn>
                </div>
              </div>
            </C.Card>
          </div>
        )}

        {/* ─── QR MODAL ─── */}
        {qrOpen && (
          <div style={{
            position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)', zIndex: 9999,
            display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
          }} onClick={() => setQrOpen(false)}>
            <div style={{
              background: '#13161e', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 20,
              padding: 28, maxWidth: 460, width: '100%', boxShadow: '0 30px 70px rgba(0,0,0,0.5)',
            }} onClick={e => e.stopPropagation()}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
                <div>
                  <div style={{ fontSize: 16, fontWeight: 700, color: '#e8eaef' }}>WhatsApp QR Login</div>
                  <div style={{ fontSize: 12, color: '#7b849a', marginTop: 4 }}>{qrMsg}</div>
                </div>
                <C.Btn variant="ghost" size="sm" onClick={() => setQrOpen(false)}>✕</C.Btn>
              </div>

              {/* Status dot in modal */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16, fontSize: 13, color: '#c8cdd8' }}>
                <span style={{ width: 10, height: 10, borderRadius: '50%', background: dotColor, display: 'inline-block', boxShadow: connStatus === 'connected' ? '0 0 8px #22c55e' : 'none' }} />
                Status: {connStatus.replace(/_/g, ' ')}
              </div>

              {qrData ? (
                <div style={{ background: '#fff', borderRadius: 16, padding: 16, textAlign: 'center' }}>
                  <img src={qrData} alt="WhatsApp QR"
                    style={{ width: '100%', maxWidth: 320, height: 'auto', imageRendering: 'pixelated' }} />
                </div>
              ) : (
                <div style={{
                  background: 'rgba(255,255,255,0.03)', borderRadius: 16, padding: 40,
                  textAlign: 'center', fontSize: 14, color: '#5a6375', minHeight: 200,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  border: '1px dashed rgba(255,255,255,0.1)',
                }}>
                  {connStatus === 'connected' ? '✅ Already connected!' : 'Waiting for QR code…'}
                </div>
              )}

              <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
                <C.Btn variant="ghost" onClick={handleFetchQR}>Refresh QR</C.Btn>
                <C.Btn variant="primary" onClick={() => setQrOpen(false)}>Close</C.Btn>
              </div>
            </div>
          </div>
        )}

        {waTab === 'Messages' && (loading ? <C.Spinner /> : (
          <div style={{ display: 'grid', gridTemplateColumns: '280px 1fr 280px', gap: 16, height: 600 }}>
            {/* Conversation list */}
            <C.Card style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
              <div style={{ padding: '12px 14px', borderBottom: '1px solid rgba(255,255,255,0.07)' }}>
                <input placeholder="Search conversations…"
                  style={{ width: '100%', background: '#1a1e28', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 8, color: '#e8eaef', fontSize: 12, padding: '7px 10px', outline: 'none', boxSizing: 'border-box' }} />
              </div>
              <div style={{ overflowY: 'auto', flex: 1 }}>
                {convos.length === 0 ? (
                  <div style={{ padding: '24px 14px', fontSize: 13, color: '#5a6375', fontStyle: 'italic', textAlign: 'center' }}>No conversations yet</div>
                ) : convos.map(c => (
                  <div key={c.phone_number} onClick={() => setSelected(c.phone_number)}
                    style={{ padding: '12px 14px', cursor: 'pointer', borderBottom: '1px solid rgba(255,255,255,0.04)', background: selected === c.phone_number ? 'rgba(90,126,245,0.1)' : 'transparent', transition: 'background 0.1s' }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 3 }}>
                      <span style={{ fontWeight: 700, fontSize: 13, color: '#e8eaef' }}>{c.display_name || c.phone_number}</span>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        {(parseInt(c.unread_count) > 0) && <span style={{ background: '#34d399', color: '#0b0d12', borderRadius: 999, fontSize: 10, fontWeight: 800, padding: '1px 6px' }}>{c.unread_count}</span>}
                        <span style={{ fontSize: 11, color: '#5a6375' }}>{c.last_message_at ? new Date(c.last_message_at).toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit', hour12: true }) : ''}</span>
                      </div>
                    </div>
                    <div style={{ fontSize: 12, color: '#7b849a', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.last_message_preview || '—'}</div>
                    <div style={{ fontSize: 11, color: '#5a6375', marginTop: 2 }}>{c.phone_number}</div>
                  </div>
                ))}
              </div>
            </C.Card>

            {/* Message thread */}
            <C.Card style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
              {selectedConvo ? (
                <div style={{ padding: '12px 16px', borderBottom: '1px solid rgba(255,255,255,0.07)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 14, color: '#e8eaef' }}>{selectedConvo.display_name || selectedConvo.phone_number}</div>
                    <div style={{ fontSize: 12, color: '#7b849a' }}>{selectedConvo.phone_number}</div>
                  </div>
                  <div style={{ display: 'flex', gap: 8 }}>
                    <C.Btn variant="ghost" size="sm">Call</C.Btn>
                    <C.Btn variant="ghost" size="sm">View CRM</C.Btn>
                  </div>
                </div>
              ) : (
                <div style={{ padding: '12px 16px', borderBottom: '1px solid rgba(255,255,255,0.07)', color: '#5a6375', fontSize: 13 }}>Select a conversation</div>
              )}
              <div style={{ flex: 1, overflowY: 'auto', padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
                {thread.map((m, i) => {
                  const role = msgRole(m);
                  return (
                    <div key={i} style={{ display: 'flex', flexDirection: role === 'agent' ? 'row-reverse' : 'row', gap: 8, alignItems: 'flex-end' }}>
                      <div style={{
                        maxWidth: '75%', padding: '9px 13px',
                        borderRadius: role === 'agent' ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
                        background: role === 'agent' ? 'rgba(90,126,245,0.2)' : '#1a1e28',
                        border: `1px solid ${role === 'agent' ? 'rgba(90,126,245,0.3)' : 'rgba(255,255,255,0.07)'}`,
                        fontSize: 13, color: '#e8eaef', lineHeight: 1.5,
                      }}>
                        {msgBody(m)}
                        <div style={{ fontSize: 10, color: '#5a6375', marginTop: 4, textAlign: role === 'agent' ? 'left' : 'right' }}>{msgTime(m)}</div>
                      </div>
                    </div>
                  );
                })}
              </div>
              <div style={{ padding: '10px 14px', borderTop: '1px solid rgba(255,255,255,0.07)', display: 'flex', gap: 8 }}>
                <input value={msgInput} onChange={e => setMsgInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()}
                  placeholder="Type a message…"
                  style={{ flex: 1, background: '#1a1e28', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 8, color: '#e8eaef', fontSize: 13, padding: '8px 12px', outline: 'none', fontFamily: 'inherit' }} />
                <C.Btn variant="primary" onClick={send} disabled={sending}>Send</C.Btn>
              </div>
            </C.Card>

            {/* Template / context panel */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <C.Card title="Message Constructor" style={{ flex: 1 }}>
                <div style={{ padding: '12px 14px', display: 'grid', gap: 10 }}>
                  {templates.length > 0 ? (
                    <>
                      <C.Select label="Template" value={tplName} onChange={setTplName}
                        options={templates.map(t => ({ value: t.name, label: t.label || t.name }))} />
                      {selectedTpl && (
                        <div style={{ fontSize: 12, color: '#7b849a', background: '#1a1e28', borderRadius: 8, padding: '10px 12px', lineHeight: 1.6, border: '1px solid rgba(255,255,255,0.06)' }}>
                          {selectedTpl.body_text || selectedTpl.body || selectedTpl.template || '—'}
                        </div>
                      )}
                      <C.Btn variant="primary" size="sm" onClick={() => setMsgInput(selectedTpl?.body_text || selectedTpl?.body || selectedTpl?.template || '')}>Use Template</C.Btn>
                    </>
                  ) : (
                    <div style={{ fontSize: 13, color: '#5a6375', fontStyle: 'italic' }}>No templates configured.</div>
                  )}
                </div>
              </C.Card>
            </div>
          </div>
        ))}

        {waTab === 'Follow-up Jobs' && (
          <C.Card title="Pending Follow-up Jobs">
            <C.Table cols={['Type','Phone','Scheduled','Status','Label']}
              empty="No follow-up jobs."
              rows={autoJobs.map(j => [
                <C.Badge color={j.trigger === 'booking_reminder' ? 'blue' : j.trigger === 'followup' ? 'purple' : 'amber'}>{(j.trigger || j.type || '').replace(/_/g, ' ')}</C.Badge>,
                <span style={{ fontVariantNumeric: 'tabular-nums' }}>{j.phone_number}</span>,
                <span style={{ fontSize: 12, color: '#7b849a' }}>{j.scheduled_for ? new Date(j.scheduled_for).toLocaleString('en-IN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: true }) : '—'}</span>,
                <C.Badge color={j.status === 'sent' ? 'green' : j.status === 'failed' ? 'red' : 'amber'}>{j.status}</C.Badge>,
                <span style={{ fontSize: 13, color: '#c8cdd8' }}>{j.label || j.template_name || '—'}</span>,
              ])} />
          </C.Card>
        )}

        {waTab === 'Templates' && (
          <div style={{ display: 'grid', gap: 14 }}>
            {templates.length === 0 ? (
              <div style={{ padding: '20px', fontSize: 13, color: '#5a6375', fontStyle: 'italic' }}>No templates configured.</div>
            ) : templates.map(t => (
              <C.Card key={t.name} style={{ padding: '16px 20px' }}>
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 700, color: '#e8eaef' }}>{t.label || t.name}</div>
                    <div style={{ fontSize: 12, color: '#7b849a', marginTop: 2 }}>{t.name}</div>
                    <div style={{ fontSize: 13, color: '#c8cdd8', marginTop: 8, lineHeight: 1.6 }}>{t.body_text || t.body || t.template || '—'}</div>
                  </div>
                  <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                    <C.Btn variant="ghost" size="sm">Edit</C.Btn>
                    <C.Btn variant="ghost" size="sm">Test Send</C.Btn>
                  </div>
                </div>
              </C.Card>
            ))}
            <C.Btn variant="ghost">+ New Template</C.Btn>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { WhatsAppPage });

