/* ============================================================
   Insights — unified shell.
   One app, two product areas under a single nav:
     · Deal flow analytics  → Pipeline overview · Outreach · Industry studies
     · Competitor analytics → Market overview · Competitor activity · Advisors
   Reuses every screen/chart/drawer from both originals; this file
   is only the shell (nav, per-screen control bars, routing, drawers).
   Old app.jsx / pl_app.jsx are NOT loaded here.
   ============================================================ */

/* ---- pipeline customize groups + section defs (from pl_app) ---- */
const SHOW_GROUPS = [
  { section: 'Funnel', items: [['funnel_kpis', 'KPI cards'], ['funnel_funnel', 'Stage funnel'], ['funnel_trend', 'Leads over time'], ['funnel_exits', 'Exits'], ['funnel_roll', 'Rolling LTM'], ['funnel_aging', 'Stage aging']] },
  { section: 'Lead', items: [['lead_sector', 'Sector mix'], ['lead_pass', 'Pass reasons'], ['lead_lost', 'Lost reasons'], ['lead_dist', 'Deal-size distribution']] },
  { section: 'Sourcing', items: [['src_channel', 'Channel mix'], ['src_advisor', 'Advisor quality'], ['src_funnels', 'Funnel by channel'], ['src_advtable', 'Top advisors'], ['src_owners', 'By team member']] },
];
const ALL_SHOW = {}; SHOW_GROUPS.forEach((g) => g.items.forEach(([k]) => ALL_SHOW[k] = true));
const PIPE_SECTIONS = [{ id: 'funnel', label: 'The funnel', icon: 'funnel' }, { id: 'lead', label: 'Lead analysis', icon: 'layers' }, { id: 'sourcing', label: 'Sourcing', icon: 'radar' }];
const DF_SCREENS = [{ id: 'outreach', label: 'Outreach', icon: 'phone' }, { id: 'industry', label: 'Industry studies', icon: 'briefcase' }];
const COMP_NAV = [{ id: 'overview', label: 'Market overview', icon: 'radar' }, { id: 'competitors', label: 'Competitor activity', icon: 'layers' }, { id: 'advisors', label: 'Advisors', icon: 'users' }];
const DEALFLOW = new Set(['pipeline', 'outreach', 'industry']);
const SCREEN_LABEL = { pipeline: 'Pipeline overview', outreach: 'Outreach', industry: 'Industry studies', overview: 'Market overview', competitors: 'Competitor activity', advisors: 'Advisors' };

/* ---- area-aware PageHead (overrides df_shared's; wins by load order) ---- */
let ACTIVE_KICKER = 'Deal flow analytics';
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 · {ACTIVE_KICKER}
        </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: 740, lineHeight: 1.5 }}>{lead}</p>}
      </div>
      {right && <div style={{ flexShrink: 0 }}>{right}</div>}
    </div>
  );
}

/* ---- unified ChartCard (supports both `right` and `height`; wins by load order) ---- */
function ChartCard({ title, sub, children, legend, footnote, right, height }) {
  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, ...(height ? { minHeight: height } : {}) }}>{children}</div>
      {legend && <ChartLegend items={legend} />}
      {footnote && <div style={{ fontSize: 10.5, color: 'var(--ink-faint)', marginTop: 9, lineHeight: 1.4 }}>{footnote}</div>}
    </div>
  );
}

