/* Firm company workspace: Overview + Oversight (Valuation + Structure). */

/* ---- generators so every company has a coherent story ---- */
function buildBridge(c) {
  if (c.id === "helios") return VCP.heliosBridge;
  const entry = +(c.ev * 0.64).toFixed(0);
  const growth = +(c.ev * 0.30).toFixed(0);
  const margin = +(c.ev * 0.10).toFixed(0);
  const mult = +(c.ev * 0.05).toFixed(0);
  const nd = +(c.ev - c.equity).toFixed(0);
  let cum = entry;
  const steps = [{ name: "Entry valuation", value: entry, cumulative: entry, kind: "start" }];
  steps.push({ name: c.multipleType === "ARR" ? "Revenue (ARR) growth" : "EBITDA growth", value: growth, cumulative: cum += growth, kind: "up" });
  steps.push({ name: "Margin improvement", value: margin, cumulative: cum += margin, kind: "up" });
  steps.push({ name: "Multiple expansion", value: mult, cumulative: cum += mult, kind: "up" });
  const adj = c.ev - cum; // reconcile to current EV
  steps.push({ name: "Net debt change", value: -Math.abs(nd), cumulative: cum = c.ev, kind: "down" });
  steps.push({ name: "Current enterprise value", value: c.ev, cumulative: c.ev, kind: "end" });
  return {
    type: c.multipleType + " multiple", steps,
    summary: { entryValuation: entry, currentValuation: +c.ev.toFixed(0), netDebt: nd, equityValue: +c.equity.toFixed(0), stake: c.stake, stakeEquityValue: +(c.equity * c.stake / 100).toFixed(1), totalValueCreated: +(c.ev - entry).toFixed(0), realisedReturn: 0 },
    entry: { revenue: +(c.invested * 0.5).toFixed(1), ebitda: +(c.invested * 0.08).toFixed(1), multiple: c.entryMultiple, margin: 14, invested: c.invested, date: c.entryDate },
    developments: { [VCP.QUARTERS[3]]: "Valuation held in line with plan for " + c.name + ". See quarterly pack for detail.", [VCP.QUARTERS[2]]: "On-plan quarter.", [VCP.QUARTERS[1]]: "Baseline.", [VCP.QUARTERS[0]]: "Baseline." },
  };
}
function valTimeline(c) {
  if (c.id === "helios") return VCP.heliosValuationTimeline;
  return VCP.QUARTERS.map(q => { const f = QFACTOR[q]; return { q, ev: +(c.ev * f).toFixed(0), equity: +(c.equity * f).toFixed(0), mm: +(c.mm * (0.85 + 0.15 * f)).toFixed(2), irr: Math.round(c.irr * (0.85 + 0.15 * f)) }; });
}
/* ---- legal structure: tidy-tree auto-layout + realistic PE stacks ---- */
function layoutStructure(entities) {
  const NODE_W = 200, HGAP = 38, VGAP = 122;
  const children = {};
  entities.forEach(e => { if (e.parent) (children[e.parent] = children[e.parent] || []).push(e.id); });
  const root = entities.find(e => !e.parent);
  const pos = {}; let leaf = 0;
  function dfs(id, depth) {
    const kids = children[id] || [];
    let x;
    if (!kids.length) { x = leaf * (NODE_W + HGAP); leaf++; }
    else { const xs = kids.map(k => dfs(k, depth + 1)); x = (Math.min(...xs) + Math.max(...xs)) / 2; }
    pos[id] = { x, y: depth * VGAP };
    return x;
  }
  dfs(root.id, 0);
  const nodes = entities.map(e => ({ ...e, x: pos[e.id].x, y: pos[e.id].y, w: NODE_W }));
  const edges = entities.filter(e => e.parent).map(e => ({ from: e.parent, to: e.id, own: e.own != null ? e.own : 100, vote: e.vote != null ? e.vote : (e.own != null ? e.own : 100) }));
  return { nodes, edges };
}
const reg1 = s => "NL" + (8600 + s.charCodeAt(0)) + ".71.2" + (10 + s.charCodeAt(1) % 80);
const reg2 = s => "NL" + (8400 + s.charCodeAt(1)) + ".33.1" + (10 + s.charCodeAt(0) % 80);

