/* ============================================================
   Deal drawer (universal drill-down) + scored deal card.
   Opens from the right; the table stays in context behind it.
   ============================================================ */

const FTE_PRESETS = [
  { value: 'all', label: 'All', test: () => true },
  { value: 'le25', label: '≤25', test: (d) => d.fte <= 25 },
  { value: 'le50', label: '≤50', test: (d) => d.fte <= 50 },
  { value: 'le100', label: '≤100', test: (d) => d.fte <= 100 },
  { value: 'gt100', label: '100+', test: (d) => d.fte > 100 },
];

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 Fact({ label, children }) {
  return (
    <div>
      <div className="micro" style={{ marginBottom: 3 }}>{label}</div>
      <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)' }}>{children}</div>
    </div>
  );
}

function ScoredDealCard({ d }) {
  const reasons = [
    { ok: DATA.softwareSet.has(d.sector), text: DATA.softwareSet.has(d.sector) ? 'IT / software sector' : 'Outside IT & software' },
    { ok: d.fte <= 100, text: d.fte <= 100 ? `≤100 FTE (${d.fte})` : `Above 100 FTE (${d.fte})` },
    { ok: d.dealSize == null || d.dealSize < 25, text: d.dealSize == null ? 'Size undisclosed' : (d.dealSize < 25 ? `Sub-€25m (${DATA.fmtSize(d.dealSize)})` : `Above €25m (${DATA.fmtSize(d.dealSize)})`) },
  ];
  return (
    <div style={{ padding: '16px 18px 18px', borderTop: '1px solid var(--line)', animation: 'fadeIn .16s ease' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 230px', gap: 22 }}>
        {/* left: enrichment */}
        <div>
          <div className="eyebrow" style={{ marginBottom: 6 }}>The machine read this deal</div>
          <p style={{ margin: '0 0 14px', fontSize: 13, lineHeight: 1.5, color: 'var(--ink-muted)' }}>{d.blurb}</p>

          {d.products.length > 0 && (
            <div style={{ marginBottom: 14 }}>
              <div className="micro" style={{ marginBottom: 6 }}>Products</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {d.products.map((p) => <span key={p} className="badge">{p}</span>)}
              </div>
            </div>
          )}

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14, marginBottom: 14 }}>
            <Fact label="Buyer"><CompCell name={d.buyer} compId={d.buyerCompId} /></Fact>
            <Fact label="Seller">{d.seller}</Fact>
            <Fact label="Financer">{d.financer || <span style={{ color: 'var(--ink-faint)' }}>None</span>}</Fact>
            <Fact label="Sell-side advisor">{d.advisorsSell.length ? d.advisorsSell.join(', ') : <span style={{ color: 'var(--ink-faint)' }}>None</span>}</Fact>
            <Fact label="Buy-side advisor">{d.advisorsBuy.length ? d.advisorsBuy.join(', ') : <span style={{ color: 'var(--ink-faint)' }}>None</span>}</Fact>
            <Fact label="Quarter">{d.quarter}</Fact>
          </div>

          <div style={{ display: 'flex', gap: 8 }}>
            <a className="btn sm" href="#" onClick={(e) => e.preventDefault()}><Icon name="globe" size={13} /> Company site</a>
            <a className="btn sm" href="#" onClick={(e) => e.preventDefault()}><Icon name="linkedin" size={13} /> LinkedIn</a>
            <a className="btn sm" href="#" onClick={(e) => e.preventDefault()}><Icon name="external" size={13} /> Source deal page</a>
          </div>
        </div>

        {/* right: fit score panel */}
        <div className="card" style={{ background: 'var(--surface)', padding: 14, alignSelf: 'start' }}>
          <div className="micro" style={{ marginBottom: 8 }}>Thesis fit</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 12 }}>
            <span className="tabular" style={{ fontSize: 30, fontWeight: 700, color: fitBadgeStyle(d.fit).color }}>{d.fit}</span>
            <span style={{ fontSize: 14, color: 'var(--ink-soft)', fontWeight: 600 }}>/ 5</span>
            <span style={{ marginLeft: 'auto', display: 'flex', gap: 3 }}>
              {[1, 2, 3, 4, 5].map((n) => <span key={n} style={{ width: 7, height: 16, borderRadius: 2, background: n <= d.fit ? fitBadgeStyle(d.fit).color : 'var(--line)' }}></span>)}
            </span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 7, marginBottom: 12 }}>
            {reasons.map((r, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 12, fontWeight: 600, color: r.ok ? 'var(--ink)' : 'var(--ink-soft)' }}>
                <span style={{ color: r.ok ? 'var(--positive)' : 'var(--danger)', display: 'inline-flex' }}>
                  <Icon name={r.ok ? 'check' : 'x'} size={13} stroke={2.4} />
                </span>{r.text}
              </div>
            ))}
          </div>
          <p style={{ margin: 0, fontSize: 12, lineHeight: 1.5, color: 'var(--ink-muted)', fontStyle: 'italic' }}>{d.fitReason}</p>
          <div style={{ marginTop: 12, paddingTop: 11, borderTop: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 7 }}>
            {d.relevant
              ? <span className="badge accent"><Icon name="dot" size={11} /> Relevant</span>
              : <span className="badge">Not relevant</span>}
            {d.seenBefore
              ? <span className="badge positive"><Icon name="check" size={11} /> Seen before</span>
              : <span className="badge danger"><Icon name="x" size={11} /> Unseen</span>}
          </div>
        </div>
      </div>
    </div>
  );
}

