/* global React, Icon, StatusPill, Avatar, fmtAED */
const { useState } = React;

/* ============================================================
   CONTRACTS / PAYMENTS / SETTINGS / CMD-K / BOOKING-PUBLIC
   ============================================================ */

function Contracts({ goto }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div className="page-header">
        <div className="page-header-left">
          <div className="page-eyebrow">Sales</div>
          <h1 className="page-title">Contracts</h1>
        </div>
        <div className="page-header-right">
          <button className="btn"><Icon name="layers" size={12} /> Templates</button>
          <button className="btn btn-primary" onClick={() => goto('contract-editor', 'ct1')}><Icon name="plus" size={12} /> New contract</button>
        </div>
      </div>
      <div style={{ flex: 1, overflow: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
          <thead>
            <tr style={{ borderBottom: '1px solid var(--divider)' }}>
              <th style={th}>Title</th><th style={th}>Counterparty</th>
              <th style={th}>Value</th><th style={th}>Status</th>
              <th style={th}>Sent</th><th style={th}></th>
            </tr>
          </thead>
          <tbody>
            {window.CONTRACTS.map(c => {
              const deal = window.DEALS.find(d => d.id === c.dealId);
              const counterparty = deal ? deal.company : '—';
              const value = deal ? deal.value : 0;
              return (
                <tr key={c.id} onClick={() => goto('contract-editor', c.id)} style={{ borderBottom: '1px solid var(--divider)', cursor: 'pointer' }}>
                  <td style={td}><div style={{ fontWeight: 500, color: 'var(--text)' }}>{c.name}</div></td>
                  <td style={td}>{counterparty}</td>
                  <td style={{...td, fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>AED {fmtAED(value)}</td>
                  <td style={td}><StatusPill status={c.status} /></td>
                  <td style={{...td, fontFamily: 'var(--font-mono)', fontSize: 10 }}>{c.sent || '—'}</td>
                  <td style={td}><Icon name="chevRight" size={13} style={{ color: 'var(--text-dim)' }} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

const th = { padding: '10px 20px', textAlign: 'left', fontSize: 9, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)' };
const td = { padding: '12px 20px', verticalAlign: 'middle', color: 'var(--text-secondary)' };

function ContractEditor({ contractId, goto }) {
  const c = window.CONTRACTS.find(x => x.id === contractId) || window.CONTRACTS[0];
  const deal = window.DEALS.find(d => d.id === c.dealId) || {};
  const counterparty = deal.company || '—';
  const value = deal.value || 0;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', height: '100%', overflow: 'hidden' }}>
      <div style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden', background: 'var(--bg)' }}>
        <div className="page-header">
          <div className="page-header-left">
            <button className="btn btn-ghost btn-sm" style={{ padding: '4px 6px', marginBottom: 6 }} onClick={() => goto('contracts')}>
              <Icon name="chevLeft" size={12} /> Contracts
            </button>
            <h1 className="page-title">{c.name}</h1>
          </div>
          <div className="page-header-right">
            <StatusPill status={c.status} />
            <button className="btn"><Icon name="download" size={12} /> PDF</button>
            <button className="btn btn-primary"><Icon name="send" size={12} /> Send to sign</button>
          </div>
        </div>
        <div style={{ flex: 1, overflow: 'auto', padding: 32, display: 'flex', justifyContent: 'center' }}>
          <div style={{ width: '100%', maxWidth: 720, background: '#fafaf9', color: '#0e0e0e', padding: '60px 64px', boxShadow: '0 0 0 1px var(--divider)', fontFamily: 'Georgia, serif', lineHeight: 1.7 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 40 }}>
              <div style={{ width: 14, height: 14, background: '#22c55e' }}></div>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#525252' }}>Linea Group · Services Agreement</span>
            </div>
            <h1 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 800, fontSize: 36, margin: '0 0 24px', letterSpacing: '-0.02em', lineHeight: 1.1 }}>{c.name}</h1>
            <p style={{ color: '#525252', fontSize: 14 }}>This Agreement is entered into between <strong style={{ color: '#0e0e0e' }}>Linea Group FZE</strong> ("Provider") and <strong style={{ color: '#0e0e0e' }}>{c.counterparty}</strong> ("Client"), effective from the Acceptance Date below.</p>
            <h2 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 700, fontSize: 18, marginTop: 32, marginBottom: 8 }}>1. Scope of Services</h2>
            <p style={{ color: '#525252', fontSize: 14 }}>Provider will deliver funnel design, paid-acquisition setup and email infrastructure as described in the attached Statement of Work.</p>
            <h2 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 700, fontSize: 18, marginTop: 28, marginBottom: 8 }}>2. Fees</h2>
            <p style={{ color: '#525252', fontSize: 14 }}>The total fee for the engagement is <strong style={{ color: '#0e0e0e' }}>AED {fmtAED(value)}</strong>, invoiced according to the schedule in Schedule A.</p>
            <h2 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 700, fontSize: 18, marginTop: 28, marginBottom: 8 }}>3. Term &amp; Termination</h2>
            <p style={{ color: '#525252', fontSize: 14 }}>Either party may terminate with thirty (30) days written notice. Pre-paid fees are non-refundable.</p>
            <div style={{ marginTop: 60, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 40 }}>
              {['Provider · Linea Group', 'Client · ' + counterparty].map((label, i) => (
                <div key={i}>
                  <div style={{ height: 60, borderBottom: '2px solid #0e0e0e', marginBottom: 8, position: 'relative' }}>
                    {i === 0 && c.status !== 'draft' && <span style={{ fontFamily: 'Caveat, cursive', fontSize: 32, color: '#0e0e0e', position: 'absolute', bottom: 4, left: 4 }}>S. Mariotti</span>}
                  </div>
                  <div style={{ fontSize: 11, color: '#525252', fontFamily: 'var(--font-mono)' }}>{label}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div style={{ borderLeft: '1px solid var(--divider)', overflowY: 'auto', padding: 18 }}>
        <div className="label" style={{ marginBottom: 10 }}>Variables</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 22 }}>
          <Field label="Title"        value={c.name} />
          <Field label="Counterparty" value={counterparty} />
          <Field label="Value (AED)"  value={value} />
          <Field label="Term (months)" value="12" />
          <Field label="Effective date" value="May 1, 2026" />
        </div>
        <div className="label" style={{ marginBottom: 10 }}>Signers</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {[
            { name: 'Sebastiano Mariotti', email: 'sebastiano@lineagroup.ae', role: 'Provider', signed: c.status !== 'draft' },
            { name: 'Counterparty signer', email: 'tbd@example.com', role: 'Client', signed: c.status === 'signed' },
          ].map(s => (
            <div key={s.role} style={{ padding: 10, background: 'var(--surface)', border: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 8 }}>
              <Avatar name={s.name} size="sm" color="#737373" />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12, fontWeight: 500, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{s.name}</div>
                <div style={{ fontSize: 10, color: 'var(--text-dim)' }}>{s.role}</div>
              </div>
              {s.signed ? <Icon name="check" size={13} style={{ color: 'var(--green)' }} /> : <Icon name="clock" size={13} style={{ color: 'var(--text-dim)' }} />}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Field({ label, value }) {
  return (
    <div>
      <div className="label" style={{ marginBottom: 4 }}>{label}</div>
      <input className="input" defaultValue={value} />
    </div>
  );
}

/* ============================================================
   PAYMENTS
   ============================================================ */

function Payments({ goto }) {
  const total = window.PAYMENTS.filter(p => p.status === 'paid').reduce((a, p) => a + p.amount, 0);
  const outstanding = window.PAYMENTS.filter(p => p.status !== 'paid').reduce((a, p) => a + p.amount, 0);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div className="page-header">
        <div className="page-header-left">
          <div className="page-eyebrow">Finance</div>
          <h1 className="page-title">Payments</h1>
        </div>
        <div className="page-header-right">
          <button className="btn"><Icon name="download" size={12} /> Export</button>
          <button className="btn btn-primary"><Icon name="plus" size={12} /> New invoice</button>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, padding: '14px 28px', borderBottom: '1px solid var(--divider)' }}>
        <SummaryStat label="Collected · 30d" value={'AED ' + fmtAED(total)} accent />
        <SummaryStat label="Outstanding" value={'AED ' + fmtAED(outstanding)} />
        <SummaryStat label="Overdue" value="AED 0" />
      </div>
      <div style={{ flex: 1, overflow: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
          <thead>
            <tr style={{ borderBottom: '1px solid var(--divider)' }}>
              <th style={th}>Invoice</th><th style={th}>Deal</th>
              <th style={th}>Amount</th><th style={th}>Paid</th>
              <th style={th}>Status</th><th style={th}>Date</th>
            </tr>
          </thead>
          <tbody>
            {window.PAYMENTS.map((p, i) => (
              <tr key={p.id} style={{ borderBottom: '1px solid var(--divider)' }}>
                <td style={{...td, fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>INV-{String(2026000 + i + 1)}</td>
                <td style={td}>{p.deal}</td>
                <td style={{...td, fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>AED {fmtAED(p.amount)}</td>
                <td style={{...td, fontFamily: 'var(--font-mono)', color: p.paid === p.amount ? 'var(--accent)' : 'var(--orange)' }}>AED {fmtAED(p.paid)}</td>
                <td style={td}><StatusPill status={p.status} /></td>
                <td style={{...td, fontFamily: 'var(--font-mono)', fontSize: 10 }}>{p.paidDate || '—'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function SummaryStat({ label, value, accent }) {
  return (
    <div className="card" style={{ padding: 14 }}>
      <div className="label" style={{ marginBottom: 6 }}>{label}</div>
      <div className="mono" style={{ fontSize: 22, color: accent ? 'var(--accent)' : 'var(--text)' }}>{value}</div>
    </div>
  );
}

/* ============================================================
   SETTINGS
   ============================================================ */

function Settings() {
  const [tab, setTab] = useState('channels');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div className="page-header">
        <div className="page-header-left">
          <div className="page-eyebrow">Workspace</div>
          <h1 className="page-title">Settings</h1>
        </div>
      </div>
      <div className="tabs">
        {['channels','templates','branding','team','billing'].map(t => (
          <div key={t} className={`tab ${tab===t?'active':''}`} onClick={() => setTab(t)} style={{ textTransform: 'capitalize' }}>{t}</div>
        ))}
      </div>
      <div style={{ flex: 1, overflow: 'auto', padding: 28 }}>
        {tab === 'channels' && <ChannelsSettings />}
        {tab === 'templates' && <TemplatesSettings />}
        {tab === 'branding' && <BrandingSettings />}
        {tab === 'team' && <TeamSettings />}
        {tab === 'billing' && <BillingSettings />}
      </div>
    </div>
  );
}

function ChannelsSettings() {
  const [channels, setChannels] = React.useState(null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    fetch('/api/channels', { credentials: 'include' })
      .then((r) => r.ok ? r.json() : Promise.reject(r.statusText))
      .then(setChannels)
      .catch((e) => setError(String(e)));
  }, []);

  const TYPE_TO_KIND = {
    LINKEDIN: 'linkedin',
    WHATSAPP: 'whatsapp',
    INSTAGRAM: 'instagram',
    GOOGLE_OAUTH: 'email',
    GOOGLE: 'email',
    OUTLOOK: 'email',
    IMAP: 'email',
  };
  const iconMap = { linkedin: 'linkedinIcon', whatsapp: 'whatsappIcon', instagram: 'instagramIcon', email: 'emailIcon' };
  const colorMap = { linkedin: '#0a66c2', whatsapp: '#25d366', instagram: '#e4405f', email: '#a3a3a3' };

  return (
    <div style={{ maxWidth: 720 }}>
      <h3 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 700, fontSize: 18, margin: '0 0 4px' }}>Connected channels</h3>
      <p style={{ color: 'var(--text-secondary)', fontSize: 13, marginTop: 0 }}>Inboxes, social DMs and email that flow into your unified inbox via Unipile.</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 18 }}>
        {channels === null && !error && (
          <div style={{ padding: 24, textAlign: 'center', color: 'var(--text-dim)', fontSize: 12 }}>Loading…</div>
        )}
        {error && (
          <div style={{ padding: 16, color: 'var(--red)', fontSize: 12 }}>Failed to load channels: {error}</div>
        )}
        {channels && channels.length === 0 && (
          <div style={{ padding: 24, textAlign: 'center', color: 'var(--text-dim)', fontSize: 12 }}>
            No channels connected yet. Add one in Unipile dashboard.
          </div>
        )}
        {channels && channels.map((ch) => {
          const kind = TYPE_TO_KIND[ch.type] || 'email';
          const status = ch.status || 'active';
          const statusColor = status === 'active' || status === 'OK' ? 'var(--green)' : status === 'paused' ? 'var(--text-dim)' : 'var(--text-secondary)';
          return (
            <div key={ch.id} className="card" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 14 }}>
              <Icon name={iconMap[kind] || 'globe'} size={18} style={{ color: colorMap[kind] || 'var(--text-secondary)' }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{ch.name}</div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>
                  <span style={{ textTransform: 'capitalize' }}>{kind}</span> · Unipile id <code className="mono">{ch.unipile_account_id}</code>
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: statusColor }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'currentColor' }}></span>
                <span style={{ textTransform: 'capitalize' }}>{status}</span>
              </div>
              <button className="btn btn-sm" disabled style={{ opacity: 0.5 }}>Configure</button>
            </div>
          );
        })}
        <button className="btn" style={{ alignSelf: 'flex-start', marginTop: 8 }} disabled>
          <Icon name="plus" size={12} /> Add channel (use Unipile dashboard)
        </button>
      </div>
    </div>
  );
}

function TemplatesSettings() {
  const tmpls = [
    { name: 'Cold intro · DTC',     uses: 142, last: '2d ago' },
    { name: 'Cold intro · SaaS',    uses: 87,  last: '5d ago' },
    { name: 'Bump · 3-day',          uses: 211, last: '1d ago' },
    { name: 'Break-up · 7-day',      uses: 167, last: '3d ago' },
    { name: 'Recap · post-discovery', uses: 64, last: '6d ago' },
    { name: 'Proposal sent · nudge', uses: 42,  last: '4d ago' },
  ];
  return (
    <div style={{ maxWidth: 800 }}>
      <h3 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 700, fontSize: 18, margin: '0 0 4px' }}>Email templates</h3>
      <p style={{ color: 'var(--text-secondary)', fontSize: 13, marginTop: 0 }}>Reusable snippets, available across inbox + sequences.</p>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 18 }}>
        {tmpls.map(t => (
          <div key={t.name} className="card" style={{ padding: 14 }}>
            <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 4 }}>{t.name}</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--text-dim)' }}>{t.uses} uses · last {t.last}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function BrandingSettings() {
  return (
    <div style={{ maxWidth: 720 }}>
      <h3 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 700, fontSize: 18, margin: '0 0 4px' }}>Workspace brand</h3>
      <p style={{ color: 'var(--text-secondary)', fontSize: 13, marginTop: 0 }}>Used on funnels, booking pages, documents and contracts.</p>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 18 }}>
        <Field label="Brand name" value="Linea Group" />
        <Field label="Domain" value="lineagroup.ae" />
        <div>
          <div className="label" style={{ marginBottom: 4 }}>Primary color</div>
          <div style={{ display: 'flex', gap: 6 }}>
            {['#22c55e','#0a0a0a','#f97316','#3b82f6','#a855f7'].map(c => (
              <div key={c} style={{ width: 28, height: 28, background: c, border: '1px solid var(--divider)', cursor: 'pointer' }}></div>
            ))}
          </div>
        </div>
        <div>
          <div className="label" style={{ marginBottom: 4 }}>Display font</div>
          <select className="input"><option>Sohne Breit</option><option>Inter Tight</option><option>Söhne</option></select>
        </div>
      </div>

      <h3 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 700, fontSize: 18, margin: '36px 0 4px' }}>Email authentication</h3>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 14 }}>
        {[
          { label: 'SPF',   status: 'pass' },
          { label: 'DKIM',  status: 'pass' },
          { label: 'DMARC', status: 'pass' },
          { label: 'Custom tracking domain', status: 'fail' },
        ].map(r => (
          <div key={r.label} className="card" style={{ padding: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ width: 8, height: 8, background: r.status === 'pass' ? 'var(--green)' : 'var(--orange)' }}></span>
            <span style={{ fontSize: 12, fontWeight: 500, flex: 1 }}>{r.label}</span>
            <span className="mono" style={{ fontSize: 10, color: 'var(--text-dim)', textTransform: 'uppercase' }}>{r.status}</span>
            <button className="btn btn-sm">{r.status === 'pass' ? 'View' : 'Fix'}</button>
          </div>
        ))}
      </div>
    </div>
  );
}