const heliosStructure = (() => {
  const ents = [
    { id: "nb", name: "Northbridge Capital B.V.", country: "NL", reg: "NL8112.45.901", role: "Fund manager", board: ["P. Janssen (Managing Partner)", "S. Bakker (Director)"] },
    { id: "coop", parent: "nb", own: 100, name: "Northbridge Fund I Coöperatief U.A.", country: "NL", reg: "NL8221.06.334", role: "Fund vehicle", board: ["Northbridge Capital B.V. (Director)"] },
    { id: "topco", parent: "coop", own: 75, vote: 80, name: "NB Helios TopCo B.V.", country: "NL", reg: "NL8634.71.220", role: "HoldCo · sweet equity", capTable: true, board: ["P. Janssen", "A. Visser (CEO)", "Stichting STAK Helios"] },
    { id: "midco", parent: "topco", own: 100, name: "NB Helios MidCo B.V.", country: "NL", reg: "NL8634.71.221", role: "Shareholder loans", board: ["P. Janssen", "S. Bakker"] },
    { id: "bidco", parent: "midco", own: 100, name: "NB Helios BidCo B.V.", country: "NL", reg: "NL8634.71.222", role: "Senior facility", board: ["P. Janssen", "I. Mol (CFO)"] },
    { id: "opco", parent: "bidco", own: 100, name: "Helios Software B.V.", country: "NL", reg: "NL8459.33.118", role: "Platform · OpCo", board: ["A. Visser (CEO)", "M. de Wit (CCO)", "I. Mol (CFO)"] },
    { id: "de", parent: "opco", own: 100, name: "Helios Analytics GmbH", country: "DE", reg: "HRB 274119", role: "Operating subsidiary", board: ["L. Bergman (Geschäftsführer)"] },
    { id: "uk", parent: "opco", own: 100, name: "Helios Insights Ltd", country: "UK", reg: "UK 11820934", role: "Bolt-on · 2024", addOn: true, board: ["A. Visser", "R. Hughes (MD)"] },
  ];
  return Object.assign({ workspace: { name: "Helios fund-holding structure", type: "Fund / SPV", registration: "NL" } }, layoutStructure(ents), {
    capTable: {
      entity: "NB Helios TopCo B.V.",
      rows: [
        { holder: "Northbridge Fund I Coöperatief U.A.", cls: "Ordinary A", inst: "Equity", own: 75, vote: 80 },
        { holder: "STAK Helios Management (sweet equity)", cls: "Ordinary B", inst: "Equity", own: 18, vote: 15 },
        { holder: "De Vroom Participaties B.V. (CEO co-invest)", cls: "Ordinary A", inst: "Equity", own: 7, vote: 5 },
      ],
    },
    instruments: [
      { entity: "NB Helios TopCo B.V.", type: "Sweet equity (Ordinary B)", holder: "STAK Management", amount: "18%", note: "3-year vesting" },
      { entity: "NB Helios MidCo B.V.", type: "Shareholder loan note", holder: "Northbridge Fund I", amount: "€14.0M", note: "PIK 8%" },
      { entity: "NB Helios BidCo B.V.", type: "Senior facility (Term + RCF)", holder: "Bank syndicate", amount: "€22.0M", note: "E + 450bps" },
    ],
    kyc: [
      { name: "UBO register extract.pdf", entity: "NB Helios TopCo B.V.", modified: "2025-04-02" },
      { name: "Shareholders agreement (STAK).pdf", entity: "NB Helios TopCo B.V.", modified: "2021-05-19" },
      { name: "Facilities agreement.pdf", entity: "NB Helios BidCo B.V.", modified: "2021-05-20" },
      { name: "Deed of incorporation.pdf", entity: "Helios Software B.V.", modified: "2021-05-20" },
      { name: "Handelsregister extract.pdf", entity: "Helios Analytics GmbH", modified: "2024-11-14" },
    ],
  });
})();

