const RF_M = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const rfCat = () => ({ name: "", u: "", p: "", ug: "", pg: "" });

function RevenueCalc() {
  const [cats, setCats] = React.useState([rfCat()]);
  const [sm, setSm] = React.useState("1");
  const [syr, setSyr] = React.useState("2026");
  const sy = parseNum(syr), smn = Number(sm);
  const up = (i, k, v) => setCats(p => p.map((c, j) => j === i ? { ...c, [k]: v } : c));
  const ok = cats.some(c => parseNum(c.u) > 0 && parseNum(c.p) > 0);
  const r = React.useMemo(() => {
    if (!ok) return null;
    const pc = cats.map(c => ({ name: c.name || "Untitled", u: parseNum(c.u), p: parseNum(c.p), ug: parseNum(c.ug) / 100, pg: parseNum(c.pg) / 100 }));
    const md = [];
    for (let i = 0; i < 12; i++) {
      const mi = (smn - 1 + i) % 12, yo = Math.floor((smn - 1 + i) / 12);
      const cr = pc.map(c => c.u * Math.pow(1 + c.ug, i) * c.p * Math.pow(1 + c.pg, i));
      md.push({ label: `${RF_M[mi]} ${sy + yo}`, tot: cr.reduce((a, b) => a + b, 0), cr });
    }
    const ann = md.reduce((a, m) => a + m.tot, 0), m1 = md[0].tot, m12 = md[11].tot;
    return { ann, avg: ann / 12, m1, m12, mom: m1 > 0 ? Math.pow(m12 / m1, 1 / 11) - 1 : 0, md, names: pc.map(c => c.name) };
  }, [ok, cats, smn, sy]);
  const d0 = n => fmtD(n, 0);
  const max = r ? Math.max(...r.md.map(m => m.tot), 1) : 1;
  return (
    <div className="cx-stack">
      <div className="cx-split">
        <Box title="Inputs" sub="Define your product categories below, set growth assumptions, and instantly see your projected monthly and annual revenue.">
          <Cells cols={2}>
            <SelIn id="sm" label="Start Month" value={sm} set={setSm} options={RF_M.map((m, i) => [String(i + 1), m])} />
            <label className="cx-in" htmlFor="syr"><span className="cx-lb">Start Year</span><span className="cx-fld"><input id="syr" inputMode="numeric" value={syr} placeholder="2026" onChange={e => setSyr(e.target.value.replace(/[^0-9]/g, ""))} /></span></label>
          </Cells>
          {cats.map((c, i) => (
            <div key={i} className="tm-seg">
              <div className="cx-bh"><span className="dl-h"><span className="dl-n">{i + 1}</span><input value={c.name} placeholder="e.g. SaaS Subscriptions" aria-label="Category name" onChange={e => up(i, "name", e.target.value)} /></span>{i > 0 && <button type="button" className="cx-del" aria-label="Remove category" onClick={() => setCats(p => p.filter((_, j) => j !== i))}><Icon name="X" size={16} /></button>}</div>
              <Cells cols={2}><NumIn id={"u" + i} label="Starting Units" ph="100" value={c.u} set={v => up(i, "u", v)} /><NumIn id={"p" + i} label="Price per Unit" pre="$" ph="50" value={c.p} set={v => up(i, "p", v)} /></Cells>
              <Cells cols={2}><NumIn id={"ug" + i} label="Monthly Unit Growth (%)" suf="%" dec ph="10" value={c.ug} set={v => up(i, "ug", v)} /><NumIn id={"pg" + i} label="Monthly Price Growth (%)" suf="%" dec ph="0" value={c.pg} set={v => up(i, "pg", v)} /></Cells>
            </div>
          ))}
          {cats.length < 5 && <div className="cx-pad" style={{ borderTop: "1px solid var(--border-subtle)" }}><button type="button" className="cx-btn-s" onClick={() => setCats(p => [...p, rfCat()])}><Icon name="Plus" size={15} />Add Category</button></div>}
        </Box>
        <div className="cx-stick">
          <Box title="Results" right={<PdfButton ready={!!r} />}>
            {!r ? <Empty>Enter at least one category with starting units and price per unit to see the projected results.</Empty> : <>
              <Cells cols={2}><Res hi label="Annual Revenue (12-Month Total)" value={d0(r.ann)} /><Res label="Average Monthly Revenue" value={d0(r.avg)} /></Cells>
              <Cells cols={3}><Res label="Month 1 Revenue" value={d0(r.m1)} /><Res label="Month 12 Revenue" value={d0(r.m12)} /><Res hi label="Implied MoM Growth" value={fmtP(r.mom)} /></Cells>
              <div className="rw-chart">
                <span className="cx-lb">Monthly revenue</span>
                <div className="rw-bars">{r.md.map((m, i) => <div key={i} title={m.label + ": " + d0(m.tot)}><span className="rf-stk" style={{ height: Math.max(2, m.tot / max * 100) + "%" }}>{m.cr.map((v, ci) => <i key={ci} style={{ flexGrow: v, background: CX_COL[ci] }}></i>)}</span><span>{m.label.slice(0, 3)}</span></div>)}</div>
                {r.names.length > 1 && <div className="cx-leg">{r.names.map((n, ci) => <span key={ci}><i style={{ background: CX_COL[ci] }}></i>{n}</span>)}</div>}
              </div>
            </>}
          </Box>
        </div>
      </div>
      {r && <Box title="12-Month Projection">
        <ScrollX label="12-month revenue projection table"><table className="cx-tbl">
          <thead><tr><th>Month</th>{r.names.length > 1 && r.names.map((n, ci) => <th key={ci}>{n}</th>)}<th>Revenue</th></tr></thead>
          <tbody>
            {r.md.map((m, i) => <tr key={i}><td style={{ fontFamily: "var(--font-mono)" }}>{m.label}</td>{r.names.length > 1 && m.cr.map((v, ci) => <td key={ci} style={{ color: "var(--text-secondary)" }}>{d0(v)}</td>)}<td style={{ fontWeight: 700 }}>{d0(m.tot)}</td></tr>)}
            <tr className="tot"><td>Total</td>{r.names.length > 1 && r.names.map((_, ci) => <td key={ci}>{d0(r.md.reduce((a, m) => a + m.cr[ci], 0))}</td>)}<td className="ct-pc">{d0(r.ann)}</td></tr>
          </tbody>
        </table></ScrollX>
      </Box>}
    </div>
  );
}

