/* ============================================================
   Deal Flow — shared: PageHead, ChartCard, StatusBadge,
   ChipToggle, Leads drawer (universal drill-down).
   Reuses Segmented / MultiSelect / KpiCell / useOutside from shared.jsx.
   ============================================================ */

function PageHead({ icon, title, lead, right }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 24, marginBottom: 20 }}>
      <div>
        <div className="eyebrow" style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 7 }}>
          <Icon name={icon} size={13} style={{ color: 'var(--accent)' }} /> Insights · Deal flow analytics
        </div>
        <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>{title}</h1>
        {lead && <p style={{ margin: '5px 0 0', fontSize: 13.5, color: 'var(--ink-muted)', maxWidth: 760, lineHeight: 1.5 }}>{lead}</p>}
      </div>
      {right && <div style={{ flexShrink: 0 }}>{right}</div>}
    </div>
  );
}

function ChartCard({ title, sub, children, legend, footnote, right }) {
  return (
    <div className="card" style={{ padding: '15px 16px 14px', display: 'flex', flexDirection: 'column' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12, gap: 12 }}>
        <div>
          <h3 style={{ fontSize: 13.5, fontWeight: 700 }}>{title}</h3>
          {sub && <div style={{ fontSize: 11.5, color: 'var(--ink-soft)', marginTop: 2, fontWeight: 500 }}>{sub}</div>}
        </div>
        {right}
      </div>
      <div style={{ flex: 1 }}>{children}</div>
      {legend && <ChartLegend items={legend} />}
      {footnote && <div style={{ fontSize: 10.5, color: 'var(--ink-faint)', marginTop: 9, lineHeight: 1.4 }}>{footnote}</div>}
    </div>
  );
}

function StatusBadge({ status }) {
  const m = DF.STATUS[status] || { label: status, tone: 'neutral' };
  const cls = m.tone === 'accent' ? 'accent' : m.tone === 'positive' ? 'positive' : m.tone === 'warn' ? 'warn' : m.tone === 'danger' ? 'danger' : '';
  return <span className={'badge ' + cls}>{m.label}</span>;
}

function ChipToggle({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 6, height: 30, padding: '0 11px', borderRadius: 7,
      fontSize: 12, fontWeight: 600, cursor: 'pointer', transition: 'all .12s',
      border: '1px solid ' + (active ? 'var(--accent)' : 'var(--line)'),
      background: active ? 'var(--accent-soft)' : 'var(--surface-card)', color: active ? 'var(--accent)' : 'var(--ink-muted)',
    }}>
      <span style={{ display: 'inline-flex', width: 13 }}>{active && <Icon name="check" size={13} stroke={2.4} />}</span>{children}
    </button>
  );
}

function ConvCell({ rate }) {
  const tone = DF.convTone(rate);
  const map = { positive: ['var(--positive-soft)', 'var(--positive)'], warn: ['var(--warn-soft)', 'var(--warn)'], danger: ['var(--danger-soft)', 'var(--danger)'] }[tone];
  return <span className="fit" style={{ background: map[0], color: map[1], minWidth: 46 }}>{DF.fmtPct(rate)}</span>;
}

/* ---------- the Leads drawer ---------- */
function LeadRow({ d, expanded, onToggle, secondCol }) {
  return (
    <React.Fragment>
      <tr className="clickable" onClick={onToggle} style={expanded ? { background: 'var(--accent-soft)' } : null}>
        <td>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
            <Icon name={expanded ? 'chevronDown' : 'chevronRight'} size={13} style={{ color: 'var(--ink-faint)', flexShrink: 0 }} />
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.name}</div>
              <div style={{ fontSize: 11, color: 'var(--ink-soft)' }}>{d.domain}</div>
            </div>
          </div>
        </td>
        <td><StatusBadge status={d.status} /></td>
        <td style={{ color: 'var(--ink-muted)', fontWeight: 500 }}>{secondCol === 'vertical' ? d.verticalName : (DF.mName(d.owner) || '—')}</td>
        <td className="tabular" style={{ color: 'var(--ink-soft)' }}>{d.month}</td>
        <td className="num tabular">{d.fte}</td>
      </tr>
      {expanded && (
        <tr>
          <td colSpan={5} style={{ padding: 0, background: 'var(--surface)' }}>
            <div style={{ padding: '13px 18px 15px', borderTop: '1px solid var(--line)', animation: 'fadeIn .15s ease' }}>
              <p style={{ margin: '0 0 12px', fontSize: 12.5, lineHeight: 1.5, color: 'var(--ink-muted)' }}>{DF.describe(d)}</p>
              <div style={{ display: 'flex', gap: 18, flexWrap: 'wrap', marginBottom: 12 }}>
                <Meta label="Vertical">{d.verticalName}</Meta>
                {d.owner && <Meta label="Owner">{DF.mName(d.owner)}</Meta>}
                {d.advisor && <Meta label="Advisor">{d.advisor}</Meta>}
                {d.dealType && <Meta label="Profile">{d.dealType === 'platform' ? 'Platform' : 'Add-on'}</Meta>}
                <Meta label="Country">{d.country}</Meta>
                <Meta label="FTE">{d.fte}</Meta>
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                <a className="btn sm" href="#" onClick={(e) => e.preventDefault()}><Icon name="globe" size={13} /> {d.domain}</a>
                <a className="btn sm" href="#" onClick={(e) => e.preventDefault()}><Icon name="linkedin" size={13} /> LinkedIn</a>
              </div>
            </div>
          </td>
        </tr>
      )}
    </React.Fragment>
  );
}
function Meta({ label, children }) {
  return <div><div className="micro" style={{ marginBottom: 2 }}>{label}</div><div style={{ fontSize: 12.5, fontWeight: 600 }}>{children}</div></div>;
}

