// CRM — Pipeline (drag), Customers, Deal detail

function CRM() {
  const D = window.HitcentsData;
  const [view, setView] = useState('pipeline');
  const [deals, setDeals] = useState(D.DEALS);
  const [openDeal, setOpenDeal] = useState(null);
  const [openCustomer, setOpenCustomer] = useState(null);
  const [openContact, setOpenContact] = useState(null);
  const [drag, setDrag] = useState(null);
  const [hoverStage, setHoverStage] = useState(null);
  const [newDealOpen, setNewDealOpen] = useState(false);
  const [newCompanyOpen, setNewCompanyOpen] = useState(false);
  const [newContactOpen, setNewContactOpen] = useState(false);
  const [, forceBump] = useState(0); // re-render after pushing to D.CUSTOMERS / D.CONTACTS
  const [logActivityOpen, setLogActivityOpen] = useState(false);

  useEffect(() => {
    function onOpen(e) {
      if (e.detail?.type === 'customer') {
        const c = D.CUSTOMERS.find(x => x.id === e.detail.id);
        if (c) setOpenCustomer(c);
      }
      if (e.detail?.type === 'contact') {
        const c = (D.CONTACTS || []).find(x => x.id === e.detail.id);
        if (c) setOpenContact(c);
      }
    }
    window.addEventListener('hitcents:open', onOpen);
    return () => window.removeEventListener('hitcents:open', onOpen);
  }, []);

  const totals = useMemo(() => {
    const open = deals.filter(d => !['won','lost'].includes(d.stage)).reduce((s,d) => s + d.value, 0);
    const weighted = deals.filter(d => !['won','lost'].includes(d.stage)).reduce((s,d) => s + d.value * (d.probability/100), 0);
    const won = deals.filter(d => d.stage === 'won').reduce((s,d) => s + d.value, 0);
    const count = deals.filter(d => !['won','lost'].includes(d.stage)).length;
    return { open, weighted, won, count };
  }, [deals]);

  function moveDeal(id, stage) {
    setDeals(ds => ds.map(d => d.id === id ? { ...d, stage } : d));
  }

  return (
    <div data-screen-label="CRM">
      <div className="page-head">
        <div>
          <h1>CRM</h1>
          <div className="sub">{totals.count} open deals · pipeline {fmtMoneyFull(totals.open)} · weighted {fmtMoneyFull(Math.round(totals.weighted))}</div>
        </div>
        <div className="row gap-2">
          <Button variant="secondary" icon="filter">Filters</Button>
          <Button variant="primary" icon="plus" onClick={() => setNewDealOpen(true)}>New deal</Button>
        </div>
      </div>

      <div className="grid g-4" style={{ marginBottom: 18, gap: 12 }}>
        <Kpi label="Open pipeline" value={fmtMoney(totals.open)} delta={`${totals.count} deals`} />
        <Kpi label="Weighted" value={fmtMoney(Math.round(totals.weighted))} delta="probability-adjusted" />
        <Kpi label="Closed won — May" value={fmtMoney(totals.won)} delta="1 deal · Marigold" tone="up" />
        <Kpi label="Average deal" value={fmtMoney(Math.round(totals.open / Math.max(totals.count, 1)))} delta="across all stages" />
      </div>

      <div className="tabs" style={{ marginBottom: 16 }}>
        <button className={`tab ${view === 'pipeline' ? 'active' : ''}`} onClick={() => setView('pipeline')}>Pipeline</button>
        <button className={`tab ${view === 'deals' ? 'active' : ''}`} onClick={() => setView('deals')}>Deals</button>
      </div>

      {view === 'pipeline' && (
        <div className="pipeline">
          {D.DEAL_STAGES.map(stage => {
            const stageDeals = deals.filter(d => d.stage === stage.id);
            const stageVal = stageDeals.reduce((s,d) => s + d.value, 0);
            const isHover = hoverStage === stage.id;
            return (
              <div key={stage.id}
                   className={`pipeline-col ${isHover ? 'drop-target' : ''}`}
                   style={isHover ? { background: 'var(--brand-orange-tint)' } : null}
                   onDragOver={e => { e.preventDefault(); setHoverStage(stage.id); }}
                   onDragLeave={() => setHoverStage(h => h === stage.id ? null : h)}
                   onDrop={() => { if (drag) moveDeal(drag, stage.id); setDrag(null); setHoverStage(null); }}>
                <div className="pipeline-col-h">
                  <div className="row gap-2">
                    <div className="pipeline-stage-dot" style={{ background: stage.color }} />
                    <strong style={{ fontSize: 12.5 }}>{stage.name}</strong>
                    <span className="dim mono" style={{ fontSize: 11 }}>{stageDeals.length}</span>
                  </div>
                  <span className="muted mono" style={{ fontSize: 11 }}>{fmtMoney(stageVal)}</span>
                </div>
                {stageDeals.map(d => {
                  const cust = d.customer ? getCustomer(d.customer) : null;
                  const owner = getEmployee(d.owner);
                  return (
                    <div key={d.id}
                         className={`deal-card ${drag === d.id ? 'dragging' : ''}`}
                         draggable
                         onDragStart={() => setDrag(d.id)}
                         onDragEnd={() => { setDrag(null); setHoverStage(null); }}
                         onClick={() => setOpenDeal(d)}>
                      <div className="name">{d.name}</div>
                      <div className="muted" style={{ fontSize: 11.5 }}>{cust?.name || d.customerName}</div>
                      <div className="meta">
                        <span className="mono" style={{ color: 'var(--brand-wine)', fontWeight: 500, fontSize: 12 }}>{fmtMoney(d.value)}</span>
                        <div className="row gap-2">
                          <span style={{ fontSize: 10.5 }}>{d.probability}%</span>
                          <Avatar person={owner} size={18} />
                        </div>
                      </div>
                    </div>
                  );
                })}
                {stageDeals.length === 0 && <div className="dim" style={{ fontSize: 11.5, padding: 8, textAlign: 'center' }}>Drop here</div>}
              </div>
            );
          })}
        </div>
      )}

      {view === 'deals' && (
        <DealsList deals={deals} onOpenDeal={setOpenDeal} onOpenCompany={setOpenCustomer} />
      )}

      {view === 'forecast' && <Forecast deals={deals} />}
      {view === 'activity' && <CRMActivity onLogActivity={() => setLogActivityOpen({})} />}


      <Drawer open={!!openDeal} onClose={() => setOpenDeal(null)} title="Deal" width={560}>
        {openDeal && <DealDetail deal={openDeal} onMoveStage={(stage) => { moveDeal(openDeal.id, stage); setOpenDeal({ ...openDeal, stage }); }} onOpenCustomer={(c) => { setOpenCustomer(c); setOpenDeal(null); }} onLogActivity={() => setLogActivityOpen({ dealId: openDeal.id })} />}
      </Drawer>
      <Drawer open={!!openCustomer} onClose={() => setOpenCustomer(null)} title="Company" width={580}>
        {openCustomer && <CustomerDetail customer={openCustomer} deals={deals} onOpenDeal={(d) => { setOpenDeal(d); setOpenCustomer(null); }} onOpenContact={(ct) => { setOpenContact(ct); setOpenCustomer(null); }} />}
      </Drawer>
      <Drawer open={!!openContact} onClose={() => setOpenContact(null)} title="Contact" width={540}>
        {openContact && <ContactDetail contact={openContact} deals={deals} onOpenCompany={(c) => { setOpenCustomer(c); setOpenContact(null); }} onOpenDeal={(d) => { setOpenDeal(d); setOpenContact(null); }} />}
      </Drawer>

      {newDealOpen && <NewDealModal onClose={() => setNewDealOpen(false)} onCreate={(deal) => {
        setDeals(ds => [...ds, deal]);
        setNewDealOpen(false);
        setOpenDeal(deal);
      }} />}
      {newCompanyOpen && <NewCompanyModal onClose={() => setNewCompanyOpen(false)} onCreate={(company) => {
        D.CUSTOMERS.push(company);
        forceBump(n => n + 1);
        setNewCompanyOpen(false);
        setView('companies');
        setOpenCustomer(company);
      }} />}
      {newContactOpen && <NewContactModal onClose={() => setNewContactOpen(false)} onCreate={(contact) => {
        if (contact.primary) (D.CONTACTS || []).forEach(c => { if (c.companyId === contact.companyId) c.primary = false; });
        D.CONTACTS.push(contact);
        forceBump(n => n + 1);
        setNewContactOpen(false);
        setView('contacts');
        setOpenContact(contact);
      }} />}
      {logActivityOpen && <LogActivityModal context={logActivityOpen} onClose={() => setLogActivityOpen(false)} onLog={() => setLogActivityOpen(false)} deals={deals} />}
    </div>
  );
}

// Contract value = DaaS retainer + (seats × seat price) + setup fee + MVP jumpstart
function DealValueBreakdown({ deal }) {
  const seatsSub = (deal.seats || 0) * (deal.seatPrice || 0);
  const total = (deal.daas || 0) + seatsSub + (deal.setup || 0) + (deal.mvp || 0);
  const lines = [
    { label: 'DaaS retainer', sub: 'Annual recurring', amount: deal.daas || 0, recurring: true },
    { label: `Seats · ${deal.seats || 0} × ${fmtMoneyFull(deal.seatPrice || 0)}`, sub: 'Per-seat licensing', amount: seatsSub, recurring: true },
    { label: 'Setup fee', sub: 'One-time', amount: deal.setup || 0 },
    { label: 'MVP Jumpstart', sub: 'One-time', amount: deal.mvp || 0 },
  ];
  return (
    <div className="deal-value">
      {lines.map((l, i) => (
        <div key={i} className={`deal-value-row ${l.amount === 0 ? 'zero' : ''}`}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="deal-value-label">{l.label}{l.recurring && <span className="deal-value-tag">/yr</span>}</div>
            <div className="deal-value-sub">{l.sub}</div>
          </div>
          <div className="deal-value-amt mono">{fmtMoneyFull(l.amount)}</div>
        </div>
      ))}
      <div className="deal-value-total">
        <span>Total contract value</span>
        <span className="mono">{fmtMoneyFull(total)}</span>
      </div>
    </div>
  );
}