const kasparStructure = (() => {
  const ents = [
    { id: "nb", name: "Northbridge Capital B.V.", country: "NL", reg: "NL8112.45.901", role: "Fund manager", board: ["P. Janssen", "S. Bakker"] },
    { id: "coop", parent: "nb", own: 100, name: "Northbridge Fund I Coöperatief U.A.", country: "NL", reg: "NL8221.06.334", role: "Fund vehicle", board: ["Northbridge Capital B.V."] },
    { id: "topco", parent: "coop", own: 70, vote: 75, name: "NB Kaspar TopCo B.V.", country: "NL", reg: "NL8640.55.118", role: "HoldCo · cap table", capTable: true, board: ["P. Janssen", "E. Schmidt (CEO)", "STAK Kaspar"] },
    { id: "bidco", parent: "topco", own: 100, name: "NB Kaspar BidCo B.V.", country: "NL", reg: "NL8640.55.119", role: "Acquisition · senior debt", board: ["P. Janssen", "T. Reinder"] },
    { id: "plat", parent: "bidco", own: 100, name: "Kaspar Foods B.V.", country: "NL", reg: "NL8112.90.554", role: "Buy-and-build platform", board: ["E. Schmidt (CEO)", "Group CFO"] },
    { id: "a1", parent: "plat", own: 100, name: "Van Dijk Bakkerijen B.V.", country: "NL", reg: "NL8233.41.020", role: "Add-on · 2021", addOn: true, board: ["J. van Dijk (MD)"] },
    { id: "a2", parent: "plat", own: 100, name: "De Vries Sauzen B.V.", country: "NL", reg: "NL8401.77.331", role: "Add-on · 2022", addOn: true, board: ["K. de Vries (MD)"] },
    { id: "a3", parent: "plat", own: 90, vote: 90, name: "Nordic Snacks AB", country: "SE", reg: "SE 556987-1122", role: "Add-on · 2023", addOn: true, board: ["A. Lindqvist (VD)"] },
    { id: "a4", parent: "plat", own: 100, name: "Alpen Feinkost GmbH", country: "DE", reg: "HRB 188204", role: "Add-on · 2024", addOn: true, board: ["M. Bauer (GF)"] },
  ];
  return Object.assign({ workspace: { name: "Kaspar buy-and-build structure", type: "Fund / Platform", registration: "NL" } }, layoutStructure(ents), {
    capTable: {
      entity: "NB Kaspar TopCo B.V.",
      rows: [
        { holder: "Northbridge Fund I Coöperatief U.A.", cls: "Ordinary A", inst: "Equity", own: 70, vote: 75 },
        { holder: "STAK Kaspar Management (sweet equity)", cls: "Ordinary B", inst: "Equity", own: 22, vote: 20 },
        { holder: "Founders (rollover)", cls: "Ordinary A", inst: "Equity", own: 8, vote: 5 },
      ],
    },
    instruments: [
      { entity: "NB Kaspar TopCo B.V.", type: "Sweet equity (Ordinary B)", holder: "STAK Management", amount: "22%", note: "ratchet on exit" },
      { entity: "NB Kaspar BidCo B.V.", type: "Senior + acquisition facility", holder: "Bank syndicate", amount: "€38.0M", note: "buy-and-build accordion" },
      { entity: "NB Kaspar BidCo B.V.", type: "Vendor loan notes", holder: "Add-on vendors", amount: "€6.5M", note: "deferred consideration" },
    ],
    kyc: [
      { name: "UBO register extract.pdf", entity: "NB Kaspar TopCo B.V.", modified: "2025-03-30" },
      { name: "Platform SPA.pdf", entity: "Kaspar Foods B.V.", modified: "2019-11-12" },
      { name: "Nordic Snacks SPA.pdf", entity: "Nordic Snacks AB", modified: "2023-06-18" },
      { name: "Alpen Feinkost SPA.pdf", entity: "Alpen Feinkost GmbH", modified: "2024-04-09" },
    ],
  });
})();