/* ---- compact single-select (pipeline filters) ---- */
function Single({ label, value, options, onChange, allLabel = 'All', icon }) {
  const [open, setOpen] = useState(false);
  const ref = useRef();
  useOutside(ref, () => setOpen(false));
  const active = value !== 'all';
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button className="btn sm" onClick={() => setOpen((o) => !o)} style={{ height: 32, gap: 6, borderColor: active ? 'var(--accent)' : 'var(--line)', color: active ? 'var(--accent)' : 'var(--ink-muted)' }}>
        {icon && <Icon name={icon} size={13} />}<span style={{ fontWeight: 600 }}>{label}:</span><span style={{ fontWeight: 700, color: 'var(--ink)' }}>{active ? value : allLabel}</span><Icon name="chevronDown" size={13} style={{ opacity: .6 }} />
      </button>
      {open && (
        <div className="card" style={{ position: 'absolute', top: 38, left: 0, zIndex: 50, minWidth: 170, maxHeight: 300, overflow: 'auto', padding: 5, boxShadow: 'var(--shadow-pop)' }}>
          <button onClick={() => { onChange('all'); setOpen(false); }} style={menuItemStyle(value === 'all')}><span style={{ width: 14 }}>{value === 'all' && <Icon name="check" size={13} />}</span>{allLabel}</button>
          <div style={{ height: 1, background: 'var(--line-soft)', margin: '4px 0' }}></div>
          {options.map((o) => <button key={o} onClick={() => { onChange(o); setOpen(false); }} style={menuItemStyle(value === o)}><span style={{ width: 14 }}>{value === o && <Icon name="check" size={13} />}</span>{o}</button>)}
        </div>
      )}
    </div>
  );
}