function TeamSettings() {
  const team = [
    { name: 'Sebastiano Mariotti', email: 'sebastiano@lineagroup.ae', role: 'Owner', initials: 'SM', color: '#22c55e' },
    { name: 'Marco Russo',         email: 'marco@lineagroup.ae',     role: 'Admin', initials: 'MR', color: '#3b82f6' },
    { name: 'Layla Saeed',         email: 'layla@lineagroup.ae',     role: 'Closer', initials: 'LS', color: '#f97316' },
  ];
  return (
    <div style={{ maxWidth: 720 }}>
      <h3 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 700, fontSize: 18, margin: '0 0 4px' }}>Team</h3>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 14 }}>
        {team.map(m => (
          <div key={m.email} className="card" style={{ padding: 12, display: 'flex', alignItems: 'center', gap: 12 }}>
            <Avatar name={m.name} initials={m.initials} color={m.color} size="md" />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600 }}>{m.name}</div>
              <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{m.email}</div>
            </div>
            <span className="chip">{m.role}</span>
          </div>
        ))}
        <button className="btn" style={{ alignSelf: 'flex-start', marginTop: 8 }}><Icon name="plus" size={12} /> Invite member</button>
      </div>
    </div>
  );
}

function BillingSettings() {
  return (
    <div style={{ maxWidth: 720 }}>
      <h3 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 700, fontSize: 18, margin: '0 0 4px' }}>Plan</h3>
      <div className="card" style={{ padding: 18, marginTop: 14 }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 12 }}>
          <div>
            <div style={{ fontSize: 18, fontWeight: 600 }}>Suite · Annual</div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 4 }}>3 seats · renews Apr 28, 2027</div>
          </div>
          <div className="mono" style={{ fontSize: 22, color: 'var(--accent)' }}>AED 14,400<span style={{ fontSize: 11, color: 'var(--text-dim)' }}> /yr</span></div>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button className="btn btn-sm">Manage seats</button>
          <button className="btn btn-sm">Update card</button>
          <button className="btn btn-sm">Download invoices</button>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   CMD-K palette
   ============================================================ */