function DealDetail({ deal, onMoveStage, onOpenCustomer, onLogActivity }) {
  const D = window.HitcentsData;
  const cust = deal.customer ? getCustomer(deal.customer) : null;
  const owner = getEmployee(deal.owner);
  const stage = D.DEAL_STAGES.find(s => s.id === deal.stage);

  // Attached documents — seeded with what's already on the deal
  const [docs, setDocs] = useState([
    { name: 'Proposal v3.pdf', size: 482000, kind: 'PDF', color: '#C2452C', who: 'Garrett', when: 'yesterday' },
  ]);
  const docInputRef = useRef(null);
  const [dragOver, setDragOver] = useState(false);

  function glyphFor(name) {
    const ext = (name.split('.').pop() || '').toLowerCase();
    const map = {
      pdf:  { kind: 'PDF', color: '#C2452C' },
      doc:  { kind: 'DOC', color: '#2B5BA8' }, docx: { kind: 'DOC', color: '#2B5BA8' },
      xls:  { kind: 'XLS', color: '#2E7D52' }, xlsx: { kind: 'XLS', color: '#2E7D52' },
      ppt:  { kind: 'PPT', color: '#C2562C' }, pptx: { kind: 'PPT', color: '#C2562C' },
      png:  { kind: 'IMG', color: '#7A5AA8' }, jpg: { kind: 'IMG', color: '#7A5AA8' }, jpeg: { kind: 'IMG', color: '#7A5AA8' },
    };
    return map[ext] || { kind: 'FILE', color: '#6B7280' };
  }
  function addFiles(fileList) {
    const next = Array.from(fileList || []).map(f => ({
      name: f.name, size: f.size, ...glyphFor(f.name), who: 'You', when: 'just now',
    }));
    if (next.length) setDocs(d => [...next, ...d]);
  }

  return (
    <div>
      <h2 style={{ margin: '0 0 4px', fontSize: 20, fontWeight: 600 }}>{deal.name}</h2>
      <div className="muted" style={{ marginBottom: 16 }}>{cust ? <a onClick={() => onOpenCustomer(cust)} style={{ cursor: 'pointer', color: 'var(--brand-orange)' }}>{cust.name}</a> : deal.customerName}</div>

      <div className="grid g-2" style={{ gap: 10, marginBottom: 16 }}>
        <InfoRow icon="chart" label="Probability" value={`${deal.probability}%`} />
        <InfoRow icon="cal" label="Close date" value={fmtDate(deal.close)} />
        <InfoRow icon="users" label="Owner" value={owner?.name} />
        <InfoRow icon="layers" label="Stage" value={stage.name} />
      </div>

      <SectionTitle>Contract value</SectionTitle>
      <DealValueBreakdown deal={deal} />

      <div className="row spread" style={{ margin: '18px 0 8px', alignItems: 'center' }}>
        <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-muted)', fontWeight: 600 }}>Documents ({docs.length})</div>
        <Button size="sm" variant="ghost" icon="plus" onClick={() => docInputRef.current?.click()}>Attach</Button>
      </div>
      <input ref={docInputRef} type="file" multiple
             accept="application/pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,image/*"
             style={{ display: 'none' }} onChange={e => { addFiles(e.target.files); e.target.value = ''; }} />
      <div className={`nc-drop ${dragOver ? 'over' : ''}`}
           style={{ padding: '16px 14px', marginBottom: 10 }}
           onClick={() => docInputRef.current?.click()}
           onDragOver={e => { e.preventDefault(); setDragOver(true); }}
           onDragLeave={() => setDragOver(false)}
           onDrop={e => { e.preventDefault(); setDragOver(false); addFiles(e.dataTransfer.files); }}>
        <Icon name="upload" size={18} />
        <div style={{ fontSize: 12.5, fontWeight: 500, marginTop: 5 }}>Drop a proposal or click to attach</div>
        <div className="dim" style={{ fontSize: 11 }}>PDF, Office docs, or images</div>
      </div>
      <div className="col" style={{ gap: 6 }}>
        {docs.map((f, i) => (
          <div key={i} className="row gap-2" style={{ padding: '8px 10px', background: 'var(--bg-elev)', borderRadius: 6 }}>
            <span className="file-glyph" style={{ background: f.color, width: 24, height: 24, fontSize: 9 }}>{f.kind}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{f.name}</div>
              <div className="dim" style={{ fontSize: 11 }}>{fileBytes(f.size)} · {f.who} · {f.when}</div>
            </div>
            <button className="icon-btn" style={{ width: 24, height: 24 }} title="Remove"
                    onClick={() => setDocs(d => d.filter((_, j) => j !== i))}><Icon name="x" size={12} /></button>
          </div>
        ))}
        {docs.length === 0 && <div className="muted" style={{ fontSize: 12.5 }}>No documents attached yet.</div>}
      </div>

      <SectionTitle>Move to stage</SectionTitle>
      <div className="row gap-2" style={{ flexWrap: 'wrap' }}>
        {D.DEAL_STAGES.map(s => (
          <button key={s.id}
                  onClick={() => onMoveStage(s.id)}
                  className={`btn btn-sm ${s.id === deal.stage ? 'btn-primary' : 'btn-secondary'}`}>
            {s.name}
          </button>
        ))}
      </div>

      <SectionTitle>Timeline</SectionTitle>
      <div className="row gap-2" style={{ marginBottom: 12 }}>
        <Button size="sm" variant="primary" icon="plus" onClick={onLogActivity}>Log activity</Button>
        <Button size="sm" variant="secondary" icon="mail">Send email</Button>
        <Button size="sm" variant="secondary" icon="phone">Log call</Button>
        <Button size="sm" variant="ghost" icon="cal">Schedule meeting</Button>
      </div>
      <div className="col" style={{ gap: 12, fontSize: 12.5 }}>
        {[
          { who: owner, when: '2 hours ago', what: 'Updated probability to ' + deal.probability + '%' },
          { who: owner, when: 'yesterday', what: 'Sent proposal v3.pdf' },
          { who: getEmployee('e22'), when: '3 days ago', what: 'Logged call (38 min)' },
          { who: owner, when: '1 week ago', what: `Stage → ${stage.name}` },
        ].map((it, i) => (
          <div key={i} className="row gap-3" style={{ alignItems: 'flex-start' }}>
            <Avatar person={it.who} size={26} />
            <div style={{ flex: 1 }}>
              <div><strong>{it.who?.name.split(' ')[0]}</strong> · {it.what}</div>
              <div className="dim" style={{ fontSize: 11 }}>{it.when}</div>
            </div>
          </div>
        ))}
      </div>

      <SectionTitle>Next step</SectionTitle>
      <div className="card" style={{ background: 'var(--brand-orange-tint)', borderColor: 'rgba(224,85,43,0.35)' }}>
        <div className="row gap-2" style={{ marginBottom: 4 }}>
          <Icon name="bolt" size={14} style={{ color: 'var(--brand-orange)' }} />
          <strong style={{ fontSize: 12.5 }}>Suggested by Hitcents AI</strong>
        </div>
        <div style={{ fontSize: 13 }}>Schedule legal review before close · ${(deal.value/1000).toFixed(0)}k contract typically routes through Ramon for MSA approval.</div>
      </div>
    </div>
  );
}

function CustomerDetail({ customer, deals, onOpenDeal, onOpenContact }) {
  const myDeals = deals.filter(d => d.customer === customer.id);
  const D = window.HitcentsData;
  const contacts = getContactsForCompany(customer.id);

  return (
    <div>
      <div className="row gap-3" style={{ marginBottom: 18 }}>
        <div style={{ width: 56, height: 56, borderRadius: 12, background: 'var(--bg-elev)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20, fontWeight: 600, color: 'var(--brand-wine)' }}>{customer.name[0]}</div>
        <div>
          <h2 style={{ margin: 0, fontSize: 20, fontWeight: 600 }}>{customer.name}</h2>
          <div className="muted" style={{ fontSize: 13 }}>{customer.hq} · {customer.website}</div>
          <div className="row gap-2" style={{ marginTop: 8 }}>
            <Badge tone={customer.tier === 'Enterprise' ? 'purple' : 'blue'}>{customer.tier}</Badge>
            <Badge tone={customer.health === 'Healthy' ? 'green' : customer.health === 'At risk' ? 'red' : 'neutral'}>{customer.health}</Badge>
            {customer.tags.map(t => <Badge key={t} tone="orange">{t}</Badge>)}
          </div>
        </div>
      </div>

      <div className="grid g-2" style={{ gap: 10, marginBottom: 18 }}>
        <InfoRow icon="store" label="Industry" value={customer.industry} />
        <InfoRow icon="users" label="Headcount" value={customer.size} />
        <InfoRow icon="card" label="MRR" value={customer.mrr ? fmtMoneyFull(customer.mrr) : '—'} />
        <InfoRow icon="cal" label="Customer since" value={fmtDate(customer.since)} />
      </div>

      <div className="row spread" style={{ margin: '18px 0 8px', alignItems: 'center' }}>
        <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-muted)', fontWeight: 600 }}>Contacts ({contacts.length})</div>
        {onOpenContact && <Button size="sm" variant="ghost" icon="plus">Add contact</Button>}
      </div>
      <div className="col" style={{ gap: 6 }}>
        {contacts.map(ct => (
          <div key={ct.id} className="contact-row" onClick={() => onOpenContact && onOpenContact(ct)}>
            <Avatar person={ct} size={32} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="row gap-2" style={{ alignItems: 'center' }}>
                <span style={{ fontWeight: 500, fontSize: 13 }}>{ct.name}</span>
                {ct.primary && <Badge tone="orange">Primary</Badge>}
              </div>
              <div className="dim" style={{ fontSize: 11.5 }}>{ct.title}</div>
            </div>
            <Icon name="chev_r" size={14} style={{ color: 'var(--text-muted)', flexShrink: 0 }} />
          </div>
        ))}
        {contacts.length === 0 && <div className="muted" style={{ fontSize: 12.5 }}>No contacts yet.</div>}
      </div>

      <SectionTitle>Deals ({myDeals.length})</SectionTitle>
      <div className="col" style={{ gap: 6 }}>
        {myDeals.map(d => {
          const s = D.DEAL_STAGES.find(x => x.id === d.stage);
          const dOwner = getEmployee(d.owner);
          return (
            <div key={d.id} className="card" style={{ padding: 10, cursor: 'pointer' }} onClick={() => onOpenDeal(d)}>
              <div className="row gap-2"><div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500, fontSize: 13 }}>{d.name}</div>
                <div className="dim mono" style={{ fontSize: 11 }}>{fmtMoneyFull(d.value)} · close {fmtDateShort(d.close)}</div>
              </div>
                <div className="row gap-2">
                  {dOwner && <Avatar person={dOwner} size={20} ring={false} />}
                  <Badge style={{ background: s.color + '22', color: s.color }}>{s.name}</Badge>
                </div>
              </div>
            </div>
          );
        })}
        {myDeals.length === 0 && <div className="muted" style={{ fontSize: 12.5 }}>No open deals.</div>}
      </div>
    </div>
  );
}