/* ---- customize (show/hide pipeline modules) ---- */
function Customize({ show, setShow }) {
  const [open, setOpen] = useState(false);
  const ref = useRef();
  useOutside(ref, () => setOpen(false));
  const hidden = Object.values(show).filter((v) => !v).length;
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button className="btn sm" onClick={() => setOpen((o) => !o)} style={{ height: 32, gap: 6 }}><Icon name="sliders" size={13} /> Customize{hidden ? ` · ${hidden} hidden` : ''}</button>
      {open && (
        <div className="card" style={{ position: 'absolute', top: 38, right: 0, zIndex: 50, width: 220, padding: '10px 6px 6px', boxShadow: 'var(--shadow-pop)' }}>
          {SHOW_GROUPS.map((g) => (
            <div key={g.section} style={{ marginBottom: 6 }}>
              <div className="micro" style={{ padding: '2px 8px 5px' }}>{g.section}</div>
              {g.items.map(([k, lab]) => (
                <button key={k} onClick={() => setShow((s) => ({ ...s, [k]: !s[k] }))} style={{ ...menuItemStyle(show[k]), justifyContent: 'flex-start' }}>
                  <span style={{ width: 16, height: 16, borderRadius: 4, border: '1.5px solid ' + (show[k] ? 'var(--accent)' : 'var(--line)'), background: show[k] ? 'var(--accent)' : '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{show[k] && <Icon name="check" size={11} stroke={3} style={{ color: '#fff' }} />}</span>
                  {lab}
                </button>
              ))}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---- sidebar nav button + sub-item ---- */
function NavBtn({ on, icon, label, onClick }) {
  return (
    <button onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 9px', borderRadius: 8, border: 'none', width: '100%', textAlign: 'left', cursor: 'pointer', transition: 'all .12s', background: on ? 'var(--surface-card)' : 'transparent', boxShadow: on ? '0 1px 2px rgba(0,0,0,.06)' : 'none', color: on ? 'var(--ink)' : 'var(--ink-muted)', fontWeight: on ? 600 : 500 }}
      onMouseEnter={(e) => { if (!on) e.currentTarget.style.background = 'rgba(255,255,255,.55)'; }} onMouseLeave={(e) => { if (!on) e.currentTarget.style.background = 'transparent'; }}>
      <span style={{ color: on ? 'var(--accent)' : 'var(--ink-soft)', display: 'inline-flex' }}><Icon name={icon} size={16} /></span>
      <span style={{ flex: 1, fontSize: 13 }}>{label}</span>
      {on && <span style={{ width: 4, height: 4, borderRadius: 9, background: 'var(--accent)' }}></span>}
    </button>
  );
}
function SubNav({ on, label, onClick }) {
  return (
    <button onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '6px 9px', borderRadius: 7, border: 'none', width: '100%', textAlign: 'left', cursor: 'pointer', transition: 'all .12s', background: 'transparent', color: on ? 'var(--accent)' : 'var(--ink-soft)', fontWeight: on ? 700 : 500, fontSize: 12.5 }}
      onMouseEnter={(e) => { if (!on) e.currentTarget.style.color = 'var(--ink-muted)'; }} onMouseLeave={(e) => { if (!on) e.currentTarget.style.color = 'var(--ink-soft)'; }}>
      <span style={{ width: 5, height: 5, borderRadius: 9, background: on ? 'var(--accent)' : 'var(--line)', flexShrink: 0 }}></span>
      {label}
    </button>
  );
}

/* ---- lighter filter bar for outreach / industry (DF universe) ---- */
function DfBar({ f, setF }) {
  const set = (patch) => setF((x) => ({ ...x, ...patch }));
  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 40, background: 'var(--surface)', borderBottom: '1px solid var(--line)' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '10px 26px' }}>
        <div className="card" style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '8px 11px', flexWrap: 'wrap' }}>
          <Icon name="filter" size={14} style={{ color: 'var(--ink-soft)' }} />
          <MultiSelect label="Vertical" options={DF.verticals.map((v) => v.name)} value={f.verticals} onChange={(v) => set({ verticals: v })} allLabel="All verticals" />
          <MultiSelect label="Owner" options={DF.members.map((m) => m.name)} value={f.owners} onChange={(v) => set({ owners: v })} allLabel="All team" />
          <div style={{ position: 'relative' }}>
            <Icon name="search" size={14} style={{ position: 'absolute', left: 10, top: 9, color: 'var(--ink-faint)' }} />
            <input value={f.search} onChange={(e) => set({ search: e.target.value })} placeholder="Search companies…" style={{ height: 32, border: '1px solid var(--line)', borderRadius: 7, padding: '0 10px 0 30px', fontSize: 12.5, width: 200, background: 'var(--surface-card)', color: 'var(--ink)' }} />
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---- competitor global filter bar (from app.jsx) ---- */
function FilterBar({ filters, setFilters }) {
  const [spin, setSpin] = useState(false);
  const set = (patch) => setFilters((f) => ({ ...f, ...patch }));
  const refresh = () => { setSpin(true); setTimeout(() => setSpin(false), 750); };
  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 40, background: 'var(--surface-card)', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 9, padding: '11px 26px' }}>
      <MultiSelect label="Quarter" options={DATA.quarters} value={filters.quarters} onChange={(v) => set({ quarters: v })} allLabel="All quarters" />
      <Segmented value={filters.tier} onChange={(v) => set({ tier: v })}
        options={[{ value: 'all', label: 'All tiers' }, { value: 'core', label: 'Core' }, { value: 'buyout', label: 'Buyout' }, { value: 'vc', label: 'VC' }]} />
      <MultiSelect label="Sector" options={DATA.allSectors} value={filters.sectors} onChange={(v) => set({ sectors: v })} allLabel="All sectors" />
      <MultiSelect label="Country" options={DATA.countries} value={filters.countries} onChange={(v) => set({ countries: v })} allLabel="All countries" />
      <div style={{ position: 'relative' }}>
        <Icon name="search" size={14} style={{ position: 'absolute', left: 10, top: 9, color: 'var(--ink-faint)' }} />
        <input value={filters.search} onChange={(e) => set({ search: e.target.value })} placeholder="Search deals, buyers, advisors…"
          style={{ height: 32, border: '1px solid var(--line)', borderRadius: 7, padding: '0 10px 0 30px', fontSize: 12.5, width: 230, background: 'var(--surface-card)', color: 'var(--ink)' }} />
      </div>
      <div style={{ flex: 1 }}></div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--ink-soft)', fontWeight: 600 }}>
        <button className="btn ghost sm" onClick={refresh} style={{ width: 28, padding: 0, justifyContent: 'center' }} title="Refresh feed">
          <span style={{ display: 'inline-flex', animation: spin ? 'spin .75s linear' : 'none' }}><Icon name="refresh" size={14} /></span>
        </button>
        Updated {DATA.updated}
      </div>
    </div>
  );
}

