/* Shared Modal + Fund Cockpit (Module A, firm portfolio home). */

function Modal({ open, onClose, title, eyebrow, children, footer, width = 480 }) {
  useEffect(() => {
    const h = e => e.key === "Escape" && onClose();
    if (open) window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [open, onClose]);
  if (!open) return null;
  return <div style={{ position: "fixed", inset: 0, zIndex: 90, display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }}>
    <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "rgba(26,28,30,0.36)", animation: "vcpScrim 150ms ease" }} />
    <div style={{ position: "relative", width, maxWidth: "94vw", maxHeight: "88vh", display: "flex", flexDirection: "column", background: "var(--surface-card)", borderRadius: 14, boxShadow: "var(--shadow-pop)", animation: "vcpFade 150ms ease" }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", padding: "16px 20px", borderBottom: "1px solid var(--line)" }}>
        <div>{eyebrow && <div className="micro" style={{ marginBottom: 4 }}>{eyebrow}</div>}<div style={{ fontSize: 16, fontWeight: 700 }}>{title}</div></div>
        <IconBtn name="x" onClick={onClose} />
      </div>
      <div className="scroll-y" style={{ padding: 20, flex: 1 }}>{children}</div>
      {footer && <div style={{ padding: "14px 20px", borderTop: "1px solid var(--line)", display: "flex", gap: 8, justifyContent: "flex-end" }}>{footer}</div>}
    </div>
  </div>;
}

function ImportModal({ open, onClose, kind, fund }) {
  return <Modal open={open} onClose={onClose} eyebrow="Module A · Valuations engine" title={kind === "val" ? "Import valuations" : "Import developments"} width={460}
    footer={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn icon="check" onClick={() => { window.vcpToast?.("Import queued — scoped to " + fund); onClose(); }}>Run import</Btn></>}>
    <p style={{ marginTop: 0, color: "var(--ink-muted)", fontSize: 13 }}>
      {kind === "val" ? "Upload the quarterly valuation workbook. The bridge importer reads each company sheet and writes one snapshot per company for the selected fund." : "Upload the narrative workbook. Quarterly developments are matched to each company by name."}
    </p>
    <div style={{ border: "1.5px dashed var(--line)", borderRadius: 12, padding: "32px 20px", textAlign: "center", background: "var(--surface)" }}>
      <div style={{ display: "inline-flex", padding: 12, borderRadius: 12, background: "var(--surface-deep)", marginBottom: 10 }}><Icon name="upload" size={20} color="var(--ink-soft)" /></div>
      <div style={{ fontWeight: 600 }}>Drop {kind === "val" ? "valuation workbook" : "developments workbook"} here</div>
      <div style={{ fontSize: 12, color: "var(--ink-soft)", marginTop: 3 }}>.xlsx, scoped to {fund}</div>
    </div>
  </Modal>;
}

function AddCompanyModal({ open, onClose }) {
  return <Modal open={open} onClose={onClose} eyebrow="Portfolio" title="Add company" width={520}
    footer={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn icon="plus" onClick={() => { window.vcpToast?.("Company created (demo)"); onClose(); }}>Create company</Btn></>}>
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
      <Field label="Company name"><TextInput placeholder="e.g. Helios Software B.V." /></Field>
      <Field label="Website"><TextInput placeholder="company.example" /></Field>
      <Field label="Fund"><Select value="" onChange={() => {}} options={VCP.FUNDS} placeholder="Select fund" width="100%" /></Field>
      <Field label="Type of deal"><Select value="" onChange={() => {}} options={VCP.optionLists["Deal types"]} placeholder="Select" width="100%" /></Field>
      <Field label="Sector"><Select value="" onChange={() => {}} options={VCP.optionLists["Sectors"]} placeholder="Select" width="100%" /></Field>
      <Field label="Entry date"><TextInput type="date" /></Field>
      <Field label="Invested capital (EUR M)"><TextInput type="number" placeholder="0.0" /></Field>
      <Field label="Entry multiple"><TextInput type="number" placeholder="0.0" /></Field>
    </div>
  </Modal>;
}

/* quarter scaling so period selection feels live */
const QFACTOR = { "24Q3": 0.86, "24Q4": 0.92, "25Q1": 0.97, "25Q2": 1.0 };
function coAtQuarter(c, q) {
  const f = QFACTOR[q] || 1;
  return {
    ...c, ev: c.ev * f, equity: c.equity * f,
    mm: +(c.mm * (0.8 + 0.2 * f)).toFixed(2), irr: Math.round(c.irr * (0.82 + 0.18 * f)),
    lexarEquity: c.equity * f * c.stake / 100,
  };
}

