const cnDays = (a, b) => { const d1 = new Date(a), d2 = new Date(b); if (isNaN(d1) || isNaN(d2)) return 0; return Math.max(0, Math.round((d2 - d1) / 864e5)); };
const cnInt = (p, r, d, c) => { const y = d / 365; return c === "annual" ? p * (Math.pow(1 + r, y) - 1) : c === "continuous" ? p * (Math.exp(r * y) - 1) : p * r * y; };
function DateIn({ id, label, value, set }) { return <label className="cx-in" htmlFor={id}><span className="cx-lb">{label}</span><span className="cx-fld"><input id={id} type="date" value={value} onChange={e => set(e.target.value)} /></span></label>; }

function ConvertibleNoteCalc() {
  const [pr, setPr] = React.useState("");
  const [ir, setIr] = React.useState("4");
  const [iss, setIss] = React.useState("");
  const [conv, setConv] = React.useState("");
  const [comp, setComp] = React.useState("simple");
  const [vc, setVc] = React.useState("");
  const [dc, setDc] = React.useState("20");
  const [pps, setPps] = React.useState("");
  const [fd, setFd] = React.useState("");
  const [nm, setNm] = React.useState("");
  const P = parseNum(pr), R = parseNum(ir) / 100, V = parseNum(vc), D = parseNum(dc), S = parseNum(pps), F = parseNum(fd), N = parseNum(nm);
  const ok = P > 0 && R >= 0 && iss !== "" && conv !== "" && cnDays(iss, conv) > 0 && V > 0 && D > 0 && S > 0 && F > 0;
  const r = React.useMemo(() => {
    if (!ok) return null;
    const days = cnDays(iss, conv), ai = cnInt(P, R, days, comp), debt = P + ai, cap = V / F, disc = S * (1 - D / 100);
    const [cp, m] = cap <= disc ? [cap, "Valuation Cap"] : [disc, "Discount"];
    const sh = debt / cp, nis = N > 0 ? N / S : 0;
    return { days, ai, debt, cap, disc, cp, m, sh, own: sh / (F + sh + nis) };
  }, [ok, P, R, iss, conv, comp, V, D, S, F, N]);
  return (
    <div className="cx-split">
      <Box title="Note Terms" sub="Enter your note terms, dates, and next round details below to see exactly how many shares the noteholder receives.">
        <Cells cols={2}><NumIn id="pr" label="Principal Amount" pre="$" ph="500,000" value={pr} set={setPr} /><NumIn id="ir" label="Annual Interest Rate (%)" suf="%" dec ph="4" value={ir} set={setIr} /></Cells>
        <Cells cols={3}><DateIn id="iss" label="Issuance Date" value={iss} set={setIss} /><DateIn id="conv" label="Conversion Date" value={conv} set={setConv} /><SelIn id="comp" label="Compounding" value={comp} set={setComp} options={[["simple", "Simple"], ["annual", "Annual"], ["continuous", "Continuous"]]} /></Cells>
        <div className="cx-bh" style={{ borderTop: "1px solid var(--border-subtle)" }}><div><h2>Conversion Terms</h2></div></div>
        <Cells cols={3}><NumIn id="vc" label="Valuation Cap" pre="$" ph="8,000,000" value={vc} set={setVc} /><NumIn id="dc" label="Discount (%)" suf="%" dec ph="20" value={dc} set={setDc} /><NumIn id="pps" label="Next Round PPS" pre="$" dec ph="1.50" value={pps} set={setPps} /></Cells>
        <Cells cols={2}><NumIn id="fd" label="Fully Diluted Shares" ph="10,000,000" value={fd} set={setFd} /><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={3}><Res label="Days Elapsed" value={fmtN(r.days)} /><Res hi label="Accrued Interest" value={fmtD(r.ai)} /><Res label="Outstanding Debt" value={fmtD(r.debt)} /></Cells>
            <Cells cols={3}><Res label="Cap Price" value={fmtD(r.cap)} /><Res label="Discount Price" value={fmtD(r.disc)} /><Res label="Round PPS" value={fmtD(S)} /></Cells>
            <Cells cols={2}><Res hi label={`Conversion Price (${r.m})`} value={fmtD(r.cp)} /><Res hi label="Shares Received" value={fmtN(r.sh)} /></Cells>
            <Res label="Post-Financing Ownership" value={fmtP(r.own)} />
          </>}
        </Box>
      </div>
    </div>
  );
}

mountCalc(
  <CalcPage slug="convertible-note-calculator" title="Convertible Note" hl="Calculator"
    lead={<><strong>Convertible notes</strong> are debt instruments that convert into equity at a future financing round. Unlike SAFEs, they accrue interest over time, which increases the total amount that converts into shares. This calculator computes accrued interest, conversion price, and resulting ownership.</>}
    how={<>
      <h2>How Convertible Note Conversion Works</h2>
      <p>A <strong>convertible note</strong> is a short-term debt instrument that converts into equity upon a qualifying financing event (typically a priced round). Unlike a SAFE, a convertible note is actual debt: it has a principal amount, an interest rate, and a maturity date.</p>
      <p><strong>Interest accrual</strong> is the key difference between convertible notes and SAFEs. The interest accrues from the issuance date to the conversion date, and the total outstanding debt (principal plus accrued interest) is what converts into equity. Most notes use simple interest, though some specify annual compounding or continuous compounding.</p>
      <p>Like SAFEs, convertible notes typically include a <strong>valuation cap</strong> and/or a <strong>discount</strong>. The cap sets a maximum valuation for conversion, while the discount gives the noteholder a percentage reduction off the round price. The noteholder gets whichever method produces a lower conversion price (and therefore more shares).</p>
      <p>The <strong>cap price</strong> is calculated by dividing the valuation cap by the fully diluted share count. The <strong>discount price</strong> is the round's price per share multiplied by (1 minus the discount percentage). The lower of these two becomes the conversion price, and the total outstanding debt is divided by this price to determine shares received.</p>
      <p>Convertible notes were the standard pre-seed and seed instrument before SAFEs became popular. They are still commonly used, especially when founders want a maturity date to create urgency for a future round, or when investors prefer the legal protections of a debt instrument.</p>
    </>}>
    <ConvertibleNoteCalc />
  </CalcPage>
);