/* ---- sidebar ---- */
function Sidebar({ screen, active, setScreen, goPipe, goPipeSection }) {
  const isPipe = screen === 'pipeline';
  return (
    <aside style={{ width: 'var(--sidebar-w)', flexShrink: 0, background: 'var(--surface-warm)', borderRight: '1px solid var(--line)', display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ padding: '15px 16px 14px', borderBottom: '1px solid var(--line)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <div style={{ width: 26, height: 26, borderRadius: 7, background: 'var(--accent)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 14, letterSpacing: '-0.03em' }}>I</div>
          <div><div style={{ fontWeight: 800, fontSize: 14.5, letterSpacing: '-0.02em', lineHeight: 1 }}>Insights</div><div style={{ fontSize: 10, color: 'var(--ink-soft)', fontWeight: 600, marginTop: 2 }}>PE deal intelligence</div></div>
        </div>
      </div>
      <nav style={{ padding: '14px 10px', flex: 1, overflow: 'auto' }}>
        <div className="micro" style={{ padding: '0 8px 9px' }}>Deal flow analytics</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          <NavBtn on={isPipe} icon="funnel" label="Pipeline overview" onClick={goPipe} />
          {isPipe && (
            <div style={{ margin: '1px 0 3px 17px', paddingLeft: 11, borderLeft: '1px solid var(--line)', display: 'flex', flexDirection: 'column', gap: 1 }}>
              {PIPE_SECTIONS.map((n) => <SubNav key={n.id} on={active === n.id} label={n.label} onClick={() => goPipeSection(n.id)} />)}
            </div>
          )}
          {DF_SCREENS.map((n) => <NavBtn key={n.id} on={screen === n.id} icon={n.icon} label={n.label} onClick={() => setScreen(n.id)} />)}
        </div>
        <div className="micro" style={{ padding: '20px 8px 9px' }}>Competitor analytics</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {COMP_NAV.map((n) => <NavBtn key={n.id} on={screen === n.id} icon={n.icon} label={n.label} onClick={() => setScreen(n.id)} />)}
        </div>
      </nav>
      <div style={{ padding: '11px 16px', borderTop: '1px solid var(--line)', fontSize: 10.5, color: 'var(--ink-soft)', display: 'flex', alignItems: 'center', gap: 6, fontWeight: 600 }}>
        <span style={{ width: 6, height: 6, borderRadius: 9, background: 'var(--positive)' }}></span> Affinity synced · {PL.updated}
      </div>
    </aside>
  );
}