function FundCockpit({ state, go }) {
  const [fund, setFund] = useState("all");
  const [view, setView] = useState("value"); // value | multiple
  const [selQ, setSelQ] = useState(null);
  const [edit, setEdit] = useState(false);
  const [modal, setModal] = useState(null);
  const sortMaster = useSort();
  const sortDetail = useSort();

  const roll = VCP.fundRollup[fund];
  const timeline = VCP.fundTimeline[fund];
  const cos = useMemo(() => VCP.companies.filter(c => fund === "all" || c.fund === fund), [fund]);

  const masterCols = [
    { key: "name", label: "Company", render: c => <div style={{ display: "flex", alignItems: "center", gap: 10 }}><CompanyMark company={c} /><span style={{ fontWeight: 600 }}>{c.name}</span></div> },
    { key: "typeDeal", label: "Type", render: c => <span style={{ color: "var(--ink-muted)" }}>{c.typeDeal}</span> },
    { key: "fundLabel", label: "Fund", render: c => <span style={{ color: "var(--ink-muted)", fontSize: 12 }}>{c.fundLabel.replace("Northbridge ", "")}</span> },
    { key: "sector", label: "Sector", render: c => <span style={{ color: "var(--ink-muted)" }}>{c.sector}</span> },
    { key: "ev", label: "Enterprise value", align: "right", render: c => <span className="tabular" style={{ fontWeight: 600 }}>{VCP.fmtM(c.ev)}</span> },
    { key: "equity", label: "Equity value", align: "right", render: c => <span className="tabular">{VCP.fmtM(c.equity)}</span> },
    { key: "maturity", label: "Maturity", align: "right", render: c => <ScoreBadge score={c.maturity} size="sm" /> },
    { key: "open", label: "Open", align: "right", render: c => <span className="tabular" style={{ fontWeight: 600 }}>{c.open}</span> },
    { key: "overdue", label: "Overdue", align: "right", render: c => <span className="tabular" style={{ fontWeight: 700, color: c.overdue > 0 ? "var(--danger)" : "var(--ink-faint)" }}>{c.overdue}</span> },
  ];
  const masterRows = sortMaster.apply(cos);

  const detailCos = selQ ? cos.map(c => coAtQuarter(c, selQ)) : [];
  const detailCols = [
    { key: "name", label: "Company", render: c => <div style={{ display: "flex", alignItems: "center", gap: 9 }}><CompanyMark company={c} size={22} /><span style={{ fontWeight: 600 }}>{c.name}</span></div> },
    { key: "entryDate", label: "Entry", render: c => <span style={{ color: "var(--ink-muted)" }} className="tabular">{c.entry}</span> },
    { key: "entryMultiple", label: "Entry mult.", align: "right", render: c => <span className="tabular">{c.entryMultiple.toFixed(1)}x</span> },
    { key: "exitMultiple", label: "Exit mult.", align: "right", render: c => <span className="tabular">{c.exitMultiple.toFixed(1)}x</span> },
    { key: "ev", label: "EV", align: "right", render: c => <span className="tabular" style={{ fontWeight: 600 }}>{VCP.fmtM(c.ev)}</span> },
    { key: "lexarEquity", label: "NB equity value", align: "right", render: c => <span className="tabular">{VCP.fmtM(c.lexarEquity)}</span> },
    { key: "invested", label: "Invested", align: "right", render: c => <span className="tabular">{VCP.fmtM(c.invested)}</span> },
    { key: "irr", label: "IRR", align: "right", render: c => <span className="tabular" style={{ color: c.irr > 0 ? "var(--positive)" : "var(--danger)", fontWeight: 600 }}>{c.irr}%</span> },
    { key: "mm", label: "MM", align: "right", render: c => <span className="tabular" style={{ color: c.mm > 1 ? "var(--positive)" : "var(--danger)", fontWeight: 600 }}>{c.mm.toFixed(1)}x</span> },
  ];
  const detailRows = sortDetail.apply(detailCos);

  return <div className="route-fade" style={{ padding: "22px 28px 60px", maxWidth: 1240, margin: "0 auto" }}>
    <SectionHeader eyebrow="Module A · Investments" title="Portfolio cockpit"
      sub="Every company's value, maturity, and open work in one read. The front door to the whole fund."
      right={<>
        <Btn variant="ghost" size="sm" icon="download" onClick={() => window.vcpToast?.("Fund report exported (demo)")}>Export</Btn>
        <Btn variant="ghost" size="sm" icon="upload" onClick={() => setModal("val")}>Import valuations</Btn>
        <Btn icon="plus" size="sm" onClick={() => setModal("add")}>Add company</Btn>
      </>} />

    {/* fund selector + roll-up band */}
    <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
      <div className="micro">Fund roll-up · {state.period}</div>
      <div style={{ flex: 1 }} />
      <div style={{ display: "inline-flex", background: "var(--surface-deep)", borderRadius: 9, padding: 3, gap: 2 }}>
        {[{ v: "all", l: "All funds" }, { v: "fund-1", l: "Fund I" }, { v: "fund-2", l: "Fund II" }].map(o => <button key={o.v} onClick={() => { setFund(o.v); setSelQ(null); }} style={{
          padding: "5px 12px", borderRadius: 7, border: "none", fontSize: 12.5, fontWeight: 600,
          background: fund === o.v ? "var(--surface-card)" : "transparent", color: fund === o.v ? "var(--ink)" : "var(--ink-soft)",
          boxShadow: fund === o.v ? "var(--shadow-card)" : "none",
        }}>{o.l}</button>)}
      </div>
    </div>
    <KPIStrip items={[
      { label: "Invested capital", value: VCP.fmtM(roll.invested).replace("EUR ", "€"), icon: "euro", sub: state.period },
      { label: "Total equity value", value: VCP.fmtM(roll.equity).replace("EUR ", "€"), icon: "trendingUp", sub: state.period },
      { label: "Fund money multiple", value: roll.mm.toFixed(1) + "x", icon: "barChart", delta: "MOIC", deltaColor: "var(--ink-soft)", color: "var(--positive)" },
      { label: "Fund IRR", value: roll.irr + "%", icon: "trendingUp", color: "var(--positive)" },
      { label: "Active companies", value: roll.active, icon: "building" },
    ]} />

    {/* timeline */}
    <Card style={{ marginTop: 18 }} pad={18}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6 }}>
        <div className="micro">Fund valuation timeline</div>
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          {selQ && <Badge variant="accent" style={{ cursor: "pointer" }}><span onClick={() => setSelQ(null)} style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>Quarter: {selQ}<Icon name="x" size={11} /></span></Badge>}
          <div style={{ display: "inline-flex", background: "var(--surface-deep)", borderRadius: 8, padding: 2 }}>
            {[{ v: "value", l: "Value" }, { v: "multiple", l: "Multiple" }].map(o => <button key={o.v} onClick={() => setView(o.v)} style={{ padding: "4px 11px", borderRadius: 6, border: "none", fontSize: 12, fontWeight: 600, background: view === o.v ? "var(--surface-card)" : "transparent", color: view === o.v ? "var(--ink)" : "var(--ink-soft)" }}>{o.l}</button>)}
          </div>
        </div>
      </div>
      <AreaLineChart points={timeline} selected={selQ} onSelect={q => setSelQ(q === selQ ? null : q)}
        accessor={view === "value" ? (p => p.equity) : (p => p.mm)}
        format={view === "value" ? (v => "€" + v.toFixed(0) + "M") : (v => v.toFixed(1) + "x")} />
      <div style={{ display: "flex", gap: 22, marginTop: 8, fontSize: 11.5, color: "var(--ink-soft)" }}>
        <span>Avg IRR <b className="tabular" style={{ color: "var(--ink)" }}>{timeline[timeline.length - 1].irr}%</b></span>
        <span>Avg MM <b className="tabular" style={{ color: "var(--ink)" }}>{timeline[timeline.length - 1].mm.toFixed(1)}x</b></span>
        <span>Companies <b className="tabular" style={{ color: "var(--ink)" }}>{timeline[timeline.length - 1].count}</b></span>
        <span style={{ marginLeft: "auto", color: "var(--ink-faint)" }}>Click a point to scope the breakdown below</span>
      </div>
    </Card>

    {/* selected quarter breakdown */}
    {selQ && <div style={{ marginTop: 22 }}>
      <SectionHeader eyebrow={"Selected quarter · " + selQ} title="Per-company valuation detail"
        right={<Btn variant="ghost" size="sm" icon="x" onClick={() => setSelQ(null)}>Clear quarter</Btn>} />
      <Table columns={detailCols} rows={detailRows} sortCtl={sortDetail} dense onRowClick={c => go({ route: "co-oversight", companyId: c.id })} rowKey={c => c.id} />
    </div>}

    {/* master table — hidden when a quarter breakdown is shown */}
    {!selQ && <div style={{ marginTop: 22 }}>
      <SectionHeader eyebrow="The fusion · value + maturity + work" title="Companies"
        right={<span style={{ fontSize: 12, color: "var(--ink-soft)" }}>{cos.length} companies</span>} />
      <Table columns={masterCols} rows={masterRows} sortCtl={sortMaster} onRowClick={c => go({ route: "co-overview", companyId: c.id })} rowKey={c => c.id} />
    </div>}

    <ImportModal open={modal === "val"} onClose={() => setModal(null)} kind="val" fund={fund === "all" ? "all funds" : VCP.FUNDS.find(f => f.value === fund).label} />
    <AddCompanyModal open={modal === "add"} onClose={() => setModal(null)} />
  </div>;
}

Object.assign(window, { Modal, FundCockpit, ImportModal, AddCompanyModal, coAtQuarter, QFACTOR });