function DealDrawer({ open, onClose, title, subtitle, deals, winner }) {
  const [minFit, setMinFit] = useState('all');
  const [fte, setFte] = useState('all');
  const [seenOnly, setSeenOnly] = useState(false);
  const [sizeKnown, setSizeKnown] = useState(false);
  const [hasAdv, setHasAdv] = useState(false);
  const [sort, setSort] = useState({ key: 'fit', dir: 'desc' });
  const [page, setPage] = useState(0);
  const [expanded, setExpanded] = useState(null);
  const PAGE = 11;

  useEffect(() => { // reset when source changes
    setMinFit('all'); setFte('all'); setSeenOnly(false); setSizeKnown(false);
    setHasAdv(false); setPage(0); setExpanded(null); setSort({ key: 'fit', dir: 'desc' });
  }, [title, subtitle, deals && deals.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 ftePreset = FTE_PRESETS.find((p) => p.value === fte);
  let view = (deals || []).filter((d) => {
    if (minFit !== 'all' && d.fit < +minFit) return false;
    if (!ftePreset.test(d)) return false;
    if (seenOnly && !d.seenBefore) return false;
    if (sizeKnown && d.dealSize == null) return false;
    if (hasAdv && d.advisorsSell.length + d.advisorsBuy.length === 0) return false;
    return true;
  });
  view = sortDeals(view, sort);
  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);
  const cols = dealColumns({ winner });
  const onSort = (key) => setSort((s) => s.key === key ? { key, dir: s.dir === 'asc' ? 'desc' : 'asc' } : { key, dir: key === 'name' ? 'asc' : 'desc' });

  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(860px, 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)',
      }}>
        {/* header */}
        <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 }} />Deals 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} deals</span>
              <button className="btn ghost sm" onClick={onClose} style={{ width: 30, padding: 0, justifyContent: 'center' }}><Icon name="x" size={16} /></button>
            </div>
          </div>
          {/* in-drawer refilters */}
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 13, alignItems: 'center' }}>
            <span className="micro" style={{ marginRight: 1 }}>Min fit</span>
            <Segmented value={minFit} onChange={(v) => { setMinFit(v); setPage(0); }} options={[{ value: 'all', label: 'All' }, { value: '2', label: '2+' }, { value: '3', label: '3+' }, { value: '4', label: '4+' }]} />
            <span className="micro" style={{ margin: '0 1px 0 6px' }}>FTE</span>
            <Segmented value={fte} onChange={(v) => { setFte(v); setPage(0); }} options={FTE_PRESETS.map((p) => ({ value: p.value, label: p.label }))} />
            <span style={{ width: 1, height: 22, background: 'var(--line)', margin: '0 2px' }}></span>
            <ChipToggle active={seenOnly} onClick={() => { setSeenOnly((v) => !v); setPage(0); }}>Seen only</ChipToggle>
            <ChipToggle active={sizeKnown} onClick={() => { setSizeKnown((v) => !v); setPage(0); }}>Size known</ChipToggle>
            <ChipToggle active={hasAdv} onClick={() => { setHasAdv((v) => !v); setPage(0); }}>Has advisors</ChipToggle>
          </div>
        </div>
        {/* table */}
        <div style={{ flex: 1, overflow: 'auto' }}>
          <DealTable deals={rows} columns={cols} sort={sort} onSort={onSort}
            onRowClick={(d) => setExpanded((e) => e === d.id ? null : d.id)}
            expandedId={expanded} renderExpanded={(d) => <ScoredDealCard d={d} />} dense />
        </div>
        {/* footer / pagination */}
        <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 deals' : `${pg * PAGE + 1} to ${Math.min(view.length, pg * PAGE + PAGE)} of ${view.length}`} · click a row for the scored card
          </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, { DealDrawer, ScoredDealCard, ChipToggle });