function App() {
  const [screen, setScreen] = useState('pipeline');
  // pipeline controls
  const [year, setYear] = useState(PL.CUR_YEAR);
  const [ghost, setGhost] = useState(true);
  const [measure, setMeasure] = useState('count');
  const [grain, setGrain] = useState('month');
  const [plFilters, setPlFilters] = useState({ sectors: [], channels: [], owners: [], programme: 'all', dealType: 'both', search: '' });
  const [showFilters, setShowFilters] = useState(true);
  const [show, setShow] = useState({ ...ALL_SHOW });
  const [active, setActive] = useState('funnel');
  const [plDrawer, setPlDrawer] = useState({ open: false, title: '', subtitle: '', deals: [] });
  const [matrix, setMatrix] = useState(false);
  // outreach / industry
  const [dff, setDff] = useState({ verticals: [], owners: [], search: '' });
  const [dfDrawer, setDfDrawer] = useState({ open: false, title: '', subtitle: '', leads: [], secondCol: 'owner' });
  // competitor
  const [compFilters, setCompFilters] = useState({ quarters: [], tier: 'all', sectors: [], countries: [], search: '' });
  const [compDrawer, setCompDrawer] = useState({ open: false, title: '', subtitle: '', deals: [], winner: false });

  const scrollRef = useRef();
  const pending = useRef(null);

  const area = DEALFLOW.has(screen) ? 'dealflow' : 'competitor';
  ACTIVE_KICKER = area === 'dealflow' ? 'Deal flow analytics' : 'Competitor analytics';

  const set = (patch) => setPlFilters((f) => ({ ...f, ...patch }));
  const fcount = plFilters.sectors.length + plFilters.channels.length + plFilters.owners.length + (plFilters.programme !== 'all' ? 1 : 0) + (plFilters.dealType !== 'both' ? 1 : 0);

  /* ---- PL filtered base ---- */
  const base = PL.deals.filter((d) => {
    if (plFilters.dealType !== 'both' && d.dealType !== plFilters.dealType) return false;
    if (plFilters.programme !== 'all' && d.programme !== plFilters.programme) return false;
    if (plFilters.sectors.length && !plFilters.sectors.includes(d.sector)) return false;
    if (plFilters.channels.length && !plFilters.channels.includes(d.channel || 'Unattributed')) return false;
    if (plFilters.owners.length && !plFilters.owners.includes(PL.oName(d.owner))) return false;
    if (plFilters.search) { const q = plFilters.search.toLowerCase(); if (!(d.name + ' ' + d.sector + ' ' + (d.advisorOrg || '')).toLowerCase().includes(q)) return false; }
    return true;
  });
  const cur = base.filter((d) => d.year === year);
  const prev = plPrevComparable(base, year);
  const ytd = year === PL.CUR_YEAR;
  const pLbl = (year - 1) + (ytd ? ' YTD' : '');

  let periods, prevPeriods;
  if (grain === 'year') {
    periods = PL.YEARS.map((y) => ({ key: '' + y, label: plYearLabel(y), set: base.filter((d) => d.year === y) }));
    prevPeriods = PL.YEARS.map((y) => ({ set: base.filter((d) => d.year === y - 1) }));
  } else if (grain === 'quarter') {
    const qs = [...new Set(PL.monthsOf(year).map(PL.quarterOf))];
    periods = qs.map((q) => ({ key: q, label: 'Q' + q.slice(-1) + " '" + q.slice(2, 4), set: cur.filter((d) => d.quarter === q) }));
    prevPeriods = qs.map((q) => ({ set: base.filter((d) => d.quarter === (year - 1) + q.slice(4)) }));
  } else {
    const ms = PL.monthsOf(year);
    periods = ms.map((m) => ({ key: m, label: PL.monthLabel(m), set: cur.filter((d) => d.month === m) }));
    prevPeriods = ms.map((m) => ({ set: base.filter((d) => d.month === (year - 1) + m.slice(4)) }));
  }

  const val = makeVal(measure), fmtVal = makeFmt(measure);
  const openPlDrawer = (title, subtitle, deals) => setPlDrawer({ open: true, title, subtitle, deals });
  const ctx = { base, year, ghost, cur, prev, pLbl, ytd, measure, val, fmtVal, grain, periods, prevPeriods, show, openDrawer: openPlDrawer, openMatrix: () => setMatrix(true) };

  const openDf = (title, subtitle, leads, vert) => setDfDrawer({ open: true, title, subtitle, leads, secondCol: vert ? 'vertical' : 'owner' });
  const openComp = (title, subtitle, deals, winner = false) => setCompDrawer({ open: true, title, subtitle, deals, winner });

  const compDeals = applyGlobalFilters(DATA.deals, compFilters);

  /* ---- scroll spy + jump (pipeline only) ---- */
  const doScroll = (id) => { const el = document.getElementById(id), sc = scrollRef.current; if (el && sc) sc.scrollTo({ top: el.offsetTop - 116, behavior: 'smooth' }); };
  const goPipe = () => { if (screen !== 'pipeline') { setScreen('pipeline'); } else { const sc = scrollRef.current; if (sc) sc.scrollTo({ top: 0, behavior: 'smooth' }); } };
  const goPipeSection = (id) => { if (screen !== 'pipeline') { pending.current = id; setScreen('pipeline'); } else doScroll(id); };
  useEffect(() => {
    const sc = scrollRef.current;
    if (screen !== 'pipeline' && sc) sc.scrollTop = 0;
    if (screen === 'pipeline' && pending.current) { const id = pending.current; pending.current = null; requestAnimationFrame(() => doScroll(id)); }
  }, [screen]);
  const onScroll = () => {
    if (screen !== 'pipeline') return;
    const sc = scrollRef.current; if (!sc) return;
    const y = sc.scrollTop + 160; let c = 'funnel';
    PIPE_SECTIONS.forEach((n) => { const el = document.getElementById(n.id); if (el && el.offsetTop <= y) c = n.id; });
    setActive(c);
  };

  const yearPill = (y) => <button key={y} onClick={() => setYear(y)} style={{ border: 'none', background: year === y ? '#fff' : 'transparent', color: year === y ? 'var(--accent)' : 'var(--ink-soft)', fontWeight: 700, fontSize: 12, padding: '6px 10px', borderRadius: 6, cursor: 'pointer', boxShadow: year === y ? '0 1px 2px rgba(0,0,0,.1)' : 'none' }}>{y === PL.CUR_YEAR ? 'YTD' : y}</button>;

  const badge = screen === 'pipeline' ? `${cur.length} leads ${ytd ? 'YTD' : 'in ' + year}`
    : screen === 'outreach' ? `${dfFilter(DF.outreach, dff).filter((d) => d.leadIn).length} lead-ins`
      : screen === 'industry' ? `${dfFilter(DF.industry, dff).filter((d) => d.inPipeline).length} in pipeline`
        : `${DATA.scanned.toLocaleString('en-US')} deals scanned`;

  return (
    <div style={{ display: 'flex', height: '100%' }}>
      <Sidebar screen={screen} active={active} setScreen={setScreen} goPipe={goPipe} goPipeSection={goPipeSection} />
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div style={{ height: 'var(--topbar-h)', flexShrink: 0, borderBottom: '1px solid var(--line)', background: 'var(--surface-card)', display: 'flex', alignItems: 'center', padding: '0 26px', gap: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 600, color: 'var(--ink-muted)' }}>
            <span style={{ color: 'var(--ink-soft)' }}>Portal</span>
            <Icon name="chevronRight" size={13} style={{ color: 'var(--ink-faint)' }} />
            <span style={{ color: 'var(--ink-soft)' }}>{area === 'dealflow' ? 'Deal flow' : 'Competitor analytics'}</span>
            <Icon name="chevronRight" size={13} style={{ color: 'var(--ink-faint)' }} />
            <span style={{ color: 'var(--ink)' }}>{SCREEN_LABEL[screen]}</span>
          </div>
          <div style={{ flex: 1 }}></div>
          <span className="badge" style={{ background: 'var(--surface-deep)' }}>Affinity · {badge}</span>
          <button className="btn"><Icon name="download" size={14} /> Export</button>
        </div>

        <div ref={scrollRef} onScroll={onScroll} id="content" style={{ flex: 1, overflow: 'auto' }}>
          {screen === 'pipeline' && (
            <React.Fragment>
              <div style={{ position: 'sticky', top: 0, zIndex: 40, background: 'var(--surface)', borderBottom: '1px solid var(--line)' }}>
                <div style={{ maxWidth: 1280, margin: '0 auto', padding: '10px 26px 0' }}>
                  <div className="card" style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 11px', flexWrap: 'wrap' }}>
                    <div style={{ display: 'inline-flex', background: 'var(--surface-deep)', borderRadius: 8, padding: 3, gap: 2 }}>{[...PL.YEARS].reverse().map(yearPill)}</div>
                    <button onClick={() => setGhost((g) => !g)} title="Overlay the prior comparable period" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, height: 32, padding: '0 11px', borderRadius: 7, fontSize: 12, fontWeight: 600, cursor: 'pointer', border: '1px solid ' + (ghost ? 'var(--accent)' : 'var(--line)'), background: ghost ? 'var(--accent-soft)' : 'var(--surface-card)', color: ghost ? 'var(--accent)' : 'var(--ink-muted)' }}>
                      <span style={{ width: 13, height: 13, borderRadius: 3, border: '1.5px dashed ' + (ghost ? 'var(--accent)' : 'var(--ink-faint)') }}></span>vs {pLbl}
                    </button>
                    <div style={{ width: 1, height: 24, background: 'var(--line)' }}></div>
                    <Segmented value={measure} onChange={setMeasure} options={[{ value: 'count', label: 'Count' }, { value: 'ebitda', label: '€ EBITDA' }, { value: 'revenue', label: '€ Rev' }]} />
                    <Segmented value={grain} onChange={setGrain} options={[{ value: 'month', label: 'Month' }, { value: 'quarter', label: 'Quarter' }, { value: 'year', label: 'Year' }]} />
                    <div style={{ flex: 1 }}></div>
                    <button className="btn sm" onClick={() => setShowFilters((s) => !s)} style={{ height: 32, gap: 6, borderColor: fcount ? 'var(--accent)' : 'var(--line)', color: fcount ? 'var(--accent)' : 'var(--ink-muted)' }}><Icon name="filter" size={13} /> Filters{fcount ? ` · ${fcount}` : ''}</button>
                    <Customize show={show} setShow={setShow} />
                  </div>
                  {showFilters && (
                    <div className="card" style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '9px 11px', marginTop: 8, flexWrap: 'wrap' }}>
                      <Segmented value={plFilters.dealType} onChange={(v) => set({ dealType: v })} options={[{ value: 'both', label: 'Both' }, { value: 'platform', label: 'Platform' }, { value: 'addon', label: 'Add-on' }]} />
                      <Single label="Portfolio" icon="layers" value={plFilters.programme} onChange={(v) => set({ programme: v })} options={['Standalone', ...PL.PROGRAMMES]} allLabel="All companies" />
                      <MultiSelect label="Sector" options={PL.SECTORS} value={plFilters.sectors} onChange={(v) => set({ sectors: v })} allLabel="All sectors" />
                      <MultiSelect label="Channel" options={[...PL.CHANNELS, 'Unattributed']} value={plFilters.channels} onChange={(v) => set({ channels: v })} allLabel="All channels" />
                      <MultiSelect label="Owner" options={PL.OWNERS.map((o) => o.name)} value={plFilters.owners} onChange={(v) => set({ owners: v })} allLabel="All team" />
                      <div style={{ position: 'relative' }}>
                        <Icon name="search" size={14} style={{ position: 'absolute', left: 10, top: 9, color: 'var(--ink-faint)' }} />
                        <input value={plFilters.search} onChange={(e) => set({ search: e.target.value })} placeholder="Search…" style={{ height: 32, border: '1px solid var(--line)', borderRadius: 7, padding: '0 10px 0 30px', fontSize: 12.5, width: 150, background: 'var(--surface-card)', color: 'var(--ink)' }} />
                      </div>
                      {fcount > 0 && <button className="btn sm ghost" onClick={() => setPlFilters({ sectors: [], channels: [], owners: [], programme: 'all', dealType: 'both', search: '' })}>Clear</button>}
                    </div>
                  )}
                  <div style={{ display: 'flex', gap: 4, padding: '9px 2px 8px' }}>
                    {PIPE_SECTIONS.map((n) => (
                      <button key={n.id} onClick={() => goPipeSection(n.id)} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, height: 30, padding: '0 12px', borderRadius: 7, border: 'none', cursor: 'pointer', fontSize: 12.5, fontWeight: 600, background: active === n.id ? 'var(--accent)' : 'transparent', color: active === n.id ? '#fff' : 'var(--ink-muted)', transition: 'all .12s' }}>
                        <Icon name={n.icon} size={13} /> {n.label}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
              <div style={{ maxWidth: 1280, margin: '0 auto', padding: '6px 26px 80px' }}>
                {base.length === 0 ? (
                  <div className="card" style={{ padding: '60px 20px', textAlign: 'center', color: 'var(--ink-soft)', marginTop: 30 }}>
                    <Icon name="layers" size={28} style={{ color: 'var(--ink-faint)' }} />
                    <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink)', marginTop: 12 }}>No deals match these filters</div>
                    <div style={{ fontSize: 12.5, marginTop: 4 }}>Clear a filter to see the pipeline.</div>
                  </div>
                ) : (
                  <React.Fragment>
                    <FunnelSection ctx={ctx} />
                    <LeadSection ctx={ctx} />
                    <SourcingSection ctx={ctx} />
                  </React.Fragment>
                )}
              </div>
            </React.Fragment>
          )}

          {(screen === 'outreach' || screen === 'industry') && (
            <React.Fragment>
              <DfBar f={dff} setF={setDff} />
              <div style={{ maxWidth: 1280, margin: '0 auto', padding: '26px 26px 80px' }}>
                {screen === 'outreach' && <Outreach outreach={dfFilter(DF.outreach, dff)} filters={dff} openDrawer={openDf} />}
                {screen === 'industry' && <IndustryStudies industry={dfFilter(DF.industry, dff)} filters={dff} openDrawer={openDf} />}
              </div>
            </React.Fragment>
          )}

          {area === 'competitor' && (
            <React.Fragment>
              <FilterBar filters={compFilters} setFilters={setCompFilters} />
              <div style={{ maxWidth: 1240, margin: '0 auto', padding: '26px 26px 60px' }}>
                {screen === 'overview' && <MarketOverview deals={compDeals} filters={compFilters} openDrawer={openComp} />}
                {screen === 'competitors' && <CompetitorActivity deals={compDeals} filters={compFilters} openDrawer={openComp} />}
                {screen === 'advisors' && <Advisors deals={compDeals} filters={compFilters} openDrawer={openComp} />}
              </div>
            </React.Fragment>
          )}
        </div>
      </div>

      <PlDrawer open={plDrawer.open} onClose={() => setPlDrawer((d) => ({ ...d, open: false }))} title={plDrawer.title} subtitle={plDrawer.subtitle} deals={plDrawer.deals} />
      <LeadsDrawer open={dfDrawer.open} onClose={() => setDfDrawer((d) => ({ ...d, open: false }))} title={dfDrawer.title} subtitle={dfDrawer.subtitle} leads={dfDrawer.leads} secondCol={dfDrawer.secondCol} />
      <DealDrawer open={compDrawer.open} onClose={() => setCompDrawer((d) => ({ ...d, open: false }))} title={compDrawer.title} subtitle={compDrawer.subtitle} deals={compDrawer.deals} winner={compDrawer.winner} />
      {matrix && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 80, display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '60px 20px', overflow: 'auto' }}>
          <div onClick={() => setMatrix(false)} style={{ position: 'absolute', inset: 0, background: 'rgba(26,28,30,0.28)', animation: 'fadeIn .15s ease' }}></div>
          <div className="card" style={{ position: 'relative', width: 'min(880px, 96vw)', padding: 22, boxShadow: 'var(--shadow-pop)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
              <div><div className="eyebrow" style={{ color: 'var(--accent)', marginBottom: 4 }}>Board scorecard</div><h3 style={{ fontSize: 18, fontWeight: 700 }}>All seasons, every metric</h3><div style={{ fontSize: 12.5, color: 'var(--ink-soft)', marginTop: 3 }}>Deal counts · latest column vs same period a year earlier{fcount ? ' · filtered' : ''}.</div></div>
              <button className="btn ghost sm" onClick={() => setMatrix(false)} style={{ width: 30, padding: 0, justifyContent: 'center' }}><Icon name="x" size={16} /></button>
            </div>
            <ScorecardMatrix base={base} />
          </div>
        </div>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