function LeadsDrawer({ open, onClose, title, subtitle, leads, secondCol = 'owner' }) {
  const [status, setStatus] = useState([]);
  const [who, setWho] = useState([]);
  const [page, setPage] = useState(0);
  const [exp, setExp] = useState(null);
  const PAGE = 12;

  useEffect(() => { setStatus([]); setWho([]); setPage(0); setExp(null); }, [title, subtitle, leads && leads.length]);
  useEffect(() => { const h = (e) => { if (e.key === 'Escape') onClose(); }; if (open) document.addEventListener('keydown', h); return () => document.removeEventListener('keydown', h); }, [open]);
  if (!open) return null;

  const statusOpts = [...new Set((leads || []).map((d) => d.status))].map((s) => DF.STATUS[s] ? DF.STATUS[s].label : s);
  const labelToKey = {}; Object.entries(DF.STATUS).forEach(([k, v]) => labelToKey[v.label] = k);
  const whoOpts = secondCol === 'vertical'
    ? [...new Set((leads || []).map((d) => d.verticalName))]
    : [...new Set((leads || []).map((d) => DF.mName(d.owner)).filter(Boolean))];

  let view = (leads || []).filter((d) => {
    if (status.length && !status.includes((DF.STATUS[d.status] || {}).label)) return false;
    if (who.length) {
      const val = secondCol === 'vertical' ? d.verticalName : DF.mName(d.owner);
      if (!who.includes(val)) return false;
    }
    return true;
  });
  const pages = Math.max(1, Math.ceil(view.length / PAGE));
  const pg = Math.min(page, pages - 1);
  const rows = view.slice(pg * PAGE, pg * PAGE + PAGE);

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 60 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(26,28,30,0.18)', animation: 'fadeIn .15s ease' }}></div>
      <aside style={{ position: 'absolute', top: 0, right: 0, height: '100%', width: 'min(760px, 94vw)', background: 'var(--surface-card)', borderLeft: '1px solid var(--line)', boxShadow: '-12px 0 40px rgba(26,28,30,.14)', display: 'flex', flexDirection: 'column', animation: 'drawerIn .2s cubic-bezier(.2,.7,.3,1)' }}>
        <div style={{ padding: '15px 20px 13px', borderBottom: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 4 }}><Icon name="panelRight" size={11} style={{ verticalAlign: -1, marginRight: 5 }} />Companies behind this</div>
              <h3 style={{ fontSize: 17, fontWeight: 700 }}>{title}</h3>
              {subtitle && <div style={{ fontSize: 12.5, color: 'var(--ink-soft)', marginTop: 3, fontWeight: 500 }}>{subtitle}</div>}
            </div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <span className="tabular badge" style={{ height: 24, fontSize: 12 }}>{view.length}</span>
              <button className="btn ghost sm" onClick={onClose} style={{ width: 30, padding: 0, justifyContent: 'center' }}><Icon name="x" size={16} /></button>
            </div>
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 13, alignItems: 'center' }}>
            <MultiSelect label="Status" options={statusOpts} value={status} onChange={(v) => { setStatus(v); setPage(0); }} allLabel="All statuses" />
            <MultiSelect label={secondCol === 'vertical' ? 'Vertical' : 'Owner'} options={whoOpts} value={who} onChange={(v) => { setWho(v); setPage(0); }} allLabel={secondCol === 'vertical' ? 'All verticals' : 'All owners'} />
          </div>
        </div>
        <div style={{ flex: 1, overflow: 'auto' }}>
          <table className="tbl">
            <thead>
              <tr>
                <th>Company</th>
                <th style={{ width: 130 }}>Status</th>
                <th style={{ width: 130 }}>{secondCol === 'vertical' ? 'Vertical' : 'Owner'}</th>
                <th style={{ width: 84 }}>Added</th>
                <th className="num" style={{ width: 60 }}>FTE</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((d) => <LeadRow key={d.id} d={d} expanded={exp === d.id} onToggle={() => setExp((e) => e === d.id ? null : d.id)} secondCol={secondCol} />)}
              {rows.length === 0 && <tr><td colSpan={5} style={{ textAlign: 'center', padding: 34, color: 'var(--ink-faint)' }}>No companies match.</td></tr>}
            </tbody>
          </table>
        </div>
        <div style={{ padding: '10px 20px', borderTop: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', background: 'var(--surface)' }}>
          <span style={{ fontSize: 12, color: 'var(--ink-soft)', fontWeight: 500 }}>{view.length === 0 ? 'No companies' : `${pg * PAGE + 1}–${Math.min(view.length, pg * PAGE + PAGE)} of ${view.length}`} · click a row to expand</span>
          <div style={{ display: 'flex', gap: 6 }}>
            <button className="btn sm" disabled={pg === 0} onClick={() => setPage(pg - 1)} style={{ opacity: pg === 0 ? .4 : 1 }}>Prev</button>
            <span className="tabular" style={{ fontSize: 12, color: 'var(--ink-muted)', alignSelf: 'center', minWidth: 44, textAlign: 'center' }}>{pg + 1} / {pages}</span>
            <button className="btn sm" disabled={pg >= pages - 1} onClick={() => setPage(pg + 1)} style={{ opacity: pg >= pages - 1 ? .4 : 1 }}>Next</button>
          </div>
        </div>
      </aside>
    </div>
  );
}

Object.assign(window, { PageHead, ChartCard, StatusBadge, ChipToggle, ConvCell, LeadsDrawer });
