/* Module C, firm portfolio scope: Maturity Heatmap + Playbook Library (+ shared PlaybookDetail). */

function HeatCell({ score, delta, onClick }) {
  if (score == null) return <td style={{ textAlign: "center", color: "var(--ink-faint)", borderBottom: "1px solid var(--line-soft)" }}>—</td>;
  const band = VCP.scoreBand(score);
  return <td style={{ padding: 4, borderBottom: "1px solid var(--line-soft)", textAlign: "center" }}>
    <button onClick={onClick} style={{
      width: "100%", border: "none", borderRadius: 7, padding: "7px 4px", cursor: "pointer",
      background: BAND_BG[band], color: BAND_FG[band], display: "flex", flexDirection: "column", alignItems: "center", gap: 1,
      transition: "all 120ms ease",
    }}>
      <span className="tabular" style={{ fontWeight: 700, fontSize: 13.5 }}>{score.toFixed(1)}</span>
      {delta != null && Math.abs(delta) > 0.001 && <span className="tabular" style={{ fontSize: 9.5, opacity: 0.85, fontWeight: 600 }}>{delta > 0 ? "▲" : "▼"}{Math.abs(delta).toFixed(1)}</span>}
    </button>
  </td>;
}

function MaturityHeatmap({ state, go }) {
  const [search, setSearch] = useState("");
  const [fund, setFund] = useState("");
  const [trend, setTrend] = useState("");
  const [minS, setMinS] = useState("");
  const [quick, setQuick] = useState("all");
  const [sortPillar, setSortPillar] = useState(null);
  const [selected, setSelected] = useState([]);
  const [compare, setCompare] = useState(false);
  const [showTrend, setShowTrend] = useState(false);
  const [drill, setDrill] = useState(null); // {company, pillar}
  const [hidden, setHidden] = useState({}); // trend chart legend

  const pillars = VCP.PILLAR_KEYS;
  const overallDelta = c => +(c.overallSeries[c.overallSeries.length - 1] - c.overallSeries[0]).toFixed(1);

  let cos = VCP.companies.filter(c => {
    if (search && !c.name.toLowerCase().includes(search.toLowerCase())) return false;
    if (fund && c.fund !== fund) return false;
    if (trend && VCP.trendOf(c.overallSeries) !== trend) return false;
    if (minS && c.maturity < +minS) return false;
    if (quick === "top" && c.maturity < 4.0) return false;
    if (quick === "attention" && c.maturity >= 2.5) return false;
    if (quick === "improved" && overallDelta(c) < 0.5) return false;
    return true;
  });
  if (sortPillar) {
    cos = [...cos].sort((a, b) => (sortPillar === "trend" ? overallDelta(b) - overallDelta(a) : b.pillars[sortPillar][0] - a.pillars[sortPillar][0]));
  }

  const scopeCos = VCP.companies; // totals computed across all
  const pillarMean = (list, p) => { const v = list.map(c => c.pillars[p][0]); return v.reduce((a, b) => a + b, 0) / v.length; };
  const fundCos = f => scopeCos.filter(c => c.fund === f);

  const toggleSel = id => setSelected(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]);

  const quickFilters = [
    { v: "all", l: "All" }, { v: "top", l: "Top performers" }, { v: "attention", l: "Need attention" }, { v: "improved", l: "Most improved" },
  ];

  return <div>
    {/* filter bar */}
    <div style={{ display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center", marginBottom: 14 }}>
      <SearchInput value={search} onChange={setSearch} placeholder="Search companies" width={200} />
      <Select value={fund} onChange={setFund} options={VCP.FUNDS} placeholder="All funds" />
      <Select value={trend} onChange={setTrend} options={[{ value: "up", label: "Improving" }, { value: "down", label: "Declining" }, { value: "stable", label: "Stable" }]} placeholder="Any trend" />
      <Select value={minS} onChange={setMinS} options={["2.0", "2.5", "3.0", "3.5", "4.0"].map(v => ({ value: v, label: "Min " + v }))} placeholder="Min score" />
      <div style={{ flex: 1 }} />
      <Btn variant={compare ? "primary" : "ghost"} size="sm" icon="columns" onClick={() => { setCompare(c => !c); if (compare) setSelected([]); }}>{compare ? `Compare (${selected.length})` : "Compare"}</Btn>
      <Btn variant="ghost" size="sm" icon="trendingUp" onClick={() => setShowTrend(s => !s)}>Trend chart</Btn>
    </div>
    <div style={{ display: "flex", gap: 6, marginBottom: 14 }}>
      {quickFilters.map(q => <button key={q.v} onClick={() => setQuick(q.v)} style={{
        padding: "5px 12px", borderRadius: 100, border: "1px solid " + (quick === q.v ? "var(--accent)" : "var(--line)"),
        background: quick === q.v ? "var(--accent-soft)" : "var(--surface-card)", color: quick === q.v ? "var(--accent)" : "var(--ink-muted)",
        fontSize: 12, fontWeight: 600,
      }}>{q.l}</button>)}
    </div>

    {showTrend && <Card style={{ marginBottom: 16 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
        <div className="micro">Overall maturity over time</div>
        <IconBtn name="x" size={14} onClick={() => setShowTrend(false)} />
      </div>
      <MultiLineChart labels={VCP.QUARTERS} series={[
        ...VCP.companies.map(c => ({ name: c.name, color: c.color, values: c.overallSeries, visible: !hidden[c.id], id: c.id })),
        { name: "Lexar Total", color: "var(--ink)", bold: true, values: VCP.QUARTERS.map((q, i) => +(VCP.companies.reduce((a, c) => a + c.overallSeries[i], 0) / VCP.companies.length).toFixed(2)), visible: !hidden.__total },
      ]} />
      <div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginTop: 10 }}>
        {VCP.companies.map(c => <button key={c.id} onClick={() => setHidden(h => ({ ...h, [c.id]: !h[c.id] }))} style={{ display: "inline-flex", alignItems: "center", gap: 6, border: "none", background: "none", fontSize: 11.5, color: hidden[c.id] ? "var(--ink-faint)" : "var(--ink-muted)", fontWeight: 600 }}>
          <span style={{ width: 10, height: 10, borderRadius: 3, background: c.color, opacity: hidden[c.id] ? 0.3 : 1 }} />{c.name}
        </button>)}
        <button onClick={() => setHidden(h => ({ ...h, __total: !h.__total }))} style={{ display: "inline-flex", alignItems: "center", gap: 6, border: "none", background: "none", fontSize: 11.5, color: hidden.__total ? "var(--ink-faint)" : "var(--ink)", fontWeight: 700 }}>
          <span style={{ width: 14, height: 3, borderRadius: 2, background: "var(--ink)", opacity: hidden.__total ? 0.3 : 1 }} />Lexar Total
        </button>
      </div>
    </Card>}

    {/* heatmap grid */}
    <div style={{ background: "var(--surface-card)", border: "1px solid var(--line)", borderRadius: "var(--radius)", overflow: "hidden", boxShadow: "var(--shadow-card)" }}>
      <div style={{ overflowX: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13, minWidth: 920, tableLayout: "fixed" }}>
          <colgroup>
            {compare && <col style={{ width: 38 }} />}
            <col style={{ width: 190 }} />
            {pillars.map(p => <col key={p} style={{ width: 78 }} />)}
            <col style={{ width: 70 }} />
          </colgroup>
          <thead><tr style={{ background: "var(--surface-deep)" }}>
            {compare && <th style={hHead(40)}></th>}
            <th style={Object.assign(hHead(190), { textAlign: "left", position: "sticky", left: 0, zIndex: 2 })}>Company</th>
            {pillars.map(p => <th key={p} onClick={() => setSortPillar(sp => sp === p ? null : p)} style={Object.assign(hHead(), { cursor: "pointer", color: sortPillar === p ? "var(--accent)" : "var(--ink-soft)" })}>{p.replace("Buy and Build", "Buy & Build").replace("Go-to-Market", "GTM")}</th>)}
            <th onClick={() => setSortPillar(sp => sp === "trend" ? null : "trend")} style={Object.assign(hHead(70), { cursor: "pointer", color: sortPillar === "trend" ? "var(--accent)" : "var(--ink-soft)" })}>Trend</th>
          </tr></thead>
          <tbody>
            {cos.map(c => <tr key={c.id}>
              {compare && <td style={{ textAlign: "center", borderBottom: "1px solid var(--line-soft)" }}><input type="checkbox" checked={selected.includes(c.id)} onChange={() => toggleSel(c.id)} /></td>}
              <td onClick={() => go({ route: "co-valuecreation", companyId: c.id })} style={{ padding: "8px 12px", borderBottom: "1px solid var(--line-soft)", position: "sticky", left: 0, background: "var(--surface-card)", cursor: "pointer" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 9 }}><CompanyMark company={c} size={24} /><div style={{ lineHeight: 1.2 }}><div style={{ fontWeight: 600, fontSize: 12.5 }}>{c.name}</div><div style={{ fontSize: 10.5, color: "var(--ink-soft)" }}>{c.fundLabel.replace("Northbridge ", "")}</div></div></div>
              </td>
              {pillars.map(p => <HeatCell key={p} score={c.pillars[p][0]} delta={c.pillars[p][1]} onClick={() => setDrill({ company: c, pillar: p })} />)}
              <td style={{ textAlign: "center", borderBottom: "1px solid var(--line-soft)" }}><TrendTag trend={VCP.trendOf(c.overallSeries)} /></td>
            </tr>)}
            {/* Totals */}
            <TotalRow label="Lexar Total" cos={scopeCos} pillars={pillars} pillarMean={pillarMean} compare={compare} bold />
            {VCP.FUNDS.map(f => <TotalRow key={f.value} label={f.label.replace("Northbridge ", "") + " Total"} cos={fundCos(f.value)} pillars={pillars} pillarMean={pillarMean} compare={compare} />)}
          </tbody>
        </table>
      </div>
    </div>

    {/* deep-link drawer */}
    <Drawer open={!!drill} onClose={() => setDrill(null)} width={440}
      eyebrow={drill && drill.company.name + " · Module C"} title={drill ? drill.pillar : ""}
      footer={drill && <><Btn variant="ghost" onClick={() => { go({ route: "co-valuecreation", companyId: drill.company.id }); setDrill(null); }}>Company matrix</Btn>
        <Btn icon="externalLink" onClick={() => { go({ door: "portco", route: "pc-assessment", companyId: drill.company.id, deeplink: { pillar: drill.pillar } }); setDrill(null); }}>Open in assessment</Btn></>}>
      {drill && <DrillContent company={drill.company} pillar={drill.pillar} />}
    </Drawer>

    {/* compare modal */}
    <CompareModal open={compare && selected.length >= 2 && false} />
    {compare && selected.length >= 2 && <CompareSheet companies={selected.map(id => VCP.companyById(id))} pillars={pillars} onClose={() => setSelected([])} />}
  </div>;
}

function hHead(w) { return { padding: "9px 8px", fontSize: 10.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.03em", color: "var(--ink-soft)", textAlign: "center", borderBottom: "1px solid var(--line)", whiteSpace: "nowrap", background: "var(--surface-deep)", width: w }; }

function TotalRow({ label, cos, pillars, pillarMean, compare, bold }) {
  return <tr style={{ background: bold ? "var(--accent-soft)" : "var(--surface)" }}>
    {compare && <td style={{ borderBottom: "1px solid var(--line)" }}></td>}
    <td style={{ padding: "9px 12px", fontWeight: 700, fontSize: 12.5, position: "sticky", left: 0, background: bold ? "var(--accent-soft)" : "var(--surface)", borderBottom: "1px solid var(--line)", color: bold ? "var(--accent)" : "var(--ink)" }}>{label}</td>
    {pillars.map(p => { const m = pillarMean(cos, p); const band = VCP.scoreBand(m); return <td key={p} style={{ textAlign: "center", borderBottom: "1px solid var(--line)" }}><span className="tabular" style={{ fontWeight: 700, fontSize: 12.5, color: BAND_FG[band] }}>{m.toFixed(1)}</span></td>; })}
    <td style={{ borderBottom: "1px solid var(--line)" }}></td>
  </tr>;
}

function DrillContent({ company, pillar }) {
  const pillarDef = VCP.PILLARS.find(p => p.key === pillar);
  // synth subpillar scores around the pillar score
  const base = company.pillars[pillar][0];
  const isHeliosTech = company.id === "helios" && pillar === "Technology";
  const subs = pillarDef.subpillars.map((sp, i) => {
    let s = isHeliosTech ? VCP.heliosTechSubpillars[sp] : Math.max(1, Math.min(5, +(base + ((i % 3) - 1) * 0.3).toFixed(1)));
    return { sp, s };
  });
  return <div>
    <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
      <ScoreBadge score={base} /><span style={{ fontSize: 13, color: "var(--ink-muted)" }}>Pillar score, {pillar}</span>
      <span style={{ marginLeft: "auto" }}><TrendTag trend={company.pillars[pillar][1] > 0.05 ? "up" : company.pillars[pillar][1] < -0.05 ? "down" : "stable"} delta={company.pillars[pillar][1]} /></span>
    </div>
    <div className="micro" style={{ marginBottom: 8 }}>Subpillars · 25Q2</div>
    <div style={{ display: "flex", flexDirection: "column", gap: 1 }}>
      {subs.map(({ sp, s }) => <div key={sp} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "8px 0", borderBottom: "1px solid var(--line-soft)" }}>
        <span style={{ fontSize: 13 }}>{sp}</span><ScoreBadge score={s} size="sm" />
      </div>)}
    </div>
    <div style={{ marginTop: 16, padding: 12, background: "var(--surface-deep)", borderRadius: 9, fontSize: 12, color: "var(--ink-soft)", lineHeight: 1.5, display: "flex", gap: 9 }}>
      <Icon name="externalLink" size={15} style={{ marginTop: 1 }} />
      <span>Opening the assessment crosses into the company's own door: the same QRAP they fill, scoped to this pillar. The scores above roll up from those answers.</span>
    </div>
  </div>;
}

function CompareModal() { return null; }
function CompareSheet({ companies, pillars, onClose }) {
  return <Modal open={true} onClose={onClose} eyebrow="Maturity comparison" title={companies.map(c => c.name).join(" · ")} width={620}
    footer={<Btn variant="ghost" onClick={onClose}>Close</Btn>}>
    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
      <thead><tr><th style={{ textAlign: "left", padding: "6px 8px", fontSize: 11, textTransform: "uppercase", color: "var(--ink-soft)" }}>Pillar</th>{companies.map(c => <th key={c.id} style={{ padding: "6px 8px", fontSize: 11.5, fontWeight: 700 }}>{c.short}</th>)}</tr></thead>
      <tbody>
        {pillars.map(p => {
          const vals = companies.map(c => c.pillars[p][0]); const best = Math.max(...vals), worst = Math.min(...vals);
          return <tr key={p}><td style={{ padding: "7px 8px", borderBottom: "1px solid var(--line-soft)" }}>{p}</td>
            {companies.map((c, i) => <td key={c.id} style={{ textAlign: "center", padding: "5px 8px", borderBottom: "1px solid var(--line-soft)" }}>
              <span className="tabular" style={{ fontWeight: 700, color: vals[i] === best ? "var(--positive)" : vals[i] === worst ? "var(--danger)" : "var(--ink)" }}>{vals[i].toFixed(1)}</span>
            </td>)}</tr>;
        })}
        <tr style={{ background: "var(--accent-soft)" }}><td style={{ padding: "8px", fontWeight: 700, color: "var(--accent)" }}>Overall</td>{companies.map(c => <td key={c.id} style={{ textAlign: "center", fontWeight: 700 }} className="tabular">{c.maturity.toFixed(1)}</td>)}</tr>
      </tbody>
    </table>
  </Modal>;
}

/* ---------- Playbook Library ---------- */
function PlaybookLibrary({ readOnly, go }) {
  const [openP, setOpenP] = useState({ "Technology": true });
  const [detail, setDetail] = useState(null);
  return <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: 0 }}>
    {!readOnly && <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 12 }}><Btn size="sm" icon="plus" onClick={() => window.vcpToast?.("Add playbook (demo)")}>Add playbook</Btn></div>}
    <div style={{ background: "var(--surface-card)", border: "1px solid var(--line)", borderRadius: "var(--radius)", overflow: "hidden", boxShadow: "var(--shadow-card)" }}>
      {VCP.playbookLibrary.map(grp => {
        const total = grp.subpillars.reduce((a, s) => a + s.count, 0);
        const open = openP[grp.pillar];
        return <div key={grp.pillar} style={{ borderBottom: "1px solid var(--line-soft)" }}>
          <button onClick={() => setOpenP(o => ({ ...o, [grp.pillar]: !o[grp.pillar] }))} style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", padding: "12px 16px", border: "none", background: "transparent", textAlign: "left" }}>
            <Icon name={open ? "chevronD" : "chevronR"} size={15} color="var(--ink-soft)" />
            <span style={{ fontWeight: 700, fontSize: 13.5 }}>{grp.pillar}</span>
            <Badge variant={grp.pillar === "Technology" ? "accent" : "neutral"} style={{ marginLeft: "auto" }}>{total} {total === 1 ? "play" : "plays"}</Badge>
          </button>
          {open && <div style={{ padding: "0 16px 10px 40px" }}>
            {grp.subpillars.map(sp => <div key={sp.name} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "7px 0", borderTop: "1px solid var(--line-soft)" }}>
              <span style={{ fontSize: 12.5, color: sp.count ? "var(--ink)" : "var(--ink-soft)" }}>{sp.name}</span>
              {sp.count > 0 ? <button onClick={() => { const pb = VCP.playbooks.find(p => p.subpillar === sp.name); if (pb) setDetail(pb); else window.vcpToast?.(sp.count + " playbook(s)"); }} style={{ border: "none", background: "var(--accent-soft)", color: "var(--accent)", borderRadius: 100, padding: "2px 10px", fontSize: 11, fontWeight: 600, cursor: "pointer" }}>{sp.count} play{sp.count > 1 ? "s" : ""} →</button>
                : <span style={{ fontSize: 11, color: "var(--ink-faint)" }}>—</span>}
            </div>)}
          </div>}
        </div>;
      })}
    </div>
    <Drawer open={!!detail} onClose={() => setDetail(null)} width={540} eyebrow={detail && detail.pillar + " · " + detail.subpillar} title={detail ? detail.name : ""}>
      {detail && <PlaybookDetail pb={detail} readOnly={readOnly} />}
    </Drawer>
  </div>;
}