mountCalc(
  <CalcPage slug="revenue-forecast" title="12-Month Revenue" hl="Forecast Builder"
    lead={<><strong>Revenue projections</strong> are the backbone of every fundraising deck and financial model. This calculator lets you build a bottom-up 12-month revenue forecast with multiple product categories, compound growth rates, and investor-ready output.</>}
    how={<>
      <h2>Building a Revenue Forecast for Your Startup</h2>
      <p><strong>A bottom-up revenue forecast</strong> is one of the most critical components of any startup financial model. Unlike top-down estimates that start with market size and assume a capture rate, bottom-up models build revenue from fundamental unit economics: how many units you sell, at what price, and how those numbers grow over time.</p>
      <p>This calculator uses a <strong>compound growth model</strong> for each product category. For each month, units are calculated as starting units multiplied by (1 + monthly growth rate) raised to the power of the month index. The same formula applies to price. Revenue for each month equals units multiplied by price, and the total forecast sums all 12 months across all categories.</p>
      <p><strong>Why multiple categories matter:</strong> Most startups have more than one revenue stream. A SaaS company might have subscription revenue, onboarding fees, and usage-based charges. An e-commerce business might sell products across different price tiers. By modeling each category independently, you capture how different parts of your business grow at different rates, giving investors a more credible and granular view.</p>
      <p><strong>The implied month-over-month growth rate</strong> shown in the results is the geometric mean growth rate that would produce the same ratio of Month 12 to Month 1 revenue. This is the number investors focus on most — early-stage startups typically need to demonstrate 15-20% MoM growth to be considered for venture funding. A 10% monthly growth rate compounds to roughly 3x annual growth.</p>
      <p><strong>Tips for a credible forecast:</strong> Ground your starting units in real data — current customers, signed contracts, or pipeline with conversion rates applied. Use growth rates that reflect historical trends or comparable companies, not aspirational targets. Separate price increases from volume growth so investors can see which lever drives your revenue expansion. A well-built 12-month forecast tells investors you understand your business mechanics at a granular level.</p>
    </>}>
    <RevenueCalc />
  </CalcPage>
);
