function SafeCalc() {
  const [type, setType] = React.useState("cap-only");
  const [amt, setAmt] = React.useState("");
  const [vcap, setVcap] = React.useState("");
  const [disc, setDisc] = React.useState("");
  const [ccap, setCcap] = React.useState("");
  const [pps, setPps] = React.useState("");
  const [nm, setNm] = React.useState("");
  const [qa, setQa] = React.useState("");
  const [qc, setQc] = React.useState("");
  const A = parseNum(amt), V = parseNum(vcap), D = parseNum(disc), C = parseNum(ccap), P = parseNum(pps), N = parseNum(nm);
  const showCap = type === "cap-only" || type === "cap-discount", showDisc = type === "discount-only" || type === "cap-discount";
  const ok = !(A <= 0 || C <= 0 || P <= 0) && !(showCap && V <= 0) && !(showDisc && D <= 0);
  const r = React.useMemo(() => {
    if (!ok) return null;
    if (type === "mfn") {
      const shares = A / P, tot = C + shares + (N > 0 ? N / P : 0);
      return { capPrice: null, discountPrice: null, conv: P, method: "MFN (Round PPS)", shares, pre: shares / (C + shares), post: shares / tot };
    }
    const capPrice = showCap ? V / C : null, discountPrice = showDisc ? P * (1 - D / 100) : null;
    let conv, method;
    if (capPrice !== null && discountPrice !== null) { if (capPrice <= discountPrice) { conv = capPrice; method = "Valuation Cap"; } else { conv = discountPrice; method = "Discount"; } }
    else if (capPrice !== null) { conv = Math.min(capPrice, P); method = capPrice < P ? "Valuation Cap" : "Round PPS"; }
    else { conv = discountPrice; method = "Discount"; }
    const shares = A / conv, nis = N > 0 ? N / P : 0, tot = C + shares + nis;
    return { capPrice, discountPrice, conv, method, shares, pre: shares / (C + shares), post: shares / tot };
  }, [ok, type, A, V, D, C, P, N, showCap, showDisc]);
  const qA = parseNum(qa), qC = parseNum(qc), q = qA > 0 && qC > 0 ? qA / qC : null;
  const priceCells = r ? [r.capPrice !== null && ["Cap Price", fmtD(r.capPrice)], r.discountPrice !== null && ["Discount Price", fmtD(r.discountPrice)]].filter(Boolean) : [];
  return (
    <div className="cx-stack">
      <div className="cx-split">
        <Box title="Inputs" sub="Choose your SAFE type, then enter the terms and next round details.">
          <div className="cx-pad" style={{ borderBottom: "1px solid var(--border-subtle)" }}><span className="cx-lb" style={{ display: "block", marginBottom: 10 }}>SAFE Type</span><Seg value={type} set={setType} options={[["cap-only", "Valuation Cap Only"], ["discount-only", "Discount Only"], ["cap-discount", "Cap + Discount"], ["mfn", "MFN"]]} /></div>
          <Cells cols={2}>
            <NumIn id="amt" label="Purchase Amount" pre="$" ph="500,000" value={amt} set={setAmt} />
            {showCap ? <NumIn id="vcap" label="Valuation Cap" pre="$" ph="10,000,000" value={vcap} set={setVcap} /> : showDisc ? <NumIn id="disc" label="Discount (%)" ph="20" dec suf="%" value={disc} set={setDisc} /> : <div></div>}
          </Cells>
          {showCap && showDisc && <Cells cols={2}><NumIn id="disc2" label="Discount (%)" ph="20" dec suf="%" value={disc} set={setDisc} /><div></div></Cells>}
          <Cells cols={3}>
            <NumIn id="ccap" label="Company Capitalization" ph="10,000,000" value={ccap} set={setCcap} />
            <NumIn id="pps" label="Next Round PPS" pre="$" ph="1.50" dec value={pps} set={setPps} />
            <NumIn id="nm" label="New Money Raised" pre="$" ph="3,000,000" value={nm} set={setNm} />
          </Cells>
        </Box>
        <div className="cx-stick">
          <Box title="Results" right={<PdfButton ready={ok} />}>
            {!r ? <Empty>Enter all required values above to see the calculated results.</Empty> : <>
              <Cells cols={priceCells.length + 1}>{priceCells.map(([l, v]) => <Res key={l} label={l} value={v} />)}<Res hi label="Conversion Price" value={fmtD(r.conv)} /></Cells>
              <Cells cols={2}><Res label="Conversion Method" value={r.method} /><Res hi label="Shares Received" value={fmtN(r.shares)} /></Cells>
              <Cells cols={2}><Res label="Pre-Dilution Ownership" value={fmtP(r.pre)} /><Res label="Post-Financing Ownership" value={fmtP(r.post)} /></Cells>
            </>}
          </Box>
        </div>
      </div>
      <Box title="Quick Post-Money SAFE Ownership" sub="For post-money SAFEs, ownership is simply Purchase Amount / Post-Money Valuation Cap.">
        <Cells cols={3}>
          <NumIn id="qa" label="Purchase Amount" pre="$" ph="500,000" value={qa} set={setQa} />
          <NumIn id="qc" label="Post-Money Valuation Cap" pre="$" ph="10,000,000" value={qc} set={setQc} />
          {q !== null ? <Res hi label="Investor Ownership" value={fmtP(q)} /> : <div className="cx-res"><span className="cx-lb">Investor Ownership</span><small style={{ fontSize: 13.5 }}>Enter both values to see investor ownership.</small></div>}
        </Cells>
      </Box>
    </div>
  );
}