function PlaybookDetail({ pb, readOnly }) {
  const [tab, setTab] = useState("overview");
  return <div>
    <div style={{ display: "flex", gap: 10, marginBottom: 16 }}>
      <Badge variant="positive">{pb.status}</Badge>
      <Badge variant={PRIORITY_VARIANT[pb.priority]}>{pb.priority} priority</Badge>
      <Badge variant="neutral"><Icon name="clock" size={11} /> {pb.timeline}</Badge>
    </div>
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 1, background: "var(--line-soft)", border: "1px solid var(--line)", borderRadius: 10, overflow: "hidden", marginBottom: 16 }}>
      {[["Timeline", pb.timeline], ["Contacts + advisors", (pb.firmExperts.length + pb.externalAdvisors.length)], ["Priority", pb.priority]].map(([l, v]) => <div key={l} style={{ background: "var(--surface-card)", padding: "10px 12px" }}><div className="micro" style={{ marginBottom: 3 }}>{l}</div><div style={{ fontWeight: 700, fontSize: 14, textTransform: "capitalize" }}>{v}</div></div>)}
    </div>
    <Tabs tabs={[{ key: "overview", label: "Overview" }, { key: "actions", label: "Action items", badge: pb.actions.length }, { key: "people", label: "People" }, { key: "docs", label: "Documents", badge: pb.docs.length }]} active={tab} onChange={setTab} />

    {tab === "overview" && <div>
      <p style={{ marginTop: 0, fontSize: 13, lineHeight: 1.6, color: "var(--ink-muted)" }}>{pb.description}</p>
      <div style={{ padding: 13, background: "var(--accent-soft)", borderRadius: 10, marginBottom: 16 }}>
        <div className="micro" style={{ color: "var(--accent)", marginBottom: 4 }}>Project goal</div>
        <div style={{ fontSize: 13, fontWeight: 600 }}>{pb.goal}</div>
      </div>
      <div className="micro" style={{ marginBottom: 6 }}>Maps to subpillars</div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 16 }}>{pb.subpillarChips.map(c => <Badge key={c.sp} variant="neutral">{c.pillar} › {c.sp}</Badge>)}</div>
      <div className="micro" style={{ marginBottom: 6 }}>Linked projects</div>
      {pb.linkedProjects.map(lp => <div key={lp.name} style={{ display: "flex", alignItems: "center", gap: 9, padding: "9px 11px", border: "1px solid var(--line)", borderRadius: 9, marginBottom: 6 }}>
        <Icon name="briefcase" size={15} color="var(--ink-soft)" /><span style={{ fontWeight: 600, fontSize: 13 }}>{lp.name}</span><span style={{ marginLeft: "auto", fontSize: 12, color: "var(--ink-soft)" }}>{lp.company}</span>
        {!readOnly && <button onClick={() => window.vcpToast?.("Unlinked (demo)")} style={{ border: "none", background: "none", color: "var(--ink-faint)", cursor: "pointer" }}><Icon name="x" size={14} /></button>}
      </div>)}
      {!readOnly && <Btn variant="ghost" size="sm" icon="link" style={{ marginTop: 4 }} onClick={() => window.vcpToast?.("Link project (demo)")}>Link project</Btn>}
    </div>}

    {tab === "actions" && <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 2 }}><div className="micro">Recommended advisor</div><Badge variant="accent"><Icon name="star" size={11} /> {pb.recommendedAdvisor}</Badge></div>
      {pb.actions.map(a => <div key={a.n} style={{ display: "flex", gap: 12, padding: "11px 13px", border: "1px solid var(--line)", borderRadius: 10 }}>
        <span style={{ width: 24, height: 24, borderRadius: 7, background: "var(--surface-deep)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 12, flexShrink: 0 }}>{a.n}</span>
        <div style={{ flex: 1 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}><span style={{ fontWeight: 600, fontSize: 13 }}>{a.name}</span></div>
          <div style={{ fontSize: 12, color: "var(--ink-soft)", marginTop: 2 }}>{a.deliverable}</div>
          <div style={{ display: "flex", gap: 8, marginTop: 7 }}><Badge variant={PRIORITY_VARIANT[a.priority]}>{a.priority}</Badge><Badge variant="neutral"><Icon name="clock" size={11} /> {a.duration}</Badge></div>
        </div>
      </div>)}
    </div>}

    {tab === "people" && <div>
      <div className="micro" style={{ marginBottom: 8 }}>Firm experts</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 2, marginBottom: 16 }}>{pb.firmExperts.map(n => <ContactRow key={n} name={n} sub="Northbridge Capital" />)}</div>
      <div className="micro" style={{ marginBottom: 8 }}>External advisors</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>{pb.externalAdvisors.map(n => <ContactRow key={n} name={n} sub={n === pb.recommendedAdvisor ? "Recommended" : "Advisor"} external recommended={n === pb.recommendedAdvisor} />)}</div>
    </div>}

    {tab === "docs" && <DocList docs={pb.docs} readOnly={readOnly} />}
  </div>;
}