function genLegal(c) {
  if (c.id === "helios") return heliosStructure;
  if (c.id === "kaspar") return kasparStructure;
  const s = c.short, stake = c.stake, vote = Math.min(100, stake + 5);
  const growth = c.typeDeal === "Growth";
  const carve = c.typeDeal === "Carve-out";
  const ents = [
    { id: "nb", name: "Northbridge Capital B.V.", country: "NL", reg: "NL8112.45.901", role: "Fund manager", board: ["P. Janssen", "S. Bakker"] },
    { id: "coop", parent: "nb", own: 100, name: c.fundLabel + " Coöperatief U.A.", country: "NL", reg: "NL8221.06.334", role: "Fund vehicle", board: ["Northbridge Capital B.V."] },
    { id: "topco", parent: "coop", own: stake, vote, name: "NB " + s + " TopCo B.V.", country: "NL", reg: reg1(s), role: "HoldCo · cap table", capTable: true, board: ["P. Janssen", "Management STAK"] },
  ];
  let opcoParent = "topco";
  if (!growth) {
    ents.push({ id: "bidco", parent: "topco", own: 100, name: "NB " + s + " BidCo B.V.", country: "NL", reg: reg2(s), role: "Acquisition · senior debt", board: ["P. Janssen", c.name.split(" ")[0] + " CFO"] });
    opcoParent = "bidco";
  }
  ents.push({ id: "opco", parent: opcoParent, own: 100, name: c.name + " B.V.", country: "NL", reg: "NL8459.33." + (100 + s.charCodeAt(0) % 90), role: carve ? "Carved-out OpCo · TSA" : "Operating company", board: [c.name.split(" ")[0] + " CEO", c.name.split(" ")[0] + " CFO"] });
  if (c.typeDeal === "Buy and build") {
    ents.push({ id: "a1", parent: "opco", own: 100, name: s + " Bolt-on Group B.V.", country: "NL", reg: "NL8233." + s.charCodeAt(0) + ".010", role: "Add-on · 2023", addOn: true, board: ["Add-on MD"] });
    ents.push({ id: "a2", parent: "opco", own: 100, name: s + " International GmbH", country: "DE", reg: "HRB " + (180000 + s.charCodeAt(1)), role: "Add-on · 2024", addOn: true, board: ["Add-on GF"] });
  } else if (!growth) {
    ents.push({ id: "sub", parent: "opco", own: 100, name: c.name.split(" ")[0] + (c.sector === "Logistics" ? " Freight" : " International") + (c.id === "verbund" ? " NV" : " GmbH"), country: c.id === "verbund" ? "BE" : "DE", reg: c.id === "verbund" ? "BE 0644.221.118" : "HRB " + (190000 + s.charCodeAt(0)), role: "Operating subsidiary", board: ["Local MD"] });
  }
  const mgmtOwn = Math.max(0, 100 - stake - 5);
  return Object.assign({ workspace: { name: c.name + " holding structure", type: growth ? "Fund / Growth equity" : "Fund / SPV", registration: "NL" } }, layoutStructure(ents), {
    capTable: {
      entity: "NB " + s + " TopCo B.V.",
      rows: [
        { holder: c.fundLabel + " Coöperatief U.A.", cls: "Ordinary A", inst: "Equity", own: stake, vote },
        { holder: "Management STAK (sweet equity)", cls: "Ordinary B", inst: "Equity", own: mgmtOwn, vote: Math.max(0, 100 - vote) },
        { holder: "Founders co-invest", cls: "Ordinary A", inst: "Equity", own: 5, vote: Math.max(0, 100 - vote - Math.max(0, 100 - vote)) },
      ],
    },
    instruments: growth
      ? [{ entity: "NB " + s + " TopCo B.V.", type: "Preferred equity", holder: c.fundLabel, amount: VCP.fmtM(c.invested).replace("EUR ", "€"), note: "1x non-participating" }]
      : [
        { entity: "NB " + s + " TopCo B.V.", type: "Sweet equity (Ordinary B)", holder: "Management STAK", amount: mgmtOwn + "%", note: "vesting" },
        { entity: "NB " + s + " BidCo B.V.", type: "Senior facility", holder: "Bank syndicate", amount: VCP.fmtM(c.ev - c.equity).replace("EUR ", "€"), note: "E + 425bps" },
      ],
    kyc: [
      { name: "UBO register extract.pdf", entity: "NB " + s + " TopCo B.V.", modified: "2025-04-02" },
      { name: "Deed of incorporation.pdf", entity: c.name + " B.V.", modified: c.entryDate },
    ],
  });
}