mountCalc(
  <CalcPage slug="safe-conversion-calculator" title="SAFE" hl="Conversion Calculator"
    lead={<><strong>SAFEs (Simple Agreement for Future Equity)</strong> convert into equity at a future priced round. The conversion price depends on the valuation cap, discount rate, or both. This calculator shows exactly how many shares a SAFE holder receives and what ownership percentage that represents.</>}
    how={<>
      <h2>How SAFE Conversion Works</h2>
      <p>A <strong>SAFE (Simple Agreement for Future Equity)</strong> is an investment instrument created by Y Combinator in 2013 that gives investors the right to receive equity in a future priced round. Unlike convertible notes, SAFEs have no interest rate, maturity date, or repayment obligation.</p>
      <p>The <strong>valuation cap</strong> sets a maximum company valuation at which the SAFE converts. If the company raises at a higher valuation, the SAFE holder converts at the cap price, effectively getting a discount. The <strong>cap price</strong> is calculated by dividing the valuation cap by the company's fully diluted capitalization.</p>
      <p>The <strong>discount rate</strong> gives the SAFE holder a percentage discount off the price per share paid by new investors. For example, a 20% discount means the SAFE converts at 80% of the round's price per share.</p>
      <p>When a SAFE has both a cap and a discount, the investor gets the <strong>better of the two</strong> (whichever results in a lower conversion price and therefore more shares). This is a key investor-friendly feature of the standard SAFE.</p>
      <p>Since 2018, Y Combinator has standardized on the <strong>post-money SAFE</strong>, where the valuation cap is post-money (includes the SAFE investment itself). This makes ownership calculation straightforward: the investor's ownership is simply their purchase amount divided by the post-money valuation cap. Pre-money SAFEs, which were used before 2018, define the cap as pre-money, making the actual ownership dependent on how much total money is raised in the round.</p>
      <p>An <strong>MFN (Most Favored Nation)</strong> SAFE has no cap or discount but includes a clause that allows the holder to adopt the terms of any subsequent SAFE issued before the equity financing. This protects early investors from being diluted by later SAFEs with better terms.</p>
    </>}>
    <SafeCalc />
  </CalcPage>
);