function CmdK({ open, onClose, goto }) {
  const [q, setQ] = useState('');
  const inputRef = React.useRef(null);
  React.useEffect(() => {
    if (open && inputRef.current) inputRef.current.focus();
  }, [open]);
  if (!open) return null;

  const all = [
    { kind: 'nav', label: 'Go to Dashboard', icon: 'dashboard', action: () => goto('dashboard') },
    { kind: 'nav', label: 'Go to Inbox',     icon: 'inbox', action: () => goto('inbox') },
    { kind: 'nav', label: 'Go to Pipeline',  icon: 'pipeline', action: () => goto('pipeline') },
    { kind: 'nav', label: 'Go to Calendar',  icon: 'calendar', action: () => goto('calendar') },
    { kind: 'nav', label: 'Go to Funnels',   icon: 'funnels', action: () => goto('funnels') },
    { kind: 'nav', label: 'Go to Campaigns', icon: 'send', action: () => goto('campaigns') },
    { kind: 'nav', label: 'Go to LinkedIn Campaign', icon: 'linkedinIcon', action: () => goto('linkedin-campaigns') },
    { kind: 'nav', label: 'Go to Documents', icon: 'document', action: () => goto('documents') },
    { kind: 'nav', label: 'Go to Contracts', icon: 'contract', action: () => goto('contracts') },
    { kind: 'nav', label: 'Go to Payments',  icon: 'payments', action: () => goto('payments') },
    { kind: 'nav', label: 'Go to Settings',  icon: 'settings', action: () => goto('settings') },
    { kind: 'create', label: 'New contact',     icon: 'userPlus' },
    { kind: 'create', label: 'New deal',         icon: 'plus' },
    { kind: 'create', label: 'New email campaign',     icon: 'send', action: () => goto('campaigns') },
    { kind: 'create', label: 'New LinkedIn campaign',   icon: 'linkedinIcon', action: () => goto('linkedin-builder', 'li4') },
    { kind: 'create', label: 'New funnel',       icon: 'funnels', action: () => goto('funnel-builder', 'f1') },
    { kind: 'create', label: 'New document',     icon: 'document', action: () => goto('document-builder', 'doc1') },
    { kind: 'create', label: 'New contract',     icon: 'contract', action: () => goto('contract-editor', 'ct1') },
    ...window.CONTACTS.slice(0, 20).map(c => ({ kind: 'contact', label: c.name, sub: c.title + ' · ' + c.company, icon: 'user', action: () => goto('contact', c.id) })),
    ...window.DEALS.map(d => ({ kind: 'deal', label: d.name, sub: 'AED ' + fmtAED(d.value) + ' · ' + d.stage, icon: 'pipeline', action: () => goto('contact', d.contactId) })),
  ];
  const filtered = q
    ? all.filter(x => x.label.toLowerCase().includes(q.toLowerCase()) || (x.sub || '').toLowerCase().includes(q.toLowerCase()))
    : all.slice(0, 14);

  const groups = {};
  filtered.forEach(it => { groups[it.kind] = groups[it.kind] || []; groups[it.kind].push(it); });

  const groupLabels = { nav: 'Navigate', create: 'Create new', contact: 'Contacts', deal: 'Deals' };

  return (
    <>
      <div className="drawer-overlay" onClick={onClose} style={{ background: 'rgba(0,0,0,0.6)' }}></div>
      <div style={{ position: 'fixed', top: 80, left: '50%', transform: 'translateX(-50%)', width: 'min(640px, 92vw)', background: 'var(--surface)', border: '1px solid var(--divider-strong)', boxShadow: '0 24px 80px rgba(0,0,0,0.6)', zIndex: 200, maxHeight: '70vh', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: 14, borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <Icon name="search" size={14} style={{ color: 'var(--text-dim)' }} />
          <input ref={inputRef} className="input" style={{ background: 'transparent', border: 'none', padding: 0, fontSize: 14 }} placeholder="Type a command, contact, deal…" value={q} onChange={e => setQ(e.target.value)} />
          <span className="mono chip">esc</span>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: 8 }}>
          {Object.keys(groups).map(g => (
            <div key={g}>
              <div className="label" style={{ padding: '8px 10px 4px' }}>{groupLabels[g] || g}</div>
              {groups[g].map((it, i) => (
                <div key={i} onClick={() => { it.action && it.action(); onClose(); }} style={{
                  padding: '8px 10px', display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
                }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--raised)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <Icon name={it.icon} size={13} style={{ color: 'var(--text-secondary)' }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, color: 'var(--text)' }}>{it.label}</div>
                    {it.sub && <div style={{ fontSize: 10, color: 'var(--text-dim)' }}>{it.sub}</div>}
                  </div>
                  <Icon name="cornerDownLeft" size={11} style={{ color: 'var(--text-dim)' }} />
                </div>
              ))}
            </div>
          ))}
          {filtered.length === 0 && <div style={{ padding: 24, textAlign: 'center', color: 'var(--text-dim)', fontSize: 12 }}>No results for "{q}"</div>}
        </div>
        <div style={{ padding: '6px 12px', borderTop: '1px solid var(--divider)', display: 'flex', gap: 12, fontSize: 10, color: 'var(--text-dim)' }} className="mono">
          <span><span className="chip">↑↓</span> navigate</span>
          <span><span className="chip">↵</span> select</span>
          <span><span className="chip">⌘K</span> close</span>
        </div>
      </div>
    </>
  );
}

