const SV_DISC = 0.28;
const SV_COH = [[0, 1e6, 1], [1e6, 3e6, .7], [3e6, 5e6, .5], [5e6, 1e7, .4], [1e7, 2e7, .3], [2e7, 5e7, .25], [5e7, Infinity, .2]];
const svMed = a => { const c = SV_COH.find(x => a >= x[0] && a < x[1]); return c ? c[2] : .2; };
const svGrowth = (g, m) => Math.max(-3, Math.min(5, (g - m) * 10));
const svTam = t => t === "small" ? -.5 : t === "large" ? .3 : 0;
const svNrr = n => n > 105 ? Math.min(2, (n - 105) * .1) : n < 85 ? Math.max(-2, -((85 - n) * .1)) : 0;
const svGm = m => Math.max(-1.5, Math.min(1.5, ((m - 74) / 10) * .5));
const svCac = c => c > 1.5 ? .5 : c >= 1 ? .3 : c < .5 ? -.5 : 0;
const fmtX = n => n.toFixed(1) + "x";

function SaasCalc() {
  const [pi, setPi] = React.useState("6.0");
  const [ca, setCa] = React.useState("");
  const [pa, setPa] = React.useState("");
  const [nr, setNr] = React.useState("");
  const [gm, setGm] = React.useState("");
  const [cr, setCr] = React.useState("");
  const [tam, setTam] = React.useState("average");
  const PI = parseNum(pi), CA = parseNum(ca), PA = parseNum(pa), NR = parseNum(nr), GM = parseNum(gm), CR = parseNum(cr);
  const ok = PI > 0 && CA > 0 && PA > 0 && NR > 0 && GM > 0 && CR > 0;
  const r = React.useMemo(() => {
    if (!ok) return null;
    const priv = PI * (1 - SV_DISC), g = (CA - PA) / PA, med = svMed(CA);
    const adj = [svGrowth(g, med), svTam(tam), svNrr(NR), svGm(GM), svCac(CR)];
    const fin = Math.max(0, priv + adj.reduce((a, b) => a + b, 0));
    const names = ["3. ARR Growth Adjustment", "4. TAM Assessment", "5. Net Retention", "6. Gross Margin", "7. CAC Efficiency"];
    let run = priv;
    const steps = [{ name: "1. Public SaaS Index Multiple", adj: PI, run: PI, base: true }, { name: "2. Private Company Discount (28%)", adj: -(PI * SV_DISC), run: priv }];
    adj.forEach((a, i) => { run += a; steps.push({ name: names[i], adj: a, run: i === 4 ? fin : run }); });
    return { steps, fin, val: fin * CA, g, med };
  }, [ok, PI, CA, PA, NR, GM, CR, tam]);
  const maxRun = r ? Math.max(...r.steps.map(s => s.run), 1) : 1;
  return (
    <div className="cx-split">
      <Box title="Inputs" sub="Enter your company metrics below to see a step-by-step waterfall of how each factor impacts your revenue multiple and estimated valuation.">
        <Cells cols={2}><NumIn id="pi" label="Public SaaS Index Multiple" suf="x" dec ph="6.0" value={pi} set={setPi} /><SelIn id="tam" label="TAM Assessment" value={tam} set={setTam} options={[["small", "Small"], ["average", "Average"], ["large", "Large"]]} /></Cells>
        <Cells cols={2}><NumIn id="ca" label="Current ARR" pre="$" ph="5,000,000" value={ca} set={setCa} /><NumIn id="pa" label="Prior Year ARR" pre="$" ph="3,000,000" value={pa} set={setPa} /></Cells>
        <Cells cols={3}><NumIn id="nr" label="Net Retention Rate (%)" suf="%" dec ph="110" value={nr} set={setNr} /><NumIn id="gm" label="Gross Margin (%)" suf="%" dec ph="75" value={gm} set={setGm} /><NumIn id="cr" label="CAC Ratio" dec ph="1.2" value={cr} set={setCr} /></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={2}><Res hi label="Final Revenue Multiple" value={fmtX(r.fin)} /><Res hi label="Estimated Valuation" value={fmtD(r.val, 0)} /></Cells>
            <div className="sv-wf">
              {r.steps.map((s, i) => {
                const c = s.base ? "" : s.adj > 0 ? "up" : s.adj < 0 ? "dn" : "z";
                return (
                  <div key={i} className="sv-row">
                    <span className="n">{s.name}</span>
                    <span className={"a " + c}>{s.base ? fmtX(s.adj) : s.adj > 0 ? "+" + s.adj.toFixed(1) : s.adj === 0 ? "0.0" : s.adj.toFixed(1)}</span>
                    <span className="tr"><i style={{ width: Math.max(0, s.run) / maxRun * 100 + "%" }} className={c}></i></span>
                    <b>{fmtX(s.run)}</b>
                  </div>
                );
              })}
            </div>
            <Cells cols={2}><Res label="ARR Growth Rate" value={fmtP(r.g, 1)} /><Res label="Cohort Median Growth" value={fmtP(r.med, 1)} /></Cells>
          </>}
        </Box>
      </div>
    </div>
  );
}

