let ctSh = 1, ctInv = 1;
const ctNewSh = (name, type) => ({ id: ctSh++, name, type, common: "", ex: "", out: "", pref: "", series: "" });
const ctNewInv = name => ({ id: ctInv++, name, amt: "" });
const CT_TYPES = ["Founder", "Employee", "Advisor", "Investor"];

function CapTableCalc() {
  const [step, setStep] = React.useState(0);
  const [shs, setShs] = React.useState(() => [ctNewSh("Founder 1", "Founder")]);
  const [auth, setAuth] = React.useState("");
  const [unal, setUnal] = React.useState("");
  const [pre, setPre] = React.useState("");
  const [pex, setPex] = React.useState("");
  const [ptg, setPtg] = React.useState("");
  const [useT, setUseT] = React.useState(false);
  const [date, setDate] = React.useState("");
  const [invs, setInvs] = React.useState(() => [ctNewInv("Lead Investor")]);
  const upS = (id, k, v) => setShs(p => p.map(s => s.id === id ? { ...s, [k]: v } : s));
  const upI = (id, k, v) => setInvs(p => p.map(s => s.id === id ? { ...s, [k]: v } : s));

  const cur = React.useMemo(() => {
    const U = parseNum(unal);
    const rows = shs.map(s => { const c = parseNum(s.common), e = parseNum(s.ex), o = parseNum(s.out), p = parseNum(s.pref), tc = c + e; return { name: s.name || "Unnamed", type: s.type, c, e, o, tc, p, fd: tc + o + p, pct: 0 }; });
    const sum = k => rows.reduce((a, r) => a + r[k], 0);
    const totalFD = sum("fd") + U;
    rows.forEach(r => { r.pct = totalFD > 0 ? r.fd / totalFD : 0; });
    return { rows, t: { c: sum("c"), e: sum("e"), o: sum("o"), tc: sum("tc"), p: sum("p"), fd: sum("fd"), U, totalFD } };
  }, [shs, unal]);

  const pf = React.useMemo(() => {
    const P = parseNum(pre), U = parseNum(unal), inv = invs.reduce((a, i) => a + parseNum(i.amt), 0);
    if (P <= 0 || inv <= 0) return null;
    const post = P + inv, curFD = cur.t.fd + U, price = P / curFD, invSh = inv / price;
    let pool = 0;
    if (useT) { const t = parseNum(ptg) / 100; if (t > 0 && t < 1) pool = Math.max(0, (t * (curFD + invSh) - U) / (1 - t)); }
    else pool = parseNum(pex);
    const tot = curFD + invSh + pool, pc = x => tot > 0 ? x / tot : 0;
    const rows = cur.rows.map(s => ({ name: s.name, type: s.type, sh: s.fd, pct: pc(s.fd), src: "Existing" }));
    if (U > 0) rows.push({ name: "Unallocated Option Pool", type: "Pool", sh: U, pct: pc(U), src: "Existing" });
    if (pool > 0) rows.push({ name: "Option Pool Expansion", type: "Pool", sh: pool, pct: pc(pool), src: "New Financing" });
    invs.forEach(i => { const a = parseNum(i.amt); if (a > 0) { const s = a / price; rows.push({ name: i.name || "Unnamed Investor", type: "Investor", sh: s, pct: pc(s), src: "New Financing" }); } });
    return { rows, P, post, price, tot };
  }, [pre, unal, invs, cur, useT, ptg, pex]);

  const steps = ["Current Cap Table", "New Financing", "Pro Forma"];
  const byType = pf ? ["Founder", "Employee", "Advisor", "Investor", "Pool"].map((t, i) => [t === "Pool" ? "Option pool" : t + "s", pf.rows.filter(r => r.type === t).reduce((a, r) => a + r.pct, 0), CX_COL[i]]).filter(x => x[1] > 0) : [];
  return (
    <div className="cx-stack">
      <div className="ct-steps" role="tablist">{steps.map((s, i) => <button key={s} type="button" role="tab" aria-selected={step === i} className={step === i ? "on" : i < step ? "done" : ""} onClick={() => setStep(i)}><span>{i < step ? <Icon name="Check" size={13} strokeWidth={3} /> : i + 1}</span>{s}</button>)}</div>

      {step === 0 && <>
        <p className="ct-intro">Walk through each step below to see how a new round of financing affects every shareholder's ownership percentage and equity position.</p>
        {shs.map((s, i) => (
          <Box key={s.id} title={<span className="dl-h"><span className="dl-n">{i + 1}</span><input value={s.name} placeholder="Shareholder Name" aria-label="Shareholder name" onChange={e => upS(s.id, "name", e.target.value)} /></span>}
            right={<div className="ct-r"><span className="cx-fld sel ct-type"><select aria-label="Shareholder type" value={s.type} onChange={e => upS(s.id, "type", e.target.value)}>{CT_TYPES.map(t => <option key={t}>{t}</option>)}</select><Icon name="ChevronDown" size={14} /></span>{shs.length > 1 && <button type="button" className="cx-del" aria-label="Remove shareholder" onClick={() => setShs(p => p.filter(x => x.id !== s.id))}><Icon name="X" size={16} /></button>}</div>}>
            <Cells cols={4}>
              <NumIn id={"c" + s.id} label="Common Shares" ph="1,000,000" value={s.common} set={v => upS(s.id, "common", v)} />
              <NumIn id={"e" + s.id} label="Options Exercised" ph="0" value={s.ex} set={v => upS(s.id, "ex", v)} />
              <NumIn id={"o" + s.id} label="Options Outstanding" ph="0" value={s.out} set={v => upS(s.id, "out", v)} />
              <NumIn id={"p" + s.id} label="Preferred Shares" ph="0" value={s.pref} set={v => upS(s.id, "pref", v)} />
            </Cells>
            {parseNum(s.pref) > 0 && <div style={{ borderTop: "1px solid var(--border-subtle)" }}><TxtIn id={"ps" + s.id} label="Preferred Series" ph="Series Seed" value={s.series} set={v => upS(s.id, "series", v)} /></div>}
          </Box>
        ))}
        <button type="button" className="cx-btn-s" style={{ height: 52, justifyContent: "center", borderRadius: 14 }} onClick={() => setShs(p => [...p, ctNewSh("", "Employee")])}><Icon name="Plus" size={16} />Add Shareholder</button>
        <Box title="Option Pool"><Cells cols={2}><NumIn id="auth" label="Authorized Pool Shares" ph="1,000,000" value={auth} set={setAuth} /><NumIn id="unal" label="Unallocated Pool Shares" ph="500,000" value={unal} set={setUnal} /></Cells></Box>
        <Box title="Current Cap Table">
          {cur.t.totalFD === 0 ? <Empty>Enter shareholder details above to see the current cap table.</Empty> : (
            <ScrollX label="Current cap table"><table className="cx-tbl">
              <thead><tr>{["Name", "Type", "Common", "Options", "Total Common", "Preferred", "Fully Diluted", "FD %"].map(h => <th key={h}>{h}</th>)}</tr></thead>
              <tbody>
                {cur.rows.map((r, i) => <tr key={i}><td>{r.name}</td><td className="ct-t">{r.type}</td><td>{fmtN(r.c)}</td><td>{fmtN(r.e + r.o)}</td><td>{fmtN(r.tc)}</td><td>{fmtN(r.p)}</td><td>{fmtN(r.fd)}</td><td className="ct-pc">{fmtP(r.pct)}</td></tr>)}
                {cur.t.U > 0 && <tr><td style={{ fontStyle: "italic", color: "var(--text-muted)" }}>Unallocated Pool</td><td className="ct-t">Pool</td><td>-</td><td>-</td><td>-</td><td>-</td><td>{fmtN(cur.t.U)}</td><td className="ct-pc">{fmtP(cur.t.U / cur.t.totalFD)}</td></tr>}
                <tr className="tot"><td>Total</td><td></td><td>{fmtN(cur.t.c)}</td><td>{fmtN(cur.t.e + cur.t.o)}</td><td>{fmtN(cur.t.tc)}</td><td>{fmtN(cur.t.p)}</td><td>{fmtN(cur.t.totalFD)}</td><td className="ct-pc">100.00%</td></tr>
              </tbody>
            </table></ScrollX>
          )}
        </Box>
        <div className="ct-next"><Button variant="primary" size="lg" arrow onClick={() => setStep(1)}>Next: New Financing</Button></div>
      </>}

      {step === 1 && <>
        <Box title="Financing Terms">
          <Cells cols={3}>
            <NumIn id="pre" label="Pre-Money Valuation" pre="$" ph="10,000,000" value={pre} set={setPre} />
            <div className="cx-in">
              <span className="ct-lbr"><span className="cx-lb">Option Pool Expansion</span><button type="button" className="ct-sw" onClick={() => setUseT(!useT)}>{useT ? "Use Shares" : "Use Target %"}</button></span>
              {useT ? <span className="cx-fld"><input aria-label="Option pool target percent" inputMode="decimal" value={ptg} placeholder="15" onChange={e => setPtg(fmtDec(e.target.value))} /><i>%</i></span>
                : <span className="cx-fld"><input aria-label="Option pool expansion shares" inputMode="numeric" value={pex} placeholder="0" onChange={e => setPex(fmtInput(e.target.value))} /></span>}
            </div>
            <label className="cx-in" htmlFor="fdate"><span className="cx-lb">Financing Date</span><span className="cx-fld"><input id="fdate" type="date" value={date} onChange={e => setDate(e.target.value)} /></span></label>
          </Cells>
        </Box>
        <Box title="New Investors">
          {invs.map((v, i) => (
            <div key={v.id} className="ct-inv">
              <span className="dl-n">{i + 1}</span>
              <TxtIn id={"in" + v.id} label="Investor Name" ph="Investor Name" value={v.name} set={x => upI(v.id, "name", x)} />
              <NumIn id={"ia" + v.id} label="Investment Amount" pre="$" ph="2,000,000" value={v.amt} set={x => upI(v.id, "amt", x)} />
              {invs.length > 1 ? <button type="button" className="cx-del" aria-label="Remove investor" onClick={() => setInvs(p => p.filter(x => x.id !== v.id))}><Icon name="X" size={16} /></button> : <span style={{ width: 32 }}></span>}
            </div>
          ))}
          <div className="cx-pad" style={{ borderTop: "1px solid var(--border-subtle)" }}><button type="button" className="cx-btn-s" onClick={() => setInvs(p => [...p, ctNewInv("")])}><Icon name="Plus" size={15} />Add Investor</button></div>
        </Box>
        <div className="ct-next"><button type="button" className="cx-skip" onClick={() => setStep(0)}>Back</button><Button variant="primary" size="lg" arrow onClick={() => setStep(2)}>See Pro Forma</Button></div>
      </>}

      {step === 2 && <Box title="Pro Forma Cap Table" sub={date ? "Financing date: " + new Date(date).toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" }) : null} right={<PdfButton ready={!!pf} />}>
        {!pf ? <Empty>Complete the Current Cap Table and New Financing steps to generate the pro forma cap table.</Empty> : <>
          <Cells cols={4}><Res label="Pre-Money" value={fmtD(pf.P)} /><Res hi label="Post-Money" value={fmtD(pf.post)} /><Res hi label="Share Price" value={fmtD(pf.price)} /><Res label="Total Shares" value={fmtN(pf.tot)} /></Cells>
          <Bar parts={byType} />
          <ScrollX label="Pro forma cap table" style={{ borderTop: "1px solid var(--border-subtle)" }}><table className="cx-tbl">
            <thead><tr>{["Name", "Type", "Shares", "Ownership %", "Source"].map(h => <th key={h} style={h === "Source" || h === "Type" ? { textAlign: "left" } : undefined}>{h}</th>)}</tr></thead>
            <tbody>
              {pf.rows.map((r, i) => <tr key={i}><td>{r.name}</td><td className="ct-t">{r.type}</td><td>{fmtN(r.sh)}</td><td className="ct-pc">{fmtP(r.pct)}</td><td className="ct-t">{r.src}</td></tr>)}
              <tr className="tot"><td>Total</td><td></td><td>{fmtN(pf.tot)}</td><td className="ct-pc">100.00%</td><td></td></tr>
            </tbody>
          </table></ScrollX>
        </>}
      </Box>}
    </div>
  );
}

mountCalc(
  <CalcPage slug="cap-table-builder" title="Cap Table" hl="Builder"
    lead={<>A <strong>cap table</strong> (capitalization table) tracks every shareholder's equity stake in a company. Build your current cap table, model a new financing round, and instantly generate a <strong>pro forma cap table</strong> showing post-financing ownership.</>}
    how={<>
      <h2>Understanding Cap Tables</h2>
      <p>A <strong>capitalization table (cap table)</strong> is the definitive record of who owns what in a company. It lists every shareholder, the type and number of securities they hold, and their resulting ownership percentage. Maintaining an accurate cap table is critical for fundraising, hiring, and corporate governance.</p>
      <p><strong>Fully diluted shares</strong> represent the total number of shares that would be outstanding if all convertible securities were exercised, including stock options (both vested and unvested), warrants, and convertible notes. Investors typically negotiate their ownership on a fully diluted basis, because this represents the true economic reality of the company's equity.</p>
      <p><strong>Convertible securities</strong> such as SAFEs and convertible notes convert into equity at a future financing event. The conversion terms (valuation cap, discount rate) determine how many shares each instrument converts into. In a pro forma cap table, these conversions are modeled to show the post-financing ownership structure.</p>
      <p><strong>Pro forma mechanics:</strong> When a new round of financing closes, the company issues new preferred shares to investors based on the share price (pre-money valuation divided by fully diluted shares). Any option pool expansion is created from authorized but unissued shares, diluting all existing shareholders proportionally. The resulting pro forma cap table shows each party's new ownership percentage after accounting for all new shares.</p>
    </>}>
    <CapTableCalc />
  </CalcPage>
);