/* ---- Overview ---- */
function CompanyOverview({ state, go }) {
  const c = VCP.companyById(state.companyId);
  const [edit, setEdit] = useState(false);
  const fin = c.id === "helios" ? VCP.heliosFinancials : null;
  const tasks = VCP.allTasks.filter(t => t.company === c.id);
  const trend = VCP.trendOf(c.overallSeries);

  const links = VCP.quickLinks;
  return <div className="route-fade" style={{ padding: "22px 28px 60px", maxWidth: 1240, margin: "0 auto" }}>
    {/* identity header */}
    <div style={{ display: "flex", alignItems: "flex-start", gap: 16, marginBottom: 20 }}>
      <CompanyMark company={c} size={52} />
      <div style={{ flex: 1 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <h2 style={{ margin: 0, fontSize: 22, fontWeight: 800, letterSpacing: "-0.02em" }}>{c.name}</h2>
          <Badge variant="positive">{c.status}</Badge>
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 16, marginTop: 8, fontSize: 12.5, color: "var(--ink-muted)" }}>
          <span><b style={{ color: "var(--ink)" }}>{c.typeDeal}</b></span>
          <span>{c.sector}</span>
          <span>{c.fundLabel}</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="calendar" size={13} /> Entry {c.entry}</span>
          <a href={"https://" + c.website} target="_blank" style={{ display: "inline-flex", alignItems: "center", gap: 5, color: "var(--accent)" }}><Icon name="globe" size={13} /> {c.website}</a>
        </div>
      </div>
      <Btn variant="ghost" size="sm" icon="pencil" onClick={() => { setEdit(e => !e); if (edit) window.vcpToast?.("Company info saved"); }}>{edit ? "Save" : "Edit info"}</Btn>
    </div>

    {/* key metrics at a glance — all 3 modules */}
    <div className="micro" style={{ marginBottom: 8 }}>At a glance · {state.period}</div>
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12, marginBottom: 12 }}>
      <GlanceCard label="Enterprise value" value={VCP.fmtM(c.ev).replace("EUR ", "€")} mod="A" />
      <GlanceCard label="Equity value" value={VCP.fmtM(c.equity).replace("EUR ", "€")} mod="A" />
      <GlanceCard label="Money multiple" value={c.mm.toFixed(1) + "x"} mod="A" color={c.mm > 1 ? "var(--positive)" : "var(--danger)"} />
      <GlanceCard label="IRR" value={c.irr + "%"} mod="A" color="var(--positive)" />
    </div>
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12, marginBottom: 24 }}>
      <GlanceCard label="Maturity" value={<span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}><ScoreBadge score={c.maturity} /><TrendTag trend={trend} /></span>} mod="C" onClick={() => go({ route: "co-valuecreation", companyId: c.id })} />
      <GlanceCard label="Open tasks" value={c.open} mod="B" onClick={() => go({ route: "co-collaboration", companyId: c.id })} />
      <GlanceCard label="Overdue tasks" value={c.overdue} mod="B" color={c.overdue > 0 ? "var(--danger)" : "var(--ink)"} onClick={() => go({ route: "co-collaboration", companyId: c.id })} />
      <GlanceCard label="Last assessment" value="25Q2" mod="C" sub="Submitted" />
    </div>

    <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 18 }}>
      {/* financial metrics panel (honest) */}
      <Card pad={18}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
          <div><div className="micro">Financial metrics</div><div style={{ fontSize: 11.5, color: "var(--ink-soft)", marginTop: 2 }}>Sample data · production connects PowerBI</div></div>
          <Badge variant="warn"><Icon name="barChart" size={11} /> Connect PowerBI</Badge>
        </div>
        {fin ? <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
          <thead><tr><th style={finTh("left")}>Metric</th><th style={finTh("right")}>LE</th><th style={finTh("right")}>Budget</th><th style={finTh("right")}>Growth YoY</th></tr></thead>
          <tbody>{fin.map(r => <tr key={r.metric}><td style={{ padding: "9px 6px", borderBottom: "1px solid var(--line-soft)", fontWeight: 600 }}>{r.metric}</td>
            <td style={{ padding: "9px 6px", textAlign: "right", borderBottom: "1px solid var(--line-soft)" }} className="tabular">€{r.le}M</td>
            <td style={{ padding: "9px 6px", textAlign: "right", borderBottom: "1px solid var(--line-soft)", color: "var(--ink-soft)" }} className="tabular">€{r.budget}M</td>
            <td style={{ padding: "9px 6px", textAlign: "right", borderBottom: "1px solid var(--line-soft)", color: "var(--positive)", fontWeight: 600 }} className="tabular">+{r.growth}%</td></tr>)}</tbody>
        </table> : <EmptyState icon="barChart" title="No financials connected" sub="Connect this company's PowerBI workspace to surface revenue, EBITDA and budget here." />}
      </Card>

      {/* quick links + open work */}
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        <Card pad={18}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}><div className="micro">Quick links</div><IconBtn name="plus" size={15} onClick={() => window.vcpToast?.("Add custom link (demo)")} /></div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
            {links.map(l => <button key={l.name} onClick={() => { if (l.name === "Value Creation") go({ route: "co-valuecreation", companyId: c.id }); else if (l.name === "Documents") go({ route: "co-collaboration", companyId: c.id, deeplink: { tab: "docs" } }); else window.vcpToast?.("Opening " + l.name); }} style={{ display: "flex", alignItems: "center", gap: 9, padding: "10px 11px", borderRadius: 9, border: "1px solid var(--line)", background: "var(--surface-card)", cursor: "pointer", textAlign: "left" }}>
              <Icon name={l.icon} size={16} color="var(--accent)" /><span style={{ fontSize: 12.5, fontWeight: 600 }}>{l.name}</span><Icon name="chevronR" size={13} color="var(--ink-faint)" style={{ marginLeft: "auto" }} />
            </button>)}
          </div>
        </Card>
        <Card pad={18}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}><div className="micro">Open work</div><button onClick={() => go({ route: "co-collaboration", companyId: c.id })} style={{ border: "none", background: "none", color: "var(--accent)", fontSize: 12, fontWeight: 600, cursor: "pointer" }}>View all →</button></div>
          {tasks.slice(0, 4).map(t => <div key={t.id} style={{ display: "flex", alignItems: "center", gap: 9, padding: "8px 0", borderBottom: "1px solid var(--line-soft)" }}>
            <Badge variant={PRIORITY_VARIANT[t.priority]} style={{ minWidth: 8, padding: "2px 7px" }}>{t.priority[0].toUpperCase()}</Badge>
            <span style={{ fontSize: 12.5, flex: 1 }}>{t.name}</span>
            <span className="tabular" style={{ fontSize: 11, color: t.overdue ? "var(--danger)" : "var(--ink-soft)" }}>{t.due}</span>
          </div>)}
        </Card>
      </div>
    </div>
  </div>;
}
function GlanceCard({ label, value, mod, sub, color, onClick }) {
  return <div onClick={onClick} style={{ background: "var(--surface-card)", border: "1px solid var(--line)", borderRadius: 10, padding: "12px 14px", boxShadow: "var(--shadow-card)", cursor: onClick ? "pointer" : "default", position: "relative" }}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}><div className="micro">{label}</div><span style={{ fontSize: 9, fontWeight: 700, color: "var(--ink-faint)", border: "1px solid var(--line)", borderRadius: 4, padding: "0 4px" }}>{mod}</span></div>
    <div className="tabular" style={{ fontSize: 22, fontWeight: 700, marginTop: 7, letterSpacing: "-0.01em", color: color || "var(--ink)" }}>{value}</div>
    {sub && <div style={{ fontSize: 11, color: "var(--ink-soft)", marginTop: 2 }}>{sub}</div>}
  </div>;
}
function finTh(align) { return { textAlign: align, padding: "6px", fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.04em", color: "var(--ink-soft)", fontWeight: 600, borderBottom: "1px solid var(--line)" }; }

/* ---- Oversight: Valuation + Structure ---- */
function CompanyOversight({ state, go }) {
  const c = VCP.companyById(state.companyId);
  const [tab, setTab] = useState("valuation");
  return <div className="route-fade" style={{ padding: "22px 28px 60px", maxWidth: 1240, margin: "0 auto" }}>
    <SectionHeader eyebrow="Module A · Investment" title="Investment management"
      sub="This company's valuation story and its legal ownership." />
    <Tabs tabs={[{ key: "valuation", label: "Valuation", icon: "trendingUp" }, { key: "structure", label: "Structure", icon: "network" }]} active={tab} onChange={setTab} />
    {tab === "valuation" ? <ValuationView c={c} /> : <StructureView c={c} />}
  </div>;
}

function ValuationView({ c }) {
  const tl = valTimeline(c);
  const bridge = buildBridge(c);
  const [selQ, setSelQ] = useState("25Q2");
  const [edit, setEdit] = useState(false);
  const sel = tl.find(p => p.q === selQ) || tl[tl.length - 1];
  const s = bridge.summary;
  return <div>
    <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginBottom: 14 }}>
      <Btn variant="ghost" size="sm" icon="download" onClick={() => window.vcpToast?.("Exported portfolio report to Word")}>Export to Word</Btn>
      <Btn variant={edit ? "primary" : "ghost"} size="sm" icon="pencil" onClick={() => { setEdit(e => !e); if (edit) window.vcpToast?.("Valuation saved"); }}>{edit ? "Done editing" : "Edit"}</Btn>
    </div>
    <KPIStrip items={[
      { label: "Invested capital", value: VCP.fmtM(bridge.entry.invested).replace("EUR ", "€"), icon: "euro" },
      { label: "Total equity value", value: VCP.fmtM(c.equity).replace("EUR ", "€"), icon: "trendingUp" },
      { label: "Money multiple", value: c.mm.toFixed(1) + "x", color: "var(--positive)" },
      { label: "IRR", value: c.irr + "%", color: "var(--positive)" },
    ]} />

    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, marginTop: 18 }}>
      <Card pad={18}>
        <div className="micro" style={{ marginBottom: 8 }}>Equity value timeline</div>
        <AreaLineChart points={tl} accessor={p => p.equity} format={v => "€" + v + "M"} selected={selQ} onSelect={setSelQ} height={170} />
      </Card>
      <Card pad={18}>
        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}><div className="micro">Quarter detail · {selQ}</div>{edit && <Badge variant="accent">Editing</Badge>}</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 1, background: "var(--line-soft)", border: "1px solid var(--line)", borderRadius: 10, overflow: "hidden" }}>
          {[["Invested capital", VCP.fmtM(bridge.entry.invested).replace("EUR ", "€")], ["Equity value", "€" + sel.equity + "M"], ["Money multiple", sel.mm.toFixed(2) + "x"], ["IRR", sel.irr + "%"]].map(([l, v]) => <div key={l} style={{ background: "var(--surface-card)", padding: "11px 13px" }}><div className="micro">{l}</div><div className="tabular" style={{ fontWeight: 700, fontSize: 16, marginTop: 4 }}>{v}</div></div>)}
        </div>
        <div className="micro" style={{ margin: "14px 0 6px" }}>Entry data</div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 14, fontSize: 12 }}>
          {[["Entry revenue", "€" + bridge.entry.revenue + "M"], ["Entry EBITDA", "€" + bridge.entry.ebitda + "M"], ["Entry multiple", bridge.entry.multiple + "x"], ["Entry margin", bridge.entry.margin + "%"]].map(([l, v]) => <div key={l}><span style={{ color: "var(--ink-soft)" }}>{l} </span><b className="tabular">{v}</b></div>)}
        </div>
      </Card>
    </div>

    {/* value bridge waterfall */}
    <Card style={{ marginTop: 18 }} pad={20}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 8 }}>
        <div><div className="micro">Value bridge · entry to {selQ}</div><div style={{ fontSize: 12, color: "var(--ink-soft)", marginTop: 2 }}>Enterprise value attribution · {bridge.type}</div></div>
        <Badge variant="positive"><Icon name="trendingUp" size={11} /> €{s.totalValueCreated}M created</Badge>
      </div>
      <Waterfall steps={bridge.steps} />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 1, background: "var(--line-soft)", border: "1px solid var(--line)", borderRadius: 10, overflow: "hidden", marginTop: 18 }}>
        {[["Entry valuation", "€" + s.entryValuation + "M"], ["Current valuation", "€" + s.currentValuation + "M"], ["Net debt", "€" + s.netDebt + "M"], ["Equity value", "€" + s.equityValue + "M"], ["Northbridge stake", s.stake + "%"], ["Northbridge equity value", "€" + s.stakeEquityValue + "M"], ["Total value created", "€" + s.totalValueCreated + "M"], ["Realised return", "€" + s.realisedReturn + "M"]].map(([l, v]) => <div key={l} style={{ background: "var(--surface-card)", padding: "10px 12px" }}><div className="micro">{l}</div><div className="tabular" style={{ fontWeight: 700, fontSize: 14, marginTop: 3 }}>{v}</div></div>)}
      </div>
    </Card>

    {/* developments + docs */}
    <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 18, marginTop: 18 }}>
      <Card pad={18}>
        <div className="micro" style={{ marginBottom: 8 }}>Quarterly developments · {selQ}</div>
        <p style={{ margin: 0, fontSize: 13, lineHeight: 1.6, color: "var(--ink-muted)" }}>{bridge.developments[selQ] || bridge.developments["25Q2"]}</p>
      </Card>
      <Card pad={18}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}><div className="micro">Valuation documents</div><IconBtn name="upload" size={15} onClick={() => window.vcpToast?.("Upload (demo)")} /></div>
        {[{ name: "Valuation workbook " + selQ + ".xlsx", by: "S. Bakker", modified: "2025-05-30", size: "1.4 MB" }, { name: "Bridge analysis.pptx", by: "Northvalue", modified: "2025-05-28", size: "3.1 MB" }].map((d, i) => <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 0", borderBottom: "1px solid var(--line-soft)" }}>
          <Icon name="fileText" size={15} color="var(--ink-soft)" /><div style={{ flex: 1 }}><div style={{ fontSize: 12.5, fontWeight: 600 }}>{d.name}</div><div style={{ fontSize: 11, color: "var(--ink-soft)" }}>{d.by} · {d.modified}</div></div><IconBtn name="download" size={14} onClick={() => window.vcpToast?.("Downloading")} />
        </div>)}
      </Card>
    </div>
  </div>;
}