function Forecast({ deals }) {
  const D = window.HitcentsData;
  const byOwner = {};
  deals.forEach(d => {
    if (!byOwner[d.owner]) byOwner[d.owner] = { open: 0, weighted: 0, won: 0, count: 0 };
    if (d.stage === 'won') byOwner[d.owner].won += d.value;
    else if (d.stage !== 'lost') { byOwner[d.owner].open += d.value; byOwner[d.owner].weighted += d.value * (d.probability/100); byOwner[d.owner].count++; }
  });

  return (
    <div className="card flush">
      <table className="table">
        <thead>
          <tr><th>Rep</th><th>Open deals</th><th>Pipeline</th><th>Weighted</th><th>Closed won (qtr)</th><th>Quota attainment</th></tr>
        </thead>
        <tbody>
          {Object.entries(byOwner).map(([oid, v]) => {
            const o = getEmployee(oid);
            const quota = 400000;
            const pct = Math.min(150, Math.round(((v.won + v.weighted) / quota) * 100));
            return (
              <tr key={oid}>
                <td><div className="row gap-2"><Avatar person={o} size={26} /><div><div style={{ fontWeight: 500 }}>{o?.name}</div><div className="dim" style={{ fontSize: 11 }}>{o?.title}</div></div></div></td>
                <td className="mono">{v.count}</td>
                <td className="mono">{fmtMoneyFull(v.open)}</td>
                <td className="mono">{fmtMoneyFull(Math.round(v.weighted))}</td>
                <td className="mono">{fmtMoneyFull(v.won)}</td>
                <td>
                  <div className="row gap-2">
                    <div className="progress" style={{ flex: 1, maxWidth: 160 }}><div className="fill" style={{ width: `${Math.min(100, pct)}%`, background: pct >= 80 ? 'var(--green)' : pct >= 50 ? 'var(--amber)' : 'var(--red)' }} /></div>
                    <span className="mono" style={{ fontSize: 12, width: 36, textAlign: 'right' }}>{pct}%</span>
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

window.CRM = CRM;

// ═════════════════════════════════════════════════════════════════
// Customers — Companies + Contacts (broken out of CRM)
// ═════════════════════════════════════════════════════════════════
function Customers() {
  const D = window.HitcentsData;
  const [view, setView] = useState('companies');
  const [openCustomer, setOpenCustomer] = useState(null);
  const [openContact, setOpenContact] = useState(null);
  const [newCompanyOpen, setNewCompanyOpen] = useState(false);
  const [newContactOpen, setNewContactOpen] = useState(false);
  const [, forceBump] = useState(0);
  const deals = D.DEALS;

  useEffect(() => {
    function onOpen(e) {
      if (e.detail?.type === 'customer') {
        const c = D.CUSTOMERS.find(x => x.id === e.detail.id);
        if (c) { setView('companies'); setOpenCustomer(c); }
      }
      if (e.detail?.type === 'contact') {
        const c = (D.CONTACTS || []).find(x => x.id === e.detail.id);
        if (c) { setView('contacts'); setOpenContact(c); }
      }
    }
    window.addEventListener('hitcents:open', onOpen);
    return () => window.removeEventListener('hitcents:open', onOpen);
  }, []);

  const totalMrr = D.CUSTOMERS.reduce((s, c) => s + (c.mrr || 0), 0);
  const active = D.CUSTOMERS.filter(c => c.health !== 'Prospect').length;
  const atRisk = D.CUSTOMERS.filter(c => c.health === 'At risk').length;

  return (
    <div data-screen-label="Customers">
      <div className="page-head">
        <div>
          <h1>Customers</h1>
          <div className="sub">{D.CUSTOMERS.length} companies · {(D.CONTACTS || []).length} contacts · {fmtMoneyFull(totalMrr)} MRR</div>
        </div>
        <div className="row gap-2">
          <Button variant="secondary" icon="filter">Filters</Button>
          {view === 'contacts'
            ? <Button variant="primary" icon="plus" onClick={() => setNewContactOpen(true)}>New contact</Button>
            : <Button variant="primary" icon="plus" onClick={() => setNewCompanyOpen(true)}>New company</Button>}
        </div>
      </div>

      <div className="grid g-4" style={{ marginBottom: 18, gap: 12 }}>
        <Kpi label="Companies" value={D.CUSTOMERS.length} delta={`${active} active accounts`} />
        <Kpi label="Contacts" value={(D.CONTACTS || []).length} delta="across all companies" />
        <Kpi label="Total MRR" value={fmtMoney(totalMrr)} delta="recurring revenue" tone="up" />
        <Kpi label="At risk" value={atRisk} delta="need attention" tone={atRisk ? 'down' : undefined} />
      </div>

      <div className="tabs" style={{ marginBottom: 16 }}>
        <button className={`tab ${view === 'companies' ? 'active' : ''}`} onClick={() => setView('companies')}>Companies</button>
        <button className={`tab ${view === 'contacts' ? 'active' : ''}`} onClick={() => setView('contacts')}>Contacts</button>
      </div>

      {view === 'companies' && (
        <div className="card flush">
          <table className="table">
            <thead>
              <tr>
                <th>Company</th><th>Tier</th><th>Industry</th><th>MRR</th>
                <th>Health</th><th>Contacts</th><th>Open deals</th><th>Since</th>
              </tr>
            </thead>
            <tbody>
              {D.CUSTOMERS.map(c => {
                const contacts = getContactsForCompany(c.id);
                const openDeals = deals.filter(d => d.customer === c.id && !['won','lost'].includes(d.stage));
                const tone = c.health === 'Healthy' ? 'green' : c.health === 'At risk' ? 'red' : c.health === 'Prospect' ? 'neutral' : 'blue';
                return (
                  <tr key={c.id} className="clickable" onClick={() => setOpenCustomer(c)}>
                    <td>
                      <div className="row gap-2">
                        <div className="company-mark">{c.name[0]}</div>
                        <div>
                          <div style={{ fontWeight: 500 }}>{c.name}</div>
                          <div className="dim" style={{ fontSize: 11.5 }}>{c.hq} · {c.website}</div>
                        </div>
                      </div>
                    </td>
                    <td><Badge tone={c.tier === 'Enterprise' ? 'purple' : c.tier === 'Mid-market' ? 'blue' : 'neutral'}>{c.tier}</Badge></td>
                    <td className="muted">{c.industry}</td>
                    <td className="mono">{c.mrr ? fmtMoneyFull(c.mrr) : '—'}</td>
                    <td><Badge tone={tone}>{c.health}</Badge></td>
                    <td>
                      {contacts.length > 0 ? (
                        <div className="row gap-2">
                          <div className="avatar-stack">
                            {contacts.slice(0, 3).map(ct => <Avatar key={ct.id} person={ct} size={20} />)}
                          </div>
                          <span className="dim mono" style={{ fontSize: 11.5 }}>{contacts.length}</span>
                        </div>
                      ) : <span className="dim">—</span>}
                    </td>
                    <td className="mono">{openDeals.length || <span className="dim">—</span>}</td>
                    <td className="muted mono" style={{ fontSize: 11.5 }}>{c.since ? fmtDateShort(c.since) : '—'}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {view === 'contacts' && (
        <Contacts onOpenContact={setOpenContact} onOpenCompany={setOpenCustomer} onNew={() => setNewContactOpen(true)} />
      )}

      <Drawer open={!!openCustomer} onClose={() => setOpenCustomer(null)} title="Company" width={580}>
        {openCustomer && <CustomerDetail customer={openCustomer} deals={deals} onOpenDeal={() => {}} onOpenContact={(ct) => { setOpenContact(ct); setOpenCustomer(null); }} />}
      </Drawer>
      <Drawer open={!!openContact} onClose={() => setOpenContact(null)} title="Contact" width={540}>
        {openContact && <ContactDetail contact={openContact} deals={deals} onOpenCompany={(c) => { setOpenCustomer(c); setOpenContact(null); }} onOpenDeal={() => {}} />}
      </Drawer>

      {newCompanyOpen && <NewCompanyModal onClose={() => setNewCompanyOpen(false)} onCreate={(company) => {
        D.CUSTOMERS.push(company); forceBump(n => n + 1); setNewCompanyOpen(false); setView('companies'); setOpenCustomer(company);
      }} />}
      {newContactOpen && <NewContactModal onClose={() => setNewContactOpen(false)} onCreate={(contact) => {
        if (contact.primary) (D.CONTACTS || []).forEach(c => { if (c.companyId === contact.companyId) c.primary = false; });
        D.CONTACTS.push(contact); forceBump(n => n + 1); setNewContactOpen(false); setView('contacts'); setOpenContact(contact);
      }} />}
    </div>
  );
}
window.Customers = Customers;

// ═════════════════════════════════════════════════════════════════
// Vendors — companies we buy from + their contacts, software & contracts
// ═════════════════════════════════════════════════════════════════
function Vendors() {
  const D = window.HitcentsData;
  const [view, setView] = useState('companies');
  const [openVendor, setOpenVendor] = useState(null);
  const [openContact, setOpenContact] = useState(null);
  const [newVendorOpen, setNewVendorOpen] = useState(false);
  const [, vBump] = useState(0);
  const vendors = D.VENDORS || [];
  const vendorContacts = D.VENDOR_CONTACTS || [];

  useEffect(() => {
    function onOpen(e) {
      if (e.detail?.type === 'vendor') {
        const v = (D.VENDORS || []).find(x => x.id === e.detail.id);
        if (v) { setView('companies'); setOpenVendor(v); }
      }
    }
    window.addEventListener('hitcents:open', onOpen);
    return () => window.removeEventListener('hitcents:open', onOpen);
  }, []);

  const totalSpend = vendors.reduce((s, v) => s + (v.annualSpend || 0), 0);
  const softwareCount = vendors.filter(v => (v.licenses || []).length).length;

  const statusTone = (s) => s === 'Active' ? 'green' : s === 'Review' ? 'orange' : s === 'Churned' ? 'red' : 'neutral';

  return (
    <div data-screen-label="Vendors">
      <div className="page-head">
        <div>
          <h1>Vendors</h1>
          <div className="sub">{vendors.length} vendors · {fmtMoneyFull(totalSpend)}/yr committed spend · {softwareCount} software providers</div>
        </div>
        <div className="row gap-2">
          <Button variant="secondary" icon="filter">Filters</Button>
          <Button variant="primary" icon="plus" onClick={() => setNewVendorOpen(true)}>New vendor</Button>
        </div>
      </div>

      <div className="grid g-4" style={{ marginBottom: 18, gap: 12 }}>
        <Kpi label="Active vendors" value={vendors.filter(v => v.status === 'Active').length} delta={`${vendors.length} total`} />
        <Kpi label="Annual spend" value={fmtMoney(totalSpend)} delta="committed" />
        <Kpi label="Software providers" value={softwareCount} delta="linked to licenses" />
        <Kpi label="Vendor contacts" value={vendorContacts.length} delta="points of contact" />
      </div>

      <div className="tabs" style={{ marginBottom: 16 }}>
        <button className={`tab ${view === 'companies' ? 'active' : ''}`} onClick={() => setView('companies')}>Companies</button>
        <button className={`tab ${view === 'contacts' ? 'active' : ''}`} onClick={() => setView('contacts')}>Contacts</button>
      </div>

      {view === 'companies' && (
        <div className="card flush">
          <table className="table">
            <thead>
              <tr>
                <th>Vendor</th><th>Category</th><th>Owner</th><th>Annual spend</th>
                <th>Software</th><th>Contracts</th><th>Status</th><th>Since</th>
              </tr>
            </thead>
            <tbody>
              {vendors.map(v => {
                const owner = getEmployee(v.owner);
                const lics = getLicensesForVendor(v);
                const contracts = getContractsForVendor(v);
                return (
                  <tr key={v.id} className="clickable" onClick={() => setOpenVendor(v)}>
                    <td>
                      <div className="row gap-2">
                        <div className="company-mark">{v.name[0]}</div>
                        <div>
                          <div style={{ fontWeight: 500 }}>{v.name}</div>
                          <div className="dim" style={{ fontSize: 11.5 }}>{v.hq} · {v.website}</div>
                        </div>
                      </div>
                    </td>
                    <td className="muted">{v.category}</td>
                    <td>{owner ? <div className="row gap-2"><Avatar person={owner} size={20} /><span style={{ fontSize: 12.5 }}>{owner.name.split(' ')[0]}</span></div> : <span className="dim">—</span>}</td>
                    <td className="mono">{v.annualSpend ? fmtMoneyFull(v.annualSpend) : '—'}</td>
                    <td className="mono">{lics.length || <span className="dim">—</span>}</td>
                    <td className="mono">{contracts.length || <span className="dim">—</span>}</td>
                    <td><Badge tone={statusTone(v.status)}>{v.status}</Badge></td>
                    <td className="muted mono" style={{ fontSize: 11.5 }}>{v.since ? fmtDateShort(v.since) : '—'}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {view === 'contacts' && (
        <div className="card flush">
          <table className="table">
            <thead>
              <tr><th>Name</th><th>Title</th><th>Vendor</th><th>Email</th><th>Phone</th><th>Status</th></tr>
            </thead>
            <tbody>
              {vendorContacts.map(ct => {
                const v = getVendor(ct.vendorId);
                return (
                  <tr key={ct.id} className="clickable" onClick={() => setOpenContact(ct)}>
                    <td>
                      <div className="row gap-2">
                        <Avatar person={ct} size={28} />
                        <div>
                          <div style={{ fontWeight: 500 }}>{ct.name}{ct.primary && <span className="dim" style={{ fontSize: 11, marginLeft: 6 }}>Primary</span>}</div>
                        </div>
                      </div>
                    </td>
                    <td className="muted">{ct.title}</td>
                    <td><button className="link-btn" onClick={(e) => { e.stopPropagation(); setOpenVendor(v); }}>{v?.name}</button></td>
                    <td className="mono" style={{ fontSize: 12 }}>{ct.email}</td>
                    <td className="mono" style={{ fontSize: 12 }}>{ct.phone}</td>
                    <td><Badge tone={ct.status === 'Active' ? 'green' : 'neutral'}>{ct.status}</Badge></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      <Drawer open={!!openVendor} onClose={() => setOpenVendor(null)} title="Vendor" width={580}>
        {openVendor && <VendorDetail vendor={openVendor} onOpenContact={(ct) => { setOpenContact(ct); setOpenVendor(null); }} />}
      </Drawer>
      <Drawer open={!!openContact} onClose={() => setOpenContact(null)} title="Vendor contact" width={520}>
        {openContact && <VendorContactDetail contact={openContact} onOpenVendor={(v) => { setOpenVendor(v); setOpenContact(null); }} />}
      </Drawer>

      {newVendorOpen && <NewVendorModal onClose={() => setNewVendorOpen(false)} onCreate={(vendor) => {
        D.VENDORS.push(vendor); vBump(n => n + 1); setNewVendorOpen(false); setView('companies'); setOpenVendor(vendor);
      }} />}
    </div>
  );
}

function VendorDetail({ vendor, onOpenContact }) {
  const owner = getEmployee(vendor.owner);
  const lics = getLicensesForVendor(vendor);
  const contracts = getContractsForVendor(vendor);
  const contacts = getVendorContacts(vendor.id);
  const monthly = lics.reduce((s, l) => s + (l.monthly || 0), 0);

  return (
    <div className="emp-profile">
      <div className="emp-hero" style={{ '--dept': 'var(--brand-orange)' }}>
        <div className="company-mark" style={{ width: 64, height: 64, fontSize: 26, borderRadius: 14 }}>{vendor.name[0]}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <h2 className="emp-hero-name">{vendor.name}</h2>
          <div className="emp-hero-title">{vendor.category} · {vendor.hq}</div>
          <div className="row gap-2" style={{ marginTop: 8, flexWrap: 'wrap' }}>
            <Badge tone={vendor.status === 'Active' ? 'green' : vendor.status === 'Review' ? 'orange' : 'neutral'}>{vendor.status}</Badge>
            {(vendor.tags || []).map(t => <Badge key={t}>{t}</Badge>)}
          </div>
        </div>
      </div>

      <div className="emp-actions" style={{ gridTemplateColumns: 'repeat(2, 1fr)' }}>
        <a className="emp-action" href={`https://${vendor.website}`} target="_blank" rel="noreferrer"><Icon name="globe" size={14} />Website</a>
        <div className="emp-action" style={{ cursor: 'default' }}><Icon name="card" size={14} />{vendor.terms}</div>
      </div>

      <SectionTitle>At a glance</SectionTitle>
      <div className="grid g-2" style={{ gap: 10 }}>
        <div className="card" style={{ padding: 12 }}>
          <div className="dim" style={{ fontSize: 11 }}>Annual spend</div>
          <div className="mono" style={{ fontSize: 18, fontWeight: 600, color: 'var(--brand-wine)' }}>{vendor.annualSpend ? fmtMoneyFull(vendor.annualSpend) : '—'}</div>
        </div>
        <div className="card" style={{ padding: 12 }}>
          <div className="dim" style={{ fontSize: 11 }}>Account owner</div>
          <div className="row gap-2" style={{ marginTop: 4 }}>{owner ? <><Avatar person={owner} size={22} /><span style={{ fontSize: 13 }}>{owner.name}</span></> : '—'}</div>
        </div>
      </div>

      <SectionTitle>Software ({lics.length})</SectionTitle>
      {lics.length > 0 ? (
        <div className="col" style={{ gap: 6 }}>
          {lics.map(l => (
            <div key={l.id} className="row gap-2" style={{ padding: '9px 11px', background: 'var(--bg-elev)', borderRadius: 7 }}>
              <Icon name="key" size={14} style={{ color: 'var(--brand-orange)' }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{l.name}</div>
                <div className="dim" style={{ fontSize: 11 }}>{l.purpose}</div>
              </div>
              <span className="mono" style={{ fontSize: 12 }}>{l.monthly ? fmtMoneyFull(l.monthly) + '/mo' : 'free'}</span>
            </div>
          ))}
          <div className="row spread" style={{ padding: '4px 11px', fontSize: 12 }}>
            <span className="dim">Monthly software spend</span>
            <span className="mono" style={{ fontWeight: 600 }}>{fmtMoneyFull(monthly)}/mo</span>
          </div>
        </div>
      ) : <div className="muted" style={{ fontSize: 12.5 }}>No software licenses linked.</div>}

      <SectionTitle>Contracts ({contracts.length})</SectionTitle>
      {contracts.length > 0 ? (
        <div className="col" style={{ gap: 6 }}>
          {contracts.map(c => (
            <div key={c.id} className="row gap-2" style={{ padding: '9px 11px', background: 'var(--bg-elev)', borderRadius: 7 }}>
              <Icon name="doc" size={14} style={{ color: 'var(--text-muted)' }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</div>
                <div className="dim mono" style={{ fontSize: 11 }}>{c.id} · {c.billing}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="mono" style={{ fontSize: 12 }}>{c.value ? fmtMoneyFull(c.value) : '—'}</div>
                <Badge tone={c.status === 'Active' ? 'green' : c.status === 'Expired' ? 'red' : 'neutral'} size="sm">{c.status}</Badge>
              </div>
            </div>
          ))}
        </div>
      ) : <div className="muted" style={{ fontSize: 12.5 }}>No contracts on file.</div>}

      <SectionTitle>Contacts ({contacts.length})</SectionTitle>
      {contacts.length > 0 ? (
        <div className="emp-reports-grid">
          {contacts.map(ct => (
            <button key={ct.id} className="emp-person-chip" onClick={() => onOpenContact(ct)}>
              <Avatar person={ct} size={32} />
              <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
                <div className="emp-person-name">{ct.name}</div>
                <div className="dim" style={{ fontSize: 11.5 }}>{ct.title}</div>
              </div>
              {ct.primary && <Badge tone="orange" size="sm">Primary</Badge>}
            </button>
          ))}
        </div>
      ) : <div className="muted" style={{ fontSize: 12.5 }}>No contacts yet.</div>}
    </div>
  );
}

function VendorContactDetail({ contact, onOpenVendor }) {
  const v = getVendor(contact.vendorId);
  return (
    <div className="emp-profile">
      <div className="emp-hero" style={{ '--dept': 'var(--brand-orange)' }}>
        <Avatar person={contact} size={64} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <h2 className="emp-hero-name">{contact.name}</h2>
          <div className="emp-hero-title">{contact.title}{v ? ` · ${v.name}` : ''}</div>
          <div className="row gap-2" style={{ marginTop: 8, flexWrap: 'wrap' }}>
            <Badge tone={contact.status === 'Active' ? 'green' : 'neutral'}>{contact.status}</Badge>
            {contact.primary && <Badge tone="orange">Primary</Badge>}
            {contact.role && <Badge>{contact.role}</Badge>}
          </div>
        </div>
      </div>

      <div className="emp-actions" style={{ gridTemplateColumns: 'repeat(2, 1fr)' }}>
        <a className="emp-action" href={`mailto:${contact.email}`}><Icon name="mail" size={14} />Email</a>
        <a className="emp-action" href={`tel:${contact.phone}`}><Icon name="phone" size={14} />Call</a>
      </div>

      <SectionTitle>Details</SectionTitle>
      <Fact icon="mail" label="Email" value={contact.email} mono />
      <Fact icon="phone" label="Phone" value={contact.phone} mono />
      {v && (
        <button className="emp-person-row" onClick={() => onOpenVendor(v)} style={{ marginTop: 8 }}>
          <span className="emp-person-tag">Vendor</span>
          <div className="company-mark">{v.name[0]}</div>
          <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
            <div className="emp-person-name">{v.name}</div>
            <div className="dim" style={{ fontSize: 11.5 }}>{v.category}</div>
          </div>
          <Icon name="chev_r" size={16} />
        </button>
      )}
    </div>
  );
}
function NewVendorModal({ onClose, onCreate }) {
  const D = window.HitcentsData;
  const cats = D.VENDOR_CATEGORIES || ['Other'];
  const [draft, setDraft] = useState({
    name: '', category: cats[0], owner: 'e7', website: '', hq: '',
    annualSpend: 0, terms: 'Annual', status: 'Active',
  });
  function set(p) { setDraft(d => ({ ...d, ...p })); }
  const owner = getEmployee(draft.owner);
  const canCreate = draft.name.trim().length > 0;
  const STATUSES = ['Active', 'Review', 'Churned'];

  function submit() {
    onCreate({
      id: `v${(D.VENDORS || []).length + 1}-${Date.now().toString(36)}`,
      name: draft.name.trim(),
      category: draft.category,
      owner: draft.owner,
      status: draft.status,
      since: '2026-06-23',
      website: draft.website.trim().replace(/^https?:\/\//, ''),
      hq: draft.hq.trim(),
      annualSpend: +draft.annualSpend || 0,
      terms: draft.terms,
      licenses: [],
      aliases: [draft.name.trim()],
      tags: [],
    });
  }

  return (
    <div className="cmdk-scrim" onClick={onClose} style={{ paddingTop: '6vh' }}>
      <div onClick={e => e.stopPropagation()}
           style={{ width: 640, maxWidth: '94vw', maxHeight: '88vh', background: 'var(--bg-card)', borderRadius: 14, border: '1px solid var(--border)', boxShadow: 'var(--shadow-lg)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>New vendor</h2>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>

        <div style={{ padding: 24, overflowY: 'auto', flex: 1 }}>
          <div className="grid" style={{ gridTemplateColumns: '1.5fr 1fr', gap: 22 }}>
            <div className="col" style={{ gap: 14 }}>
              <div className="field" style={{ margin: 0 }}>
                <label>Vendor name</label>
                <input autoFocus placeholder="e.g. Snowflake" value={draft.name} onChange={e => set({ name: e.target.value })} />
              </div>
              <div className="grid g-2" style={{ gap: 12 }}>
                <div className="field" style={{ margin: 0 }}>
                  <label>Website</label>
                  <input placeholder="snowflake.com" value={draft.website} onChange={e => set({ website: e.target.value })} />
                </div>
                <div className="field" style={{ margin: 0 }}>
                  <label>Headquarters</label>
                  <input placeholder="Bozeman, MT" value={draft.hq} onChange={e => set({ hq: e.target.value })} />
                </div>
              </div>
              <div className="grid g-2" style={{ gap: 12 }}>
                <div className="field" style={{ margin: 0 }}>
                  <label>Category</label>
                  <select value={draft.category} onChange={e => set({ category: e.target.value })}>
                    {cats.map(c => <option key={c}>{c}</option>)}
                  </select>
                </div>
                <DollarInput label="Annual spend" value={draft.annualSpend} onChange={v => set({ annualSpend: v })} />
              </div>
              <div className="grid g-2" style={{ gap: 12 }}>
                <div className="field" style={{ margin: 0 }}>
                  <label>Account owner</label>
                  <select value={draft.owner} onChange={e => set({ owner: e.target.value })}>
                    {D.EMPLOYEES.map(e => <option key={e.id} value={e.id}>{e.name} · {e.title}</option>)}
                  </select>
                </div>
                <div className="field" style={{ margin: 0 }}>
                  <label>Payment terms</label>
                  <input placeholder="Net 30" value={draft.terms} onChange={e => set({ terms: e.target.value })} />
                </div>
              </div>
              <div className="field" style={{ margin: 0 }}>
                <label>Relationship status</label>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
                  {STATUSES.map(s => (
                    <button key={s} type="button" onClick={() => set({ status: s })}
                            className={`btn btn-sm ${draft.status === s ? 'btn-primary' : 'btn-secondary'}`}
                            style={{ justifyContent: 'center' }}>{s}</button>
                  ))}
                </div>
              </div>
            </div>

            {/* Live preview */}
            <div>
              <div className="dim" style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: 0.6, fontWeight: 600, marginBottom: 8 }}>Live preview</div>
              <div className="card" style={{ padding: 14 }}>
                <div className="row gap-2" style={{ marginBottom: 10 }}>
                  <div className="company-mark">{(draft.name.trim()[0] || 'V').toUpperCase()}</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{draft.name.trim() || 'New vendor'}</div>
                    <div className="dim" style={{ fontSize: 11.5 }}>{[draft.hq, draft.website].filter(Boolean).join(' · ') || 'Location · website'}</div>
                  </div>
                </div>
                <div className="row gap-2" style={{ flexWrap: 'wrap', marginBottom: 10 }}>
                  <Badge tone={draft.status === 'Active' ? 'green' : draft.status === 'Review' ? 'orange' : 'neutral'}>{draft.status}</Badge>
                  <Badge tone="blue">{draft.category}</Badge>
                </div>
                <div className="row spread" style={{ fontSize: 11, marginTop: 4 }}>
                  <span className="muted">Annual spend</span><span className="mono">{draft.annualSpend ? fmtMoneyFull(+draft.annualSpend) : '—'}</span>
                </div>
                <div className="row spread" style={{ fontSize: 11, marginTop: 4 }}>
                  <span className="muted">Owner</span><span>{owner?.name}</span>
                </div>
                <div className="row spread" style={{ fontSize: 11, marginTop: 4 }}>
                  <span className="muted">Terms</span><span>{draft.terms}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div style={{ padding: '14px 24px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', background: 'var(--bg-elev)' }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <div className="row gap-2">
            {!canCreate && <span className="dim" style={{ fontSize: 11.5 }}>Vendor name required</span>}
            <Button variant="primary" icon="check" disabled={!canCreate} onClick={submit}>Create vendor</Button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Vendors = Vendors;

// ─────────────────────────────────────────────────────────────────────────────
// Deals — flat list of every deal. Owners come from People; companies don't own.
// ─────────────────────────────────────────────────────────────────────────────

function DealsList({ deals, onOpenDeal, onOpenCompany }) {
  const D = window.HitcentsData;
  const [q, setQ] = useState('');
  const [stageFilter, setStageFilter] = useState('all');
  const [ownerFilter, setOwnerFilter] = useState('all');

  const owners = [...new Set(deals.map(d => d.owner))].map(getEmployee).filter(Boolean);

  const rows = deals.filter(d => {
    if (stageFilter !== 'all' && d.stage !== stageFilter) return false;
    if (ownerFilter !== 'all' && d.owner !== ownerFilter) return false;
    const company = d.customer ? getCustomer(d.customer) : null;
    const hay = `${d.name} ${company?.name || d.customerName || ''}`.toLowerCase();
    if (q && !hay.includes(q.toLowerCase())) return false;
    return true;
  });

  const totalValue = rows.reduce((s, d) => s + d.value, 0);

  return (
    <>
      <div className="toolbar">
        <div className="search-inline">
          <Icon name="search" size={14} />
          <input placeholder="Search deals, companies…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
        <select value={stageFilter} onChange={e => setStageFilter(e.target.value)}
                style={{ padding: '7px 10px', border: '1px solid var(--border)', borderRadius: 8, background: 'var(--bg-card)', fontSize: 13 }}>
          <option value="all">All stages</option>
          {D.DEAL_STAGES.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
        </select>
        <select value={ownerFilter} onChange={e => setOwnerFilter(e.target.value)}
                style={{ padding: '7px 10px', border: '1px solid var(--border)', borderRadius: 8, background: 'var(--bg-card)', fontSize: 13 }}>
          <option value="all">All owners</option>
          {owners.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
        </select>
        <div style={{ marginLeft: 'auto' }} className="row gap-3">
          <span className="muted">{rows.length} deals · {fmtMoney(totalValue)}</span>
        </div>
      </div>

      <div className="card flush">
        <table className="table">
          <thead>
            <tr>
              <th>Deal</th>
              <th>Company</th>
              <th>Stage</th>
              <th>Value</th>
              <th>Prob.</th>
              <th>Close date</th>
              <th>Owner</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(d => {
              const company = d.customer ? getCustomer(d.customer) : null;
              const owner = getEmployee(d.owner);
              const s = D.DEAL_STAGES.find(x => x.id === d.stage);
              return (
                <tr key={d.id} className="clickable" onClick={() => onOpenDeal(d)}>
                  <td style={{ fontWeight: 500 }}>{d.name}</td>
                  <td>
                    {company ? (
                      <button className="company-link" onClick={(e) => { e.stopPropagation(); onOpenCompany(company); }}>
                        <span className="company-mark sm">{company.name[0]}</span>
                        {company.name}
                      </button>
                    ) : <span className="muted">{d.customerName || '—'}</span>}
                  </td>
                  <td><Badge style={{ background: s.color + '22', color: s.color }}>{s.name}</Badge></td>
                  <td className="mono" style={{ fontWeight: 500 }}>{fmtMoneyFull(d.value)}</td>
                  <td className="mono">{d.probability}%</td>
                  <td className="muted mono" style={{ fontSize: 11.5 }}>{fmtDateShort(d.close)}</td>
                  <td>
                    {owner ? (
                      <div className="row gap-2"><Avatar person={owner} size={22} /><span style={{ fontSize: 12.5 }}>{owner.name}</span></div>
                    ) : <span className="dim">Unassigned</span>}
                  </td>
                </tr>
              );
            })}
            {rows.length === 0 && (
              <tr><td colSpan={7} style={{ textAlign: 'center', padding: 40, color: 'var(--text-muted)' }}>No deals match the current filters.</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </>
  );
}

window.DealsList = DealsList;

// ─────────────────────────────────────────────────────────────────────────────
// Contacts — people who belong to companies (one company each)
// ─────────────────────────────────────────────────────────────────────────────

function Contacts({ onOpenContact, onOpenCompany, onNew }) {
  const D = window.HitcentsData;
  const [q, setQ] = useState('');
  const [companyFilter, setCompanyFilter] = useState('all');

  const contacts = (D.CONTACTS || []).filter(ct => {
    if (companyFilter !== 'all' && ct.companyId !== companyFilter) return false;
    if (q && !`${ct.name} ${ct.title} ${ct.email}`.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });

  return (
    <>
      <div className="toolbar">
        <div className="search-inline">
          <Icon name="search" size={14} />
          <input placeholder="Search contacts, titles, emails…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
        <select value={companyFilter} onChange={e => setCompanyFilter(e.target.value)}
                style={{ padding: '7px 10px', border: '1px solid var(--border)', borderRadius: 8, background: 'var(--bg-card)', fontSize: 13 }}>
          <option value="all">All companies</option>
          {D.CUSTOMERS.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
        </select>
        <div style={{ marginLeft: 'auto' }} className="row gap-2">
          <span className="muted">{contacts.length} contacts</span>
          <Button variant="primary" size="sm" icon="plus" onClick={onNew}>New contact</Button>
        </div>
      </div>

      <div className="card flush">
        <table className="table">
          <thead>
            <tr>
              <th>Name</th>
              <th>Title</th>
              <th>Company</th>
              <th>Buying role</th>
              <th>Email</th>
              <th>Phone</th>
            </tr>
          </thead>
          <tbody>
            {contacts.map(ct => {
              const company = getCustomer(ct.companyId);
              return (
                <tr key={ct.id} className="clickable" onClick={() => onOpenContact(ct)}>
                  <td>
                    <div className="row gap-2">
                      <Avatar person={ct} size={28} />
                      <div className="row gap-2" style={{ alignItems: 'center' }}>
                        <span style={{ fontWeight: 500 }}>{ct.name}</span>
                        {ct.primary && <Badge tone="orange">Primary</Badge>}
                      </div>
                    </div>
                  </td>
                  <td className="muted">{ct.title}</td>
                  <td>
                    <button className="company-link" onClick={(e) => { e.stopPropagation(); onOpenCompany(company); }}>
                      <span className="company-mark sm">{company?.name[0]}</span>
                      {company?.name}
                    </button>
                  </td>
                  <td>{ct.role ? <Badge tone="blue">{ct.role}</Badge> : <span className="dim">—</span>}</td>
                  <td className="mono" style={{ fontSize: 11.5 }}>{ct.email}</td>
                  <td className="mono" style={{ fontSize: 11.5 }}>{ct.phone}</td>
                </tr>
              );
            })}
            {contacts.length === 0 && (
              <tr><td colSpan={6} style={{ textAlign: 'center', padding: 40, color: 'var(--text-muted)' }}>No contacts match the current filters.</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </>
  );
}

function ContactDetail({ contact, deals, onOpenCompany, onOpenDeal }) {
  const company = getCustomer(contact.companyId);
  const siblings = getContactsForCompany(contact.companyId).filter(c => c.id !== contact.id);
  const companyDeals = deals.filter(d => d.customer === contact.companyId);

  return (
    <div>
      <div className="row gap-3" style={{ marginBottom: 18 }}>
        <Avatar person={contact} size={64} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="row gap-2" style={{ alignItems: 'center' }}>
            <h2 style={{ margin: 0, fontSize: 20, fontWeight: 600 }}>{contact.name}</h2>
            {contact.primary && <Badge tone="orange">Primary</Badge>}
          </div>
          <div className="muted" style={{ fontSize: 13.5 }}>{contact.title}</div>
          <div className="row gap-2" style={{ marginTop: 8, flexWrap: 'wrap' }}>
            <Badge tone={contact.status === 'Active' ? 'green' : 'neutral'}>{contact.status}</Badge>
            {contact.role && <Badge tone="blue">{contact.role}</Badge>}
          </div>
        </div>
      </div>

      {/* Quick actions */}
      <div className="emp-actions" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
        <a className="emp-action" href={`mailto:${contact.email}`}><Icon name="mail" size={14} />Email</a>
        <button className="emp-action"><Icon name="phone" size={14} />Call</button>
        <button className="emp-action"><Icon name="send" size={14} />Log activity</button>
      </div>

      <div className="grid g-2" style={{ gap: 10, marginBottom: 4 }}>
        <InfoRow icon="mail" label="Email" value={contact.email} />
        <InfoRow icon="phone" label="Phone" value={contact.phone} />
      </div>

      <SectionTitle>Company</SectionTitle>
      <button className="contact-company-card" onClick={() => onOpenCompany(company)}>
        <div className="company-mark">{company?.name[0]}</div>
        <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
          <div style={{ fontWeight: 600, fontSize: 14 }}>{company?.name}</div>
          <div className="dim" style={{ fontSize: 11.5 }}>{company?.industry} · {company?.tier} · {company?.hq}</div>
        </div>
        <Icon name="chev_r" size={15} style={{ color: 'var(--text-muted)' }} />
      </button>

      {companyDeals.length > 0 && <>
        <SectionTitle>Related deals ({companyDeals.length})</SectionTitle>
        <div className="col" style={{ gap: 6 }}>
          {companyDeals.map(d => {
            const s = window.HitcentsData.DEAL_STAGES.find(x => x.id === d.stage);
            return (
              <div key={d.id} className="card" style={{ padding: 10, cursor: 'pointer' }} onClick={() => onOpenDeal(d)}>
                <div className="row gap-2"><div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 500, fontSize: 13 }}>{d.name}</div>
                  <div className="dim mono" style={{ fontSize: 11 }}>{fmtMoneyFull(d.value)} · close {fmtDateShort(d.close)}</div>
                </div>
                  <Badge style={{ background: s.color + '22', color: s.color }}>{s.name}</Badge>
                </div>
              </div>
            );
          })}
        </div>
      </>}

      {siblings.length > 0 && <>
        <SectionTitle>Other contacts at {company?.name}</SectionTitle>
        <div className="col" style={{ gap: 6 }}>
          {siblings.map(ct => (
            <div key={ct.id} className="contact-row" onClick={() => { onOpenCompany(company); }}>
              <Avatar person={ct} size={28} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 500, fontSize: 13 }}>{ct.name}</div>
                <div className="dim" style={{ fontSize: 11.5 }}>{ct.title}</div>
              </div>
              {ct.primary && <Badge tone="orange">Primary</Badge>}
            </div>
          ))}
        </div>
      </>}
    </div>
  );
}

window.Contacts = Contacts;
window.ContactDetail = ContactDetail;

const CRM_ACTIVITY = [
  { id: 'a1', kind: 'note',    rep: 'e20', target: { type: 'deal', name: 'Stratoscale — Platform tier upgrade' }, body: 'Spoke with Maya (VP Eng). They want a side-by-side comparison of permission models vs incumbent. Sent over the data sheet + asked for a follow-up next Tuesday.', when: '2026-05-15T14:38:00' },
  { id: 'a2', kind: 'email',   rep: 'e21', target: { type: 'deal', name: 'Vellum Health — Seat expansion' }, body: 'Email out: pricing for 25-seat upgrade with annual prepay discount.', when: '2026-05-15T13:12:00' },
  { id: 'a3', kind: 'stage',   rep: 'e20', target: { type: 'deal', name: 'Klein & Auer — EU data residency' }, body: 'Negotiation → moved on after legal redline #3 approved by Ramon.', when: '2026-05-15T11:50:00' },
  { id: 'a4', kind: 'call',    rep: 'e22', target: { type: 'deal', name: 'Foxtail Robotics — POC' }, body: 'Discovery call (32 min). Stack: GCP + BigQuery. Pains around long ETL pipelines. Strong tech fit. Champion: Jordan Wu.', when: '2026-05-15T10:14:00' },
  { id: 'a5', kind: 'meeting', rep: 'e20', target: { type: 'customer', name: 'Northbrook Manufacturing' }, body: 'QBR on-site in Detroit. Adoption strong with their new ops team. Renewal mood: cautiously positive. Action items: build ROI deck.', when: '2026-05-14T16:00:00' },
  { id: 'a6', kind: 'won',     rep: 'e21', target: { type: 'deal', name: 'Marigold Studios — Team plan' }, body: 'Closed Won! 12-month annual contract, $14.4k ARR. Champion: Renée Hsieh.', when: '2026-05-14T15:22:00' },
  { id: 'a7', kind: 'note',    rep: 'e20', target: { type: 'deal', name: 'Junction Bank — Pilot SOW' }, body: 'Compliance team flagged SOC 2 Type II + data residency as gates. Looped in Owen for security review session.', when: '2026-05-14T11:45:00' },
  { id: 'a8', kind: 'email',   rep: 'e22', target: { type: 'deal', name: 'Plenum Analytics — Mid-market' }, body: 'Outbound sequence step 3 sent. Open rate 38%, reply pending.', when: '2026-05-14T09:30:00' },
  { id: 'a9', kind: 'task',    rep: 'e20', target: { type: 'deal', name: 'Halcyon Biotech — Analytics module' }, body: 'Task: send updated MSA with revised IP indemnification clause.', when: '2026-05-13T18:20:00' },
  { id: 'a10', kind: 'lost',   rep: 'e21', target: { type: 'deal', name: 'Cerulean Foods' }, body: 'Closed Lost — budget pulled. Champion still warm; flagged to revisit in Q3.', when: '2026-05-13T15:11:00' },
  { id: 'a11', kind: 'meeting', rep: 'e4', target: { type: 'customer', name: 'Stratoscale Robotics' }, body: 'Exec sync with their CTO. Discussed multi-region deploy + 2027 roadmap alignment.', when: '2026-05-13T13:00:00' },
  { id: 'a12', kind: 'call',   rep: 'e20', target: { type: 'deal', name: 'Klein & Auer — EU data residency' }, body: 'Procurement intro call. Standard process, expect signed PO within 10 business days.', when: '2026-05-13T08:45:00' },
];

const KIND_META = {
  note:    { icon: 'pencil',  tone: 'orange',  label: 'Note' },
  email:   { icon: 'mail',    tone: 'blue',    label: 'Email' },
  call:    { icon: 'phone',   tone: 'teal',    label: 'Call' },
  meeting: { icon: 'cal',     tone: 'purple',  label: 'Meeting' },
  stage:   { icon: 'layers',  tone: 'amber',   label: 'Stage change' },
  task:    { icon: 'check',   tone: 'neutral', label: 'Task' },
  won:     { icon: 'star',    tone: 'green',   label: 'Closed won' },
  lost:    { icon: 'x',       tone: 'red',     label: 'Closed lost' },
};

function CRMActivity({ onLogActivity }) {
  const [filter, setFilter] = useState('all');
  const filtered = filter === 'all' ? CRM_ACTIVITY : CRM_ACTIVITY.filter(a => a.kind === filter);

  // Group by day
  const groups = {};
  filtered.forEach(a => {
    const d = new Date(a.when);
    const day = d.toDateString();
    (groups[day] = groups[day] || []).push(a);
  });

  return (
    <>
      <div className="toolbar">
        <div className="row gap-2">
          {[['all','All'],['note','Notes'],['email','Email'],['call','Calls'],['meeting','Meetings'],['stage','Stage changes'],['won','Wins']].map(([id, label]) => (
            <button key={id} onClick={() => setFilter(id)}
                    className={`btn btn-sm ${filter === id ? 'btn-primary' : 'btn-ghost'}`}>{label}</button>
          ))}
        </div>
        <div style={{ marginLeft: 'auto' }} className="row gap-2">
          <Button variant="secondary" size="sm" icon="filter">By rep</Button>
          <Button variant="primary" size="sm" icon="plus" onClick={onLogActivity}>Log activity</Button>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: '2fr 1fr', gap: 16 }}>
        <div className="card">
          <div className="col" style={{ gap: 14 }}>
            {Object.entries(groups).map(([day, items]) => (
              <div key={day}>
                <div className="dim" style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: 0.5, fontWeight: 600, marginBottom: 8 }}>
                  {new Date(day).toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}
                </div>
                <div className="col" style={{ gap: 10 }}>
                  {items.map(a => {
                    const rep = getEmployee(a.rep);
                    const meta = KIND_META[a.kind];
                    return (
                      <div key={a.id} className="row gap-3" style={{ alignItems: 'flex-start', padding: '10px 12px', background: 'var(--bg-elev)', borderRadius: 8 }}>
                        <div style={{ width: 28, height: 28, borderRadius: 999, background: `var(--${meta.tone === 'neutral' ? 'border-strong' : meta.tone})`, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                          <Icon name={meta.icon} size={13} />
                        </div>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div className="row gap-2" style={{ marginBottom: 2, flexWrap: 'wrap' }}>
                            <strong style={{ fontSize: 12.5 }}>{rep?.name.split(' ')[0]}</strong>
                            <span className="muted" style={{ fontSize: 12 }}>{meta.label.toLowerCase()} on</span>
                            <span style={{ fontSize: 12.5, fontWeight: 500 }}>{a.target.name}</span>
                            <span className="dim mono" style={{ fontSize: 11, marginLeft: 'auto' }}>{new Date(a.when).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })}</span>
                          </div>
                          <div style={{ fontSize: 12.5, color: 'var(--text)', lineHeight: 1.5 }}>{a.body}</div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="col" style={{ gap: 16 }}>
          <div className="card">
            <div className="card-h"><h3>Activity by rep</h3></div>
            <div className="col" style={{ gap: 8 }}>
              {['e20','e21','e22','e4'].map(rid => {
                const r = getEmployee(rid);
                const count = CRM_ACTIVITY.filter(a => a.rep === rid).length;
                return (
                  <div key={rid} className="row gap-2">
                    <Avatar person={r} size={26} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 500 }}>{r?.name}</div>
                      <div className="dim" style={{ fontSize: 11 }}>{r?.title}</div>
                    </div>
                    <span className="mono" style={{ fontSize: 12 }}>{count} this week</span>
                  </div>
                );
              })}
            </div>
          </div>
          <div className="card">
            <div className="card-h"><h3>Activity mix</h3><div className="sub">Last 30 days</div></div>
            <div className="col" style={{ gap: 6 }}>
              {[['Email', 84, 'blue'],['Call', 38, 'teal'],['Meeting', 27, 'purple'],['Note', 64, 'orange'],['Stage', 41, 'amber']].map(([k,c,t]) => (
                <div key={k} className="row gap-2" style={{ fontSize: 12 }}>
                  <span style={{ width: 60 }}>{k}</span>
                  <div style={{ flex: 1, height: 12, background: 'var(--bg-canvas)', borderRadius: 3 }}>
                    <div style={{ width: `${c/84*100}%`, height: '100%', background: `var(--${t})`, borderRadius: 3 }} />
                  </div>
                  <span className="mono dim" style={{ width: 28, textAlign: 'right' }}>{c}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

window.CRMActivity = CRMActivity;

// ─────────────────────────────────────────────────────────────────────────────
// New Deal modal — focused 2-step deal creation
// ─────────────────────────────────────────────────────────────────────────────

function DollarInput({ label, value, onChange }) {
  return (
    <div className="field" style={{ margin: 0 }}>
      <label>{label}</label>
      <div style={{ position: 'relative' }}>
        <span style={{ position: 'absolute', left: 12, top: 9, color: 'var(--text-muted)', fontSize: 13.5 }}>$</span>
        <input type="number" min="0" step="500" value={value}
               onChange={e => onChange(+e.target.value)}
               style={{ paddingLeft: 24, width: '100%' }} />
      </div>
    </div>
  );
}

function NewDealModal({ onClose, onCreate }) {
  const D = window.HitcentsData;
  const [step, setStep] = useState(1);
  const [draft, setDraft] = useState({
    name: '',
    customer: '',
    customerName: '',
    isNewCustomer: false,
    daas: 30000,
    seats: 40,
    seatPrice: 500,
    setup: 8000,
    mvp: 0,
    stage: 'qual',
    probability: 40,
    close: '2026-08-15',
    owner: 'e20',
    source: 'Inbound',
    nextStep: '',
    contactName: '',
    contactRole: '',
    contactEmail: '',
    tags: [],
  });

  const dealValue = (draft.daas || 0) + (draft.seats || 0) * (draft.seatPrice || 0) + (draft.setup || 0) + (draft.mvp || 0);

  function set(patch) { setDraft(d => ({ ...d, ...patch })); }

  // Auto-prefill deal name when customer is picked
  function pickCustomer(cid) {
    if (cid === '_new') {
      set({ customer: '', isNewCustomer: true });
      return;
    }
    const c = D.CUSTOMERS.find(x => x.id === cid);
    set({
      customer: cid,
      isNewCustomer: false,
      name: draft.name || (c ? `${c.name} — ` : ''),
      owner: c?.owner || draft.owner,
    });
  }

  // Auto-set probability when stage changes
  function pickStage(sid) {
    const probMap = { lead: 15, qual: 35, prop: 55, negt: 75, won: 100, lost: 0 };
    set({ stage: sid, probability: probMap[sid] ?? draft.probability });
  }

  function submit() {
    const id = `d${D.DEALS.length + 1}-${Date.now().toString(36)}`;
    const deal = {
      id,
      name: draft.name || 'Untitled deal',
      customer: draft.customer || null,
      customerName: draft.isNewCustomer ? draft.customerName : undefined,
      value: dealValue,
      daas: draft.daas, seats: draft.seats, seatPrice: draft.seatPrice, setup: draft.setup, mvp: draft.mvp,
      stage: draft.stage,
      owner: draft.owner,
      close: draft.close,
      probability: draft.probability,
      source: draft.source,
    };
    onCreate(deal);
  }

  const customer = draft.customer ? getCustomer(draft.customer) : null;
  const owner = getEmployee(draft.owner);
  const stage = D.DEAL_STAGES.find(s => s.id === draft.stage);
  const weightedValue = dealValue * draft.probability / 100;

  return (
    <div className="cmdk-scrim" onClick={onClose} style={{ paddingTop: '6vh' }}>
      <div onClick={e => e.stopPropagation()}
           style={{ width: 760, maxWidth: '94vw', maxHeight: '88vh', background: 'var(--bg-card)', borderRadius: 14, border: '1px solid var(--border)', boxShadow: 'var(--shadow-lg)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>

        <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div className="row gap-2" style={{ marginBottom: 4 }}>
              <span className="dim" style={{ fontSize: 11 }}>Step {step} of 2</span>
              <div style={{ display: 'flex', gap: 4 }}>
                {[1,2].map(s => (
                  <div key={s} style={{ width: 36, height: 4, borderRadius: 2, background: s <= step ? 'var(--brand-orange)' : 'var(--border-strong)' }} />
                ))}
              </div>
            </div>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>
              {step === 1 ? 'New deal' : 'Deal details & next step'}
            </h2>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>

        <div style={{ padding: 24, overflowY: 'auto', flex: 1 }}>
          {step === 1 && (
            <div className="grid" style={{ gridTemplateColumns: '1.4fr 1fr', gap: 22 }}>
              <div className="col" style={{ gap: 16 }}>
                <div className="field" style={{ margin: 0 }}>
                  <label>Customer</label>
                  <select value={draft.isNewCustomer ? '_new' : (draft.customer || '')} onChange={e => pickCustomer(e.target.value)}>
                    <option value="">— Select a customer —</option>
                    {D.CUSTOMERS.map(c => <option key={c.id} value={c.id}>{c.name} {c.mrr ? `· $${(c.mrr/1000).toFixed(1)}k MRR` : '· prospect'}</option>)}
                    <option value="_new">＋ New prospect (not yet in CRM)</option>
                  </select>
                </div>

                {draft.isNewCustomer && (
                  <div className="field" style={{ margin: 0 }}>
                    <label>New prospect name</label>
                    <input autoFocus placeholder="Acme Robotics" value={draft.customerName} onChange={e => set({ customerName: e.target.value })} />
                    <div className="dim" style={{ fontSize: 11, marginTop: 4 }}>A customer record will be auto-created and linked to this deal.</div>
                  </div>
                )}

                <div className="field" style={{ margin: 0 }}>
                  <label>Deal name</label>
                  <input placeholder="e.g. Acme — Platform expansion" value={draft.name} onChange={e => set({ name: e.target.value })} />
                </div>

                <div className="field" style={{ margin: 0 }}>
                  <label>Contract value</label>
                  <div className="newdeal-value-grid">
                    <DollarInput label="DaaS retainer / yr" value={draft.daas} onChange={v => set({ daas: v })} />
                    <DollarInput label="Setup fee" value={draft.setup} onChange={v => set({ setup: v })} />
                    <div className="field" style={{ margin: 0 }}>
                      <label>Seat count</label>
                      <input type="number" min="0" step="1" value={draft.seats} onChange={e => set({ seats: +e.target.value })} />
                    </div>
                    <DollarInput label="Seat price" value={draft.seatPrice} onChange={v => set({ seatPrice: v })} />
                    <DollarInput label="MVP Jumpstart" value={draft.mvp} onChange={v => set({ mvp: v })} />
                    <div className="field" style={{ margin: 0 }}>
                      <label>Expected close</label>
                      <input type="date" value={draft.close} onChange={e => set({ close: e.target.value })} />
                    </div>
                  </div>
                  <div className="newdeal-value-total">
                    <span>Total contract value</span>
                    <span className="mono">{fmtMoneyFull(dealValue)}</span>
                  </div>
                </div>

                <div className="field" style={{ margin: 0 }}>
                  <label>Stage</label>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
                    {D.DEAL_STAGES.filter(s => !['won','lost'].includes(s.id)).map(s => (
                      <button key={s.id} type="button" onClick={() => pickStage(s.id)}
                              className={`btn btn-sm ${draft.stage === s.id ? '' : 'btn-secondary'}`}
                              style={draft.stage === s.id ? { background: s.color, color: '#fff', borderColor: s.color, justifyContent: 'center' } : { justifyContent: 'center' }}>
                        {s.name}
                      </button>
                    ))}
                  </div>
                </div>

                <div className="grid g-2" style={{ gap: 12 }}>
                  <div className="field" style={{ margin: 0 }}>
                    <label>Owner</label>
                    <select value={draft.owner} onChange={e => set({ owner: e.target.value })}>
                      {D.EMPLOYEES.filter(e => e.dept === 'sal' || e.id === 'e1').map(e => (
                        <option key={e.id} value={e.id}>{e.name} · {e.title}</option>
                      ))}
                    </select>
                  </div>
                  <div className="field" style={{ margin: 0 }}>
                    <label>Source</label>
                    <select value={draft.source} onChange={e => set({ source: e.target.value })}>
                      {['Inbound','Outbound','Referral','Partner','Expansion','Renewal','Event'].map(s => <option key={s}>{s}</option>)}
                    </select>
                  </div>
                </div>
              </div>

              {/* Live preview card */}
              <div>
                <div className="dim" style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: 0.6, fontWeight: 600, marginBottom: 8 }}>Live preview</div>
                <div className="deal-card" style={{ cursor: 'default', padding: 14 }}>
                  <div className="name" style={{ fontSize: 13.5 }}>{draft.name || 'Untitled deal'}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{customer?.name || draft.customerName || 'No customer yet'}</div>
                  <div className="meta" style={{ marginTop: 10 }}>
                    <span className="mono" style={{ color: 'var(--brand-wine)', fontWeight: 600, fontSize: 14 }}>{fmtMoneyFull(dealValue)}</span>
                    <div className="row gap-2">
                      <span style={{ fontSize: 11 }}>{draft.probability}%</span>
                      <Avatar person={owner} size={20} />
                    </div>
                  </div>
                  <div className="divider" style={{ margin: '10px 0' }} />
                  <div className="row spread" style={{ fontSize: 11 }}>
                    <span className="muted">Stage</span>
                    <Badge style={{ background: stage.color + '22', color: stage.color }}>{stage.name}</Badge>
                  </div>
                  <div className="row spread" style={{ fontSize: 11, marginTop: 4 }}>
                    <span className="muted">Weighted</span>
                    <span className="mono" style={{ fontWeight: 500 }}>{fmtMoneyFull(Math.round(weightedValue))}</span>
                  </div>
                  <div className="row spread" style={{ fontSize: 11, marginTop: 4 }}>
                    <span className="muted">Close</span>
                    <span className="mono">{fmtDate(draft.close)}</span>
                  </div>
                </div>

                {customer && (
                  <div className="card" style={{ marginTop: 14, padding: 12, background: 'var(--bg-elev)' }}>
                    <div className="row gap-2" style={{ marginBottom: 6 }}>
                      <Icon name="bolt" size={12} style={{ color: 'var(--brand-orange)' }} />
                      <strong style={{ fontSize: 11.5 }}>Auto-filled from {customer.name}</strong>
                    </div>
                    <ul style={{ margin: 0, padding: '0 0 0 16px', fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.5 }}>
                      <li>Account tier: {customer.tier}</li>
                      <li>Industry: {customer.industry}</li>
                      <li>Owner: {getEmployee(customer.owner)?.name}</li>
                      <li>Customer since {fmtDateShort(customer.since)}</li>
                    </ul>
                  </div>
                )}
              </div>
            </div>
          )}

          {step === 2 && (
            <div className="col" style={{ gap: 18 }}>
              <div className="field" style={{ margin: 0 }}>
                <label>Primary contact at {customer?.name || draft.customerName || 'the customer'}</label>
                <div className="grid" style={{ gridTemplateColumns: '1.4fr 1fr 1.2fr', gap: 8 }}>
                  <input placeholder="Name" value={draft.contactName} onChange={e => set({ contactName: e.target.value })}
                         style={{ border: '1px solid var(--border-strong)', borderRadius: 8, padding: '9px 12px', fontSize: 13.5 }} />
                  <input placeholder="Role" value={draft.contactRole} onChange={e => set({ contactRole: e.target.value })}
                         style={{ border: '1px solid var(--border-strong)', borderRadius: 8, padding: '9px 12px', fontSize: 13.5 }} />
                  <input placeholder="Email" type="email" value={draft.contactEmail} onChange={e => set({ contactEmail: e.target.value })}
                         style={{ border: '1px solid var(--border-strong)', borderRadius: 8, padding: '9px 12px', fontSize: 13.5 }} />
                </div>
              </div>

              <div className="field" style={{ margin: 0 }}>
                <label>Win probability — {draft.probability}%</label>
                <input type="range" min="0" max="100" step="5" value={draft.probability} onChange={e => set({ probability: +e.target.value })} />
                <div className="row spread" style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>
                  <span>0% — Long shot</span><span>50% — Coin flip</span><span>100% — Committed</span>
                </div>
                <div style={{ marginTop: 6, fontSize: 12 }}>
                  Weighted value: <strong className="mono">{fmtMoneyFull(Math.round(weightedValue))}</strong>
                </div>
              </div>

              <div className="field" style={{ margin: 0 }}>
                <label>Next step</label>
                <textarea rows={3} placeholder="What's the immediate next action? (e.g. Send proposal v2 by Tuesday, schedule technical deep-dive with their CTO)"
                          value={draft.nextStep} onChange={e => set({ nextStep: e.target.value })} />
              </div>

              <div className="field" style={{ margin: 0 }}>
                <label>Tags</label>
                <div className="row gap-2" style={{ flexWrap: 'wrap' }}>
                  {['expansion','renewal','enterprise','mid-market','smb','technical-fit-risk','procurement','poc','reference','referral'].map(tag => {
                    const on = draft.tags.includes(tag);
                    return (
                      <button key={tag} type="button"
                              onClick={() => set({ tags: on ? draft.tags.filter(t => t !== tag) : [...draft.tags, tag] })}
                              className={`btn btn-sm ${on ? 'btn-primary' : 'btn-secondary'}`}>
                        {on && <Icon name="check" size={10} stroke={3} />}
                        #{tag}
                      </button>
                    );
                  })}
                </div>
              </div>

              <div className="card" style={{ background: 'var(--brand-orange-tint)', borderColor: 'rgba(224,85,43,0.35)' }}>
                <div className="row gap-2" style={{ marginBottom: 6 }}>
                  <Icon name="bolt" size={13} style={{ color: 'var(--brand-orange)' }} />
                  <strong style={{ fontSize: 12.5 }}>What happens when you create this deal</strong>
                </div>
                <ul style={{ margin: 0, padding: '0 0 0 20px', fontSize: 12.5, lineHeight: 1.6 }}>
                  <li>Added to the {stage.name} column of your pipeline</li>
                  <li>{owner?.name} becomes the owner and is notified in Slack</li>
                  {draft.isNewCustomer && draft.customerName && <li>New customer record <strong>{draft.customerName}</strong> created</li>}
                  {draft.contactName && <li>Contact <strong>{draft.contactName}</strong> linked to the account</li>}
                  {draft.nextStep && <li>Next step logged as a task on the deal timeline</li>}
                  {dealValue >= 100000 && <li>⚠️ Over $100k — auto-tagged for legal review on contract</li>}
                </ul>
              </div>
            </div>
          )}
        </div>

        <div style={{ padding: '14px 24px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', background: 'var(--bg-elev)' }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <div className="row gap-2">
            {step > 1 && <Button variant="secondary" icon="chev_l" onClick={() => setStep(1)}>Back</Button>}
            {step < 2 && <Button variant="primary" iconRight="chev_r" disabled={!draft.name || (!draft.customer && !draft.customerName)} onClick={() => setStep(2)}>Continue</Button>}
            {step === 2 && <Button variant="primary" icon="check" onClick={submit}>Create deal</Button>}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// New Company modal — single-screen create flow
// ─────────────────────────────────────────────────────────────────────────────

function crmAvatar(name, seed) {
  return { initials: (name.trim().split(/\s+/).map(s => s[0]).slice(0, 2).join('') || '?').toUpperCase(), hue: (seed * 47) % 360 };
}

function NewCompanyModal({ onClose, onCreate }) {
  const D = window.HitcentsData;
  const [draft, setDraft] = useState({
    name: '', website: '', hq: '', industry: 'Technology', size: '',
    tier: 'Mid-market', health: 'Prospect', owner: 'e20', mrr: 0, tags: [],
  });
  function set(patch) { setDraft(d => ({ ...d, ...patch })); }

  const owner = getEmployee(draft.owner);
  const canCreate = draft.name.trim().length > 0;
  const TIERS = ['SMB', 'Mid-market', 'Enterprise'];
  const HEALTHS = ['Prospect', 'New', 'Healthy', 'At risk'];
  const INDUSTRIES = ['Technology','Robotics','Manufacturing','Healthcare','Biotech','Finance','Logistics','Education','Creative','Retail','Energy','Media','Other'];
  const healthTone = draft.health === 'Healthy' ? 'green' : draft.health === 'At risk' ? 'red' : draft.health === 'Prospect' ? 'neutral' : 'blue';

  function submit() {
    const company = {
      id: `c${D.CUSTOMERS.length + 1}-${Date.now().toString(36)}`,
      name: draft.name.trim(),
      industry: draft.industry,
      size: String(draft.size || '').trim() || '—',
      mrr: +draft.mrr || 0,
      since: draft.health === 'Prospect' ? null : '2026-06-23',
      owner: draft.owner,
      tier: draft.tier,
      health: draft.health,
      tags: draft.tags,
      website: draft.website.trim().replace(/^https?:\/\//, ''),
      hq: draft.hq.trim(),
    };
    onCreate(company);
  }

  return (
    <div className="cmdk-scrim" onClick={onClose} style={{ paddingTop: '6vh' }}>
      <div onClick={e => e.stopPropagation()}
           style={{ width: 720, maxWidth: '94vw', maxHeight: '88vh', background: 'var(--bg-card)', borderRadius: 14, border: '1px solid var(--border)', boxShadow: 'var(--shadow-lg)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>New company</h2>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>

        <div style={{ padding: 24, overflowY: 'auto', flex: 1 }}>
          <div className="grid" style={{ gridTemplateColumns: '1.5fr 1fr', gap: 22 }}>
            <div className="col" style={{ gap: 16 }}>
              <div className="field" style={{ margin: 0 }}>
                <label>Company name</label>
                <input autoFocus placeholder="Acme Robotics" value={draft.name} onChange={e => set({ name: e.target.value })} />
              </div>

              <div className="grid g-2" style={{ gap: 12 }}>
                <div className="field" style={{ margin: 0 }}>
                  <label>Website</label>
                  <input placeholder="acme.com" value={draft.website} onChange={e => set({ website: e.target.value })} />
                </div>
                <div className="field" style={{ margin: 0 }}>
                  <label>Headquarters</label>
                  <input placeholder="Austin, TX" value={draft.hq} onChange={e => set({ hq: e.target.value })} />
                </div>
              </div>

              <div className="grid g-2" style={{ gap: 12 }}>
                <div className="field" style={{ margin: 0 }}>
                  <label>Industry</label>
                  <select value={draft.industry} onChange={e => set({ industry: e.target.value })}>
                    {INDUSTRIES.map(s => <option key={s}>{s}</option>)}
                  </select>
                </div>
                <div className="field" style={{ margin: 0 }}>
                  <label>Headcount</label>
                  <input type="number" min="0" step="1" placeholder="250" value={draft.size} onChange={e => set({ size: e.target.value })} />
                </div>
              </div>

              <div className="field" style={{ margin: 0 }}>
                <label>Account tier</label>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
                  {TIERS.map(tt => (
                    <button key={tt} type="button" onClick={() => set({ tier: tt })}
                            className={`btn btn-sm ${draft.tier === tt ? 'btn-primary' : 'btn-secondary'}`}
                            style={{ justifyContent: 'center' }}>{tt}</button>
                  ))}
                </div>
              </div>

              <div className="field" style={{ margin: 0 }}>
                <label>Relationship</label>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
                  {HEALTHS.map(hh => (
                    <button key={hh} type="button" onClick={() => set({ health: hh })}
                            className={`btn btn-sm ${draft.health === hh ? 'btn-primary' : 'btn-secondary'}`}
                            style={{ justifyContent: 'center' }}>{hh}</button>
                  ))}
                </div>
              </div>

              <div className="grid g-2" style={{ gap: 12 }}>
                <div className="field" style={{ margin: 0 }}>
                  <label>Account owner</label>
                  <select value={draft.owner} onChange={e => set({ owner: e.target.value })}>
                    {D.EMPLOYEES.filter(e => e.dept === 'sal' || e.id === 'e1').map(e => (
                      <option key={e.id} value={e.id}>{e.name} · {e.title}</option>
                    ))}
                  </select>
                </div>
                <DollarInput label="Current MRR" value={draft.mrr} onChange={v => set({ mrr: v })} />
              </div>
            </div>

            {/* Live preview */}
            <div>
              <div className="dim" style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: 0.6, fontWeight: 600, marginBottom: 8 }}>Live preview</div>
              <div className="card" style={{ padding: 14 }}>
                <div className="row gap-2" style={{ marginBottom: 10 }}>
                  <div className="company-mark">{(draft.name.trim()[0] || 'A').toUpperCase()}</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{draft.name.trim() || 'New company'}</div>
                    <div className="dim" style={{ fontSize: 11.5 }}>{[draft.hq, draft.website].filter(Boolean).join(' · ') || 'Location · website'}</div>
                  </div>
                </div>
                <div className="row gap-2" style={{ flexWrap: 'wrap', marginBottom: 10 }}>
                  <Badge tone={draft.tier === 'Enterprise' ? 'purple' : draft.tier === 'Mid-market' ? 'blue' : 'neutral'}>{draft.tier}</Badge>
                  <Badge tone={healthTone}>{draft.health}</Badge>
                </div>
                <div className="row spread" style={{ fontSize: 11, marginTop: 4 }}>
                  <span className="muted">Industry</span><span>{draft.industry}</span>
                </div>
                <div className="row spread" style={{ fontSize: 11, marginTop: 4 }}>
                  <span className="muted">MRR</span><span className="mono">{draft.mrr ? fmtMoneyFull(+draft.mrr) : '—'}</span>
                </div>
                <div className="row spread" style={{ fontSize: 11, marginTop: 4 }}>
                  <span className="muted">Owner</span><span>{owner?.name}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div style={{ padding: '14px 24px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', background: 'var(--bg-elev)' }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <div className="row gap-2">
            {!canCreate && <span className="dim" style={{ fontSize: 11.5 }}>Company name required</span>}
            <Button variant="primary" icon="check" disabled={!canCreate} onClick={submit}>Create company</Button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// New Contact modal — single-screen create flow
// ─────────────────────────────────────────────────────────────────────────────

function NewContactModal({ onClose, onCreate, defaultCompany }) {
  const D = window.HitcentsData;
  const [draft, setDraft] = useState({
    name: '', title: '', companyId: defaultCompany || '', email: '', phone: '',
    role: '', primary: false, status: 'Active',
  });
  function set(patch) { setDraft(d => ({ ...d, ...patch })); }

  const company = draft.companyId ? getCustomer(draft.companyId) : null;
  const ROLES = ['Economic buyer', 'Decision maker', 'Champion', 'User', 'Procurement', 'Legal / compliance', 'Influencer'];
  const canCreate = draft.name.trim().length > 0 && !!draft.companyId;

  // Suggested email from first name + company website
  const suggestedEmail = (draft.name.trim() && company?.website)
    ? `${draft.name.trim().split(/\s+/)[0].toLowerCase()}@${company.website}` : '';

  function submit() {
    const contact = {
      id: `ct${(D.CONTACTS || []).length + 1}-${Date.now().toString(36)}`,
      name: draft.name.trim(),
      title: draft.title.trim() || '—',
      companyId: draft.companyId,
      email: draft.email.trim() || suggestedEmail,
      phone: draft.phone.trim() || '—',
      primary: draft.primary,
      status: draft.status,
      role: draft.role || undefined,
      avatar: crmAvatar(draft.name, (D.CONTACTS || []).length + 41),
    };
    onCreate(contact);
  }

  return (
    <div className="cmdk-scrim" onClick={onClose} style={{ paddingTop: '6vh' }}>
      <div onClick={e => e.stopPropagation()}
           style={{ width: 680, maxWidth: '94vw', maxHeight: '88vh', background: 'var(--bg-card)', borderRadius: 14, border: '1px solid var(--border)', boxShadow: 'var(--shadow-lg)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>New contact</h2>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>

        <div style={{ padding: 24, overflowY: 'auto', flex: 1 }}>
          {/* Identity row */}
          <div className="row gap-3" style={{ marginBottom: 18, alignItems: 'center' }}>
            <Avatar person={{ name: draft.name.trim() || '?', avatar: crmAvatar(draft.name || '?', 41) }} size={52} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 16 }}>{draft.name.trim() || 'New contact'}</div>
              <div className="dim" style={{ fontSize: 12.5 }}>{[draft.title, company?.name].filter(Boolean).join(' · ') || 'Title · company'}</div>
            </div>
            {draft.primary && <Badge tone="orange">Primary</Badge>}
          </div>

          <div className="grid g-2" style={{ gap: 12, marginBottom: 14 }}>
            <div className="field" style={{ margin: 0 }}>
              <label>Full name</label>
              <input autoFocus placeholder="Jordan Wu" value={draft.name} onChange={e => set({ name: e.target.value })} />
            </div>
            <div className="field" style={{ margin: 0 }}>
              <label>Title</label>
              <input placeholder="VP Engineering" value={draft.title} onChange={e => set({ title: e.target.value })} />
            </div>
          </div>

          <div className="grid g-2" style={{ gap: 12, marginBottom: 14 }}>
            <div className="field" style={{ margin: 0 }}>
              <label>Company</label>
              <select value={draft.companyId} onChange={e => set({ companyId: e.target.value })}>
                <option value="">— Select a company —</option>
                {D.CUSTOMERS.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
            <div className="field" style={{ margin: 0 }}>
              <label>Buying role</label>
              <select value={draft.role} onChange={e => set({ role: e.target.value })}>
                <option value="">— None —</option>
                {ROLES.map(r => <option key={r}>{r}</option>)}
              </select>
            </div>
          </div>

          <div className="grid g-2" style={{ gap: 12, marginBottom: 14 }}>
            <div className="field" style={{ margin: 0 }}>
              <label>Email</label>
              <input type="email" placeholder={suggestedEmail || 'name@company.com'} value={draft.email} onChange={e => set({ email: e.target.value })} />
              {!draft.email && suggestedEmail && <div className="dim" style={{ fontSize: 11, marginTop: 4 }}>Suggested: {suggestedEmail}</div>}
            </div>
            <div className="field" style={{ margin: 0 }}>
              <label>Phone</label>
              <input placeholder="+1 555 555 0100" value={draft.phone} onChange={e => set({ phone: e.target.value })} />
            </div>
          </div>

          <label className="nc-autorenew" style={{ marginTop: 4 }}>
            <input type="checkbox" checked={draft.primary} onChange={e => set({ primary: e.target.checked })} />
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 500, fontSize: 13 }}>Primary contact</div>
              <div className="dim" style={{ fontSize: 11 }}>{company ? `Becomes the main relationship owner at ${company.name}` : 'The main relationship owner for the company'}</div>
            </div>
          </label>
        </div>

        <div style={{ padding: '14px 24px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', background: 'var(--bg-elev)' }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <div className="row gap-2">
            {!canCreate && <span className="dim" style={{ fontSize: 11.5 }}>Name & company required</span>}
            <Button variant="primary" icon="check" disabled={!canCreate} onClick={submit}>Create contact</Button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Log Activity modal — note / email / call / meeting / task
// ─────────────────────────────────────────────────────────────────────────────

function LogActivityModal({ context, onClose, onLog, deals }) {
  const D = window.HitcentsData;
  const [kind, setKind] = useState('note');
  const [dealId, setDealId] = useState(context?.dealId || '');
  const [body, setBody] = useState('');
  const [outcome, setOutcome] = useState('positive');
  const [duration, setDuration] = useState(20);
  const [followUp, setFollowUp] = useState(true);
  const [followUpDate, setFollowUpDate] = useState('2026-05-22');
  const [followUpTask, setFollowUpTask] = useState('');
  const [updateStage, setUpdateStage] = useState(false);
  const [newStage, setNewStage] = useState('');
  const [logged, setLogged] = useState(false);

  const kinds = [
    { id: 'note',    label: 'Note',         icon: 'pencil',  tone: 'orange',  desc: 'Capture a thought, prep, or context.' },
    { id: 'email',   label: 'Email',        icon: 'mail',    tone: 'blue',    desc: 'Log an email you sent or received.' },
    { id: 'call',    label: 'Call',         icon: 'phone',   tone: 'teal',    desc: 'Log a phone or Zoom 1-on-1.' },
    { id: 'meeting', label: 'Meeting',      icon: 'cal',     tone: 'purple',  desc: 'Log a multi-attendee meeting or demo.' },
    { id: 'task',    label: 'Task',         icon: 'check',   tone: 'neutral', desc: 'Add a to-do for yourself or teammate.' },
  ];
  const selectedKind = kinds.find(k => k.id === kind);
  const deal = deals.find(d => d.id === dealId);
  const customer = deal?.customer ? getCustomer(deal.customer) : null;

  function submit() {
    setLogged(true);
    setTimeout(() => onLog(), 1100);
  }

  if (logged) {
    return (
      <div className="cmdk-scrim" onClick={onClose} style={{ paddingTop: '20vh' }}>
        <div onClick={e => e.stopPropagation()} style={{ width: 360, background: 'var(--bg-card)', borderRadius: 14, border: '1px solid var(--border)', padding: 32, textAlign: 'center', boxShadow: 'var(--shadow-lg)' }}>
          <div style={{ width: 56, height: 56, borderRadius: 999, background: 'var(--green)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: '#fff', marginBottom: 14 }}>
            <Icon name="check" size={26} stroke={3} />
          </div>
          <h3 style={{ margin: '0 0 4px', fontSize: 17, fontWeight: 600 }}>Activity logged</h3>
          <p className="muted" style={{ fontSize: 13, margin: 0 }}>Saved to {deal ? deal.name : 'the CRM activity feed'}.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="cmdk-scrim" onClick={onClose} style={{ paddingTop: '6vh' }}>
      <div onClick={e => e.stopPropagation()}
           style={{ width: 720, maxWidth: '94vw', maxHeight: '88vh', background: 'var(--bg-card)', borderRadius: 14, border: '1px solid var(--border)', boxShadow: 'var(--shadow-lg)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>

        <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>Log activity</h2>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>Capture what just happened so the next teammate doesn't have to ask.</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>

        {/* Activity type tabs */}
        <div style={{ padding: '12px 24px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 6, paddingBottom: 12 }}>
            {kinds.map(k => {
              const active = kind === k.id;
              return (
                <button key={k.id} onClick={() => setKind(k.id)}
                        style={{
                          padding: '10px 8px', border: `1px solid ${active ? `var(--${k.tone === 'neutral' ? 'border-strong' : k.tone === 'orange' ? 'brand-orange' : k.tone})` : 'var(--border)'}`,
                          background: active ? (k.tone === 'neutral' ? 'var(--bg-elev)' : `var(--${k.tone === 'orange' ? 'brand-orange' : k.tone}-tint)`) : 'transparent',
                          color: active ? `var(--${k.tone === 'neutral' ? 'text' : k.tone === 'orange' ? 'brand-orange' : k.tone})` : 'var(--text)',
                          borderRadius: 8, cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                  <Icon name={k.icon} size={16} />
                  <span style={{ fontSize: 12.5, fontWeight: 500 }}>{k.label}</span>
                </button>
              );
            })}
          </div>
        </div>

        <div style={{ padding: 22, overflowY: 'auto', flex: 1 }}>
          {/* Linked deal */}
          <div className="field" style={{ margin: 0, marginBottom: 16 }}>
            <label>Linked deal or account</label>
            <select value={dealId} onChange={e => setDealId(e.target.value)}>
              <option value="">— No specific deal (account-level activity) —</option>
              {deals.filter(d => !['won','lost'].includes(d.stage)).map(d => {
                const c = d.customer ? getCustomer(d.customer) : null;
                return <option key={d.id} value={d.id}>{c?.name || d.customerName} — {d.name.split(' — ').slice(-1)[0]} (${(d.value/1000).toFixed(0)}k)</option>;
              })}
            </select>
            {deal && customer && (
              <div className="row gap-2" style={{ marginTop: 8, padding: '8px 10px', background: 'var(--bg-elev)', borderRadius: 6 }}>
                <Avatar person={getEmployee(deal.owner)} size={22} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500 }}>{deal.name}</div>
                  <div className="dim" style={{ fontSize: 11 }}>{customer.name} · {D.DEAL_STAGES.find(s => s.id === deal.stage)?.name} · {fmtMoneyFull(deal.value)}</div>
                </div>
              </div>
            )}
          </div>

          {/* Kind-specific quick fields */}
          {kind === 'call' && (
            <div className="grid g-2" style={{ gap: 12, marginBottom: 14 }}>
              <div className="field" style={{ margin: 0 }}>
                <label>Duration — {duration} min</label>
                <input type="range" min="5" max="120" step="5" value={duration} onChange={e => setDuration(+e.target.value)} />
              </div>
              <div className="field" style={{ margin: 0 }}>
                <label>Outcome</label>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 4 }}>
                  {[['positive','😀 Positive','green'],['neutral','😐 Neutral','neutral'],['negative','😟 Concern','red']].map(([id,label,tone]) => (
                    <button key={id} type="button" onClick={() => setOutcome(id)}
                            className={`btn btn-sm ${outcome === id ? 'btn-primary' : 'btn-secondary'}`}
                            style={{ justifyContent: 'center' }}>{label}</button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {kind === 'meeting' && (
            <div className="grid g-2" style={{ gap: 12, marginBottom: 14 }}>
              <div className="field" style={{ margin: 0 }}>
                <label>Meeting type</label>
                <select>
                  <option>Discovery</option>
                  <option>Demo</option>
                  <option>Technical deep-dive</option>
                  <option>QBR</option>
                  <option>Procurement / Legal</option>
                  <option>Stakeholder intro</option>
                </select>
              </div>
              <div className="field" style={{ margin: 0 }}>
                <label>Attendees on their side</label>
                <input placeholder="e.g. CTO, VP Eng, security lead" />
              </div>
            </div>
          )}

          {kind === 'email' && (
            <div className="field" style={{ margin: 0, marginBottom: 14 }}>
              <label>Subject line</label>
              <input placeholder="e.g. Re: Proposal v3 — questions on data residency" />
            </div>
          )}

          {kind === 'task' && (
            <div className="grid g-2" style={{ gap: 12, marginBottom: 14 }}>
              <div className="field" style={{ margin: 0 }}>
                <label>Due</label>
                <input type="date" defaultValue="2026-05-20" />
              </div>
              <div className="field" style={{ margin: 0 }}>
                <label>Assignee</label>
                <select defaultValue="e20">
                  {D.EMPLOYEES.filter(e => e.dept === 'sal' || e.id === 'e1').map(e => <option key={e.id} value={e.id}>{e.name}</option>)}
                </select>
              </div>
            </div>
          )}

          {/* Main body */}
          <div className="field" style={{ margin: 0, marginBottom: 14 }}>
            <label>
              {kind === 'note' && 'What did you observe?'}
              {kind === 'email' && 'Email summary'}
              {kind === 'call' && 'What was discussed?'}
              {kind === 'meeting' && 'Meeting notes'}
              {kind === 'task' && 'What needs to be done?'}
            </label>
            <textarea rows={5} autoFocus
                      placeholder={
                        kind === 'note'    ? "Champion expressed interest in EU rollout. Pricing concerns flagged — wants to see ROI model." :
                        kind === 'email'   ? 'Replied with revised SOW. Awaiting their legal redline.' :
                        kind === 'call'    ? '30 min discovery. Stack on AWS + Snowflake. Pain: long ETL pipelines. Budget owner: VP Eng. Next step: technical deep-dive next Tuesday.' :
                        kind === 'meeting' ? 'Demo with full team. Strong reaction to async workflow runner. Concern around SSO compatibility — sent docs after.' :
                                             'Send pricing comparison for 50-seat upgrade by Friday.'
                      }
                      value={body} onChange={e => setBody(e.target.value)} />
            <div className="row spread" style={{ marginTop: 6, fontSize: 11 }}>
              <span className="muted">{body.length} characters · supports @mentions</span>
              <span className="muted">Tip: paste an email thread for auto-summary</span>
            </div>
          </div>

          {/* Side effects: follow-up + stage update */}
          <div className="card" style={{ background: 'var(--bg-elev)', padding: 14 }}>
            <div className="dim" style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: 0.6, fontWeight: 600, marginBottom: 10 }}>Side effects</div>

            <label className="row gap-2" style={{ marginBottom: 10, fontSize: 13, cursor: 'pointer' }}>
              <input type="checkbox" checked={followUp} onChange={e => setFollowUp(e.target.checked)} />
              <span style={{ flex: 1 }}>Create a follow-up task</span>
            </label>
            {followUp && (
              <div className="grid" style={{ gridTemplateColumns: '1fr 160px', gap: 8, marginLeft: 22, marginBottom: 10 }}>
                <input placeholder={`Follow-up: ${kind === 'call' ? 'send recap email' : kind === 'meeting' ? 'circulate notes' : 'follow up on this'}`}
                       value={followUpTask} onChange={e => setFollowUpTask(e.target.value)}
                       style={{ border: '1px solid var(--border-strong)', borderRadius: 8, padding: '8px 12px', fontSize: 13 }} />
                <input type="date" value={followUpDate} onChange={e => setFollowUpDate(e.target.value)}
                       style={{ border: '1px solid var(--border-strong)', borderRadius: 8, padding: '8px 12px', fontSize: 13 }} />
              </div>
            )}

            {deal && (
              <>
                <label className="row gap-2" style={{ marginBottom: 6, fontSize: 13, cursor: 'pointer' }}>
                  <input type="checkbox" checked={updateStage} onChange={e => setUpdateStage(e.target.checked)} />
                  <span style={{ flex: 1 }}>Update deal stage based on this activity</span>
                </label>
                {updateStage && (
                  <div className="row gap-2" style={{ marginLeft: 22, flexWrap: 'wrap' }}>
                    {D.DEAL_STAGES.map(s => (
                      <button key={s.id} type="button" onClick={() => setNewStage(s.id)}
                              className={`btn btn-sm ${newStage === s.id ? '' : 'btn-secondary'}`}
                              style={newStage === s.id ? { background: s.color, color: '#fff', borderColor: s.color } : {}}>
                        {s.name}
                      </button>
                    ))}
                  </div>
                )}
              </>
            )}

            <div className="row gap-2" style={{ marginTop: 10, color: 'var(--text-muted)', fontSize: 11.5 }}>
              <Icon name="bolt" size={11} />
              <span>Posts a digest to <span className="mono">#sales</span> if any side effect changes deal stage or value.</span>
            </div>
          </div>
        </div>

        <div style={{ padding: '14px 24px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'var(--bg-elev)' }}>
          <div className="row gap-2">
            <Button variant="ghost" onClick={onClose}>Cancel</Button>
            <span className="dim" style={{ fontSize: 11.5 }}>⌘+Enter to log</span>
          </div>
          <div className="row gap-2">
            <Button variant="secondary" icon="clock">Schedule for later</Button>
            <Button variant="primary" icon="check" disabled={!body.trim()} onClick={submit}>Log {selectedKind.label.toLowerCase()}</Button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.NewDealModal = NewDealModal;
window.LogActivityModal = LogActivityModal;