/* ============================================================
   PUBLIC BOOKING PAGE (shown via "Public Booking Page" route)
   ============================================================ */

function BookingPublic({ goto }) {
  const [date, setDate] = useState(28);
  const [slot, setSlot] = useState(null);
  const [confirmed, setConfirmed] = useState(false);
  const slots = ['09:00','09:30','10:00','11:00','14:00','14:30','15:00','16:00','16:30'];
  const days = Array.from({ length: 14 }, (_, i) => 28 + i).map(d => d > 30 ? d - 30 : d);

  return (
    <div style={{ height: '100%', overflow: 'auto', background: 'var(--surface)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 28 }}>
      <div style={{ width: 'min(900px, 100%)', background: 'var(--bg)', border: '1px solid var(--divider)' }}>
        <div style={{ padding: 24, borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 14, height: 14, background: 'var(--accent)' }}></div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>Linea Group · Booking</div>
          <button className="btn btn-ghost btn-sm" style={{ marginLeft: 'auto' }} onClick={() => goto('calendar')}><Icon name="x" size={11} /> Exit preview</button>
        </div>
        {!confirmed ? (
          <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr 200px' }}>
            <div style={{ padding: 28, borderRight: '1px solid var(--divider)' }}>
              <Avatar name="Sebastiano Mariotti" initials="SM" color="#22c55e" size="lg" />
              <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 14 }}>Sebastiano Mariotti</div>
              <h1 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 800, fontSize: 30, margin: '6px 0 14px', letterSpacing: '-0.02em', lineHeight: 1.05 }}>30-min Discovery Call</h1>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 12, color: 'var(--text-secondary)' }}>
                <div style={{ display: 'flex', gap: 8 }}><Icon name="clock" size={13} style={{ color: 'var(--text-dim)' }} /> 30 minutes</div>
                <div style={{ display: 'flex', gap: 8 }}><Icon name="video" size={13} style={{ color: 'var(--text-dim)' }} /> Zoom (auto-generated)</div>
                <div style={{ display: 'flex', gap: 8 }}><Icon name="globe" size={13} style={{ color: 'var(--text-dim)' }} /> Asia/Dubai (GMT+4)</div>
              </div>
              <p style={{ marginTop: 18, fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.6 }}>
                A no-pressure intro. We'll look at your funnel together, identify what's leaking, and decide if it makes sense to keep talking.
              </p>
            </div>
            <div style={{ padding: 28 }}>
              <div className="label" style={{ marginBottom: 12 }}>Pick a date · April 2026</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4 }}>
                {days.map((d, i) => (
                  <div key={i} onClick={() => setDate(d)} style={{
                    aspectRatio: '1', display: 'flex', alignItems: 'center', justifyContent: 'center',
                    border: '1px solid', borderColor: date === d ? 'var(--accent)' : 'var(--divider)',
                    background: date === d ? 'var(--accent-bg)' : 'var(--surface)',
                    color: date === d ? 'var(--accent)' : 'var(--text-secondary)',
                    cursor: 'pointer', fontSize: 13, fontWeight: 500,
                  }} className="mono">{d}</div>
                ))}
              </div>
            </div>
            <div style={{ padding: 28, borderLeft: '1px solid var(--divider)' }}>
              <div className="label" style={{ marginBottom: 12 }}>Pick a time</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                {slots.map(s => (
                  <button key={s} onClick={() => setSlot(s)} className="btn btn-sm" style={{
                    justifyContent: 'center',
                    borderColor: slot === s ? 'var(--accent)' : 'var(--divider)',
                    color: slot === s ? 'var(--accent)' : 'var(--text)',
                    background: slot === s ? 'var(--accent-bg)' : 'var(--surface)',
                  }}>{s}</button>
                ))}
              </div>
              {slot && (
                <button className="btn btn-primary" style={{ width: '100%', marginTop: 14, justifyContent: 'center' }} onClick={() => setConfirmed(true)}>
                  Confirm {date} April · {slot}
                </button>
              )}
            </div>
          </div>
        ) : (
          <div style={{ padding: '60px 40px', textAlign: 'center' }}>
            <div style={{ width: 56, height: 56, background: 'var(--accent-bg)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18, border: '1px solid var(--accent)' }}>
              <Icon name="check" size={26} style={{ color: 'var(--accent)' }} />
            </div>
            <h1 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 800, fontSize: 36, letterSpacing: '-0.02em', margin: '0 0 10px' }}>You're booked.</h1>
            <p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{date} April · {slot} (Asia/Dubai). Calendar invite + Zoom link sent to your inbox.</p>
            <button className="btn" style={{ marginTop: 22 }} onClick={() => goto('calendar')}><Icon name="external" size={11} /> Add to my calendar</button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, {
  Contracts, ContractEditor, Payments, Settings, CmdK, BookingPublic,
});