function StructureView({ c }) {
  const data = genLegal(c);
  const [edit, setEdit] = useState(false);
  const [sel, setSel] = useState(null);
  const capTotal = data.capTable.rows.reduce((a, r) => a + r.own, 0);
  return <div>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
      <div style={{ fontSize: 12.5, color: "var(--ink-soft)" }}>{data.workspace.name} · {data.nodes.length} entities</div>
      <div style={{ display: "flex", gap: 8 }}>
        {edit && <Btn variant="ghost" size="sm" icon="plus" onClick={() => window.vcpToast?.("Add entity (demo)")}>Add entity</Btn>}
        {edit && <Btn variant="ghost" size="sm" icon="link" onClick={() => window.vcpToast?.("Add ownership (demo)")}>Add ownership</Btn>}
        <Btn variant={edit ? "primary" : "ghost"} size="sm" icon="pencil" onClick={() => { setEdit(e => !e); if (edit) window.vcpToast?.("Structure saved · ownership totals validated"); }}>{edit ? "Save layout" : "Edit"}</Btn>
      </div>
    </div>
    <LegalGraph data={data} editMode={edit} height={560} onSelect={setSel} selectedId={sel && sel.id} />
    <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 18, marginTop: 18 }}>
      <Card pad={18}>
        <div className="micro" style={{ marginBottom: 10 }}>Cap table · {data.capTable.entity}</div>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
          <thead><tr><th style={finTh("left")}>Shareholder</th><th style={finTh("left")}>Class</th><th style={finTh("left")}>Instrument</th><th style={finTh("right")}>Own.</th><th style={finTh("right")}>Vote</th></tr></thead>
          <tbody>
            {data.capTable.rows.map(r => <tr key={r.holder}>
              <td style={{ padding: "9px 6px", borderBottom: "1px solid var(--line-soft)", fontSize: 12.5 }}>{r.holder}</td>
              <td style={{ padding: "9px 6px", borderBottom: "1px solid var(--line-soft)" }}><Badge variant={r.cls && r.cls.includes("B") ? "warn" : "neutral"}>{r.cls}</Badge></td>
              <td style={{ padding: "9px 6px", borderBottom: "1px solid var(--line-soft)", color: "var(--ink-soft)", fontSize: 12 }}>{r.inst}</td>
              <td className="tabular" style={{ padding: "9px 6px", textAlign: "right", borderBottom: "1px solid var(--line-soft)", fontWeight: 600 }}>{r.own}%</td>
              <td className="tabular" style={{ padding: "9px 6px", textAlign: "right", borderBottom: "1px solid var(--line-soft)", color: "var(--ink-muted)" }}>{r.vote}%</td>
            </tr>)}
            <tr><td style={{ padding: "8px 6px", fontWeight: 700 }}>Total</td><td></td><td></td><td className="tabular" style={{ textAlign: "right", fontWeight: 700, color: capTotal === 100 ? "var(--positive)" : "var(--danger)" }}>{capTotal}%</td><td></td></tr>
          </tbody>
        </table>
        <div className="micro" style={{ margin: "16px 0 8px" }}>Funding instruments</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
          {data.instruments.map((ins, i) => <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 11px", border: "1px solid var(--line)", borderRadius: 9 }}>
            <Icon name={ins.type.includes("equity") || ins.type.includes("Sweet") || ins.type.includes("Preferred") ? "trendingUp" : "euro"} size={15} color="var(--ink-soft)" />
            <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 12.5, fontWeight: 600 }}>{ins.type}</div><div style={{ fontSize: 11, color: "var(--ink-soft)" }}>{ins.entity} · {ins.holder}{ins.note ? " · " + ins.note : ""}</div></div>
            <span className="tabular" style={{ fontWeight: 700, fontSize: 13 }}>{ins.amount}</span>
          </div>)}
        </div>
      </Card>
      <Card pad={18}>
        <div className="micro" style={{ marginBottom: 10 }}>KYC documents</div>
        {data.kyc.map((d, i) => <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 0", borderBottom: i < data.kyc.length - 1 ? "1px solid var(--line-soft)" : "none" }}>
          <Icon name="shield" size={15} color="var(--ink-soft)" /><div style={{ flex: 1 }}><div style={{ fontSize: 12.5, fontWeight: 600 }}>{d.name}</div><div style={{ fontSize: 11, color: "var(--ink-soft)" }}>{d.entity} · {d.modified}</div></div><IconBtn name="download" size={14} onClick={() => window.vcpToast?.("Downloading")} />
        </div>)}
      </Card>
    </div>

    <Drawer open={!!sel} onClose={() => setSel(null)} width={400} eyebrow={sel && sel.country + " · " + sel.role} title={sel ? sel.name : ""}>
      {sel && <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <Badge variant="neutral">{sel.country}</Badge>
          {sel.capTable && <Badge variant="accent">Cap table entity</Badge>}
          {sel.addOn && <Badge variant="positive">Buy-and-build add-on</Badge>}
        </div>
        {[["Role", sel.role], ["Registration", sel.reg], ["Ownership by parent", sel.own != null ? sel.own + "%" + (sel.vote != null && sel.vote !== sel.own ? " (vote " + sel.vote + "%)" : "") : "—"]].map(([l, v]) => v && <div key={l} style={{ display: "flex", justifyContent: "space-between", padding: "9px 0", borderBottom: "1px solid var(--line-soft)", gap: 12 }}><span className="micro">{l}</span><span style={{ fontSize: 12.5, fontWeight: 500, textAlign: "right" }} className={l === "Registration" ? "tabular" : ""}>{v}</span></div>)}
        <div>
          <div className="micro" style={{ marginBottom: 8 }}>Management board</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            {(sel.board || []).map(m => <div key={m} style={{ display: "flex", alignItems: "center", gap: 9, padding: "7px 0", borderBottom: "1px solid var(--line-soft)" }}><Avatar name={m.replace(/\(.*\)/, "").trim()} size={26} /><span style={{ fontSize: 12.5 }}>{m}</span></div>)}
            {(!sel.board || !sel.board.length) && <span style={{ fontSize: 12, color: "var(--ink-faint)" }}>No board recorded.</span>}
          </div>
        </div>
        {sel.capTable && <div style={{ padding: 12, background: "var(--accent-soft)", borderRadius: 9, fontSize: 12, color: "var(--accent)", lineHeight: 1.5 }}>This entity holds the deal cap table. See the cap table panel for share classes, instruments, ownership, and voting.</div>}
      </div>}
    </Drawer>
  </div>;
}

Object.assign(window, { CompanyOverview, CompanyOversight, buildBridge, valTimeline, genLegal, GlanceCard });