function ContactRow({ name, sub, external, recommended, onClick }) {
  return <button onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 4px", border: "none", background: "none", width: "100%", textAlign: "left", borderBottom: "1px solid var(--line-soft)", cursor: onClick ? "pointer" : "default" }}>
    {external ? <span style={{ width: 28, height: 28, borderRadius: 7, background: "var(--surface-deep)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name="briefcase" size={14} color="var(--ink-soft)" /></span> : <Avatar name={name} size={28} />}
    <div style={{ lineHeight: 1.25 }}><div style={{ fontWeight: 600, fontSize: 13 }}>{name}</div><div style={{ fontSize: 11.5, color: "var(--ink-soft)" }}>{sub}</div></div>
    {recommended && <Badge variant="accent" style={{ marginLeft: "auto" }}><Icon name="star" size={10} /></Badge>}
  </button>;
}

function DocList({ docs, readOnly }) {
  return <div>
    {!readOnly && <Btn variant="ghost" size="sm" icon="upload" style={{ marginBottom: 10 }} onClick={() => window.vcpToast?.("Upload to SharePoint (demo)")}>Upload</Btn>}
    <div style={{ border: "1px solid var(--line)", borderRadius: 10, overflow: "hidden" }}>
      {docs.map((d, i) => <div key={i} style={{ display: "flex", alignItems: "center", gap: 11, padding: "10px 12px", borderBottom: i < docs.length - 1 ? "1px solid var(--line-soft)" : "none" }}>
        <Icon name="fileText" size={16} color="var(--ink-soft)" />
        <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontWeight: 600, fontSize: 12.5 }}>{d.name}</div><div style={{ fontSize: 11, color: "var(--ink-soft)" }}>{d.by} · {d.modified}{d.folder ? " · " + d.folder : ""}</div></div>
        <span style={{ fontSize: 11, color: "var(--ink-faint)" }} className="tabular">{d.size}</span>
        <IconBtn name="download" size={15} onClick={() => window.vcpToast?.("Downloading " + d.name)} />
      </div>)}
    </div>
  </div>;
}

function ValueCreationFirm({ state, go }) {
  const [tab, setTab] = useState("heatmap");
  return <div className="route-fade" style={{ padding: "22px 28px 60px", maxWidth: 1240, margin: "0 auto" }}>
    <SectionHeader eyebrow="Module C · Value Creation" title="Portfolio value creation"
      sub="Where every company stands on the eight-pillar maturity model, and the reusable playbooks that move them." />
    <Tabs key={"vc-" + tab} tabs={[{ key: "heatmap", label: "Maturity heatmap", icon: "gauge" }, { key: "playbooks", label: "Playbook library", icon: "book" }]} active={tab} onChange={setTab} />
    {tab === "heatmap" ? <MaturityHeatmap state={state} go={go} /> : <PlaybookLibrary go={go} />}
  </div>;
}

Object.assign(window, { ValueCreationFirm, PlaybookLibrary, PlaybookDetail, ContactRow, DocList, HeatCell });