mountCalc(
  <CalcPage slug="saas-valuation-calculator" title="SaaS Valuation" hl="Calculator"
    lead={<>Estimate your SaaS company's valuation using the <strong>SaaS Capital 7-step method</strong>. Start with public market multiples, apply a private company discount, then adjust for your company's specific growth, retention, margins, and efficiency metrics.</>}
    how={<>
      <h2>Understanding the SaaS Capital 7-Step Valuation Method</h2>
      <p>The <strong>SaaS Capital 7-step method</strong> is a widely used framework for estimating the valuation of private SaaS companies. It starts with the public SaaS market multiple and adjusts it based on company-specific factors to arrive at a fair revenue multiple for a private company.</p>
      <p><strong>Step 1: Public SaaS Index Multiple.</strong> This is the current median revenue multiple of publicly traded SaaS companies. It serves as the market baseline and fluctuates with public market conditions. You can find the current index value from sources like the BVP Nasdaq Emerging Cloud Index or SaaS Capital's own index.</p>
      <p><strong>Step 2: Private Company Discount.</strong> Private companies trade at a discount to public peers due to illiquidity, smaller scale, and higher risk. The standard discount is 28%, meaning a private company's baseline multiple is roughly 72% of the public index.</p>
      <p><strong>Step 3: Growth Rate Adjustment.</strong> Growth is the single most important driver of SaaS valuations. Your ARR growth rate is compared against the median growth rate for companies in your ARR cohort. Growing faster than the median earns a premium; growing slower results in a discount. This adjustment can range from -3.0x to +5.0x.</p>
      <p><strong>Step 4: TAM Assessment.</strong> Companies operating in large total addressable markets receive a modest premium (+0.3x) because they have more room to grow. Small TAMs result in a -0.5x discount. Average TAMs have no adjustment.</p>
      <p><strong>Step 5: Net Revenue Retention.</strong> Net retention above 105% indicates strong expansion revenue and low churn, earning a premium of up to +2.0x. Retention below 85% signals significant churn problems, resulting in a discount of up to -2.0x. Retention between 85-105% is considered neutral.</p>
      <p><strong>Step 6: Gross Margin.</strong> The SaaS industry median gross margin is approximately 74%. Companies with higher margins are more capital-efficient and command higher multiples. The adjustment is +/-0.5x per 10 percentage points above or below the median, capped at +/-1.5x.</p>
      <p><strong>Step 7: CAC Efficiency.</strong> The CAC ratio (new ARR divided by sales and marketing spend) measures go-to-market efficiency. A ratio above 1.5x earns +0.5x, between 1.0-1.5x earns +0.3x, and below 0.5x results in a -0.5x discount. Efficient customer acquisition is rewarded.</p>
      <p><strong>How to use this calculator:</strong> Enter the current public SaaS index multiple (check BVP Cloud Index or SaaS Capital for the latest), your company's current and prior year ARR, net retention rate, gross margin percentage, CAC ratio, and TAM assessment. The calculator will walk you through each adjustment step and produce an estimated valuation based on your final revenue multiple applied to current ARR.</p>
    </>}>
    <SaasCalc />
  </CalcPage>
);
