const tamSeg = name => ({ name, bc: "", cg: "", acv: "", ag: "", sam: "", som: "" });
const fmtShort = n => n >= 1e9 ? "$" + (n / 1e9).toFixed(1) + "B" : n >= 1e6 ? "$" + (n / 1e6).toFixed(1) + "M" : n >= 1e3 ? "$" + (n / 1e3).toFixed(0) + "K" : "$" + n.toFixed(0);

function TamCalc() {
  const cy = new Date().getFullYear();
  const [segs, setSegs] = React.useState([tamSeg("Segment 1")]);
  const [pyr, setPyr] = React.useState("6");
  const [syr, setSyr] = React.useState(String(cy));
  const py = (n => Number.isFinite(n) && n >= 1 && n <= 20 ? n : 0)(parseInt(pyr, 10));
  const sy = (n => Number.isFinite(n) && n >= 2000 && n <= 2100 ? n : 0)(parseInt(syr, 10));
  const up = (i, k, v) => setSegs(p => p.map((s, j) => j === i ? { ...s, [k]: v } : s));
  const ok = py >= 1 && sy >= 2000 && segs.every(s => { const v = k => parseNum(s[k]); return v("bc") > 0 && v("cg") >= 0 && v("cg") <= 100 && v("acv") > 0 && v("ag") >= 0 && v("ag") <= 100 && v("sam") > 0 && v("sam") <= 100 && v("som") > 0 && v("som") <= 100; });
  const r = React.useMemo(() => {
    if (!ok) return null;
    const yrs = [];
    for (let i = 0; i < py; i++) {
      let T = 0, S = 0, O = 0;
      for (const s of segs) {
        const tam = parseNum(s.bc) * Math.pow(1 + parseNum(s.cg) / 100, i) * parseNum(s.acv) * Math.pow(1 + parseNum(s.ag) / 100, i);
        const sam = tam * parseNum(s.sam) / 100;
        T += tam; S += sam; O += sam * parseNum(s.som) / 100;
      }
      yrs.push({ year: sy + i, tam: T, sam: S, som: O });
    }
    const f = yrs[0], l = yrs[yrs.length - 1], n = yrs.length, cagr = (a, b) => a <= 0 || n <= 1 ? 0 : Math.pow(b / a, 1 / (n - 1)) - 1;
    return { yrs, f, l, tc: cagr(f.tam, l.tam), sc: cagr(f.sam, l.sam), oc: cagr(f.som, l.som) };
  }, [ok, segs, py, sy]);
  return (
    <div className="cx-stack">
      <div className="cx-split">
        <Box title="Inputs" sub="Define your customer segments below with base customer counts, average contract values, and growth rates to project your Total Addressable Market, Serviceable Addressable Market, and Serviceable Obtainable Market over time.">
          <Cells cols={2}>
            <label className="cx-in" htmlFor="pyr"><span className="cx-lb">Projection Years</span><span className="cx-fld"><input id="pyr" inputMode="numeric" value={pyr} placeholder="6" onChange={e => setPyr(e.target.value.replace(/[^0-9]/g, ""))} /></span></label>
            <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={String(cy)} onChange={e => setSyr(e.target.value.replace(/[^0-9]/g, ""))} /></span></label>
          </Cells>
          {segs.map((s, i) => (
            <div key={i} className="tm-seg">
              <div className="cx-bh"><span className="dl-h"><span className="dl-n">{i + 1}</span><input value={s.name} placeholder="e.g. Enterprise" aria-label="Segment name" onChange={e => up(i, "name", e.target.value)} /></span>{segs.length > 1 && <button type="button" className="cx-del" aria-label="Remove segment" onClick={() => setSegs(p => p.filter((_, j) => j !== i))}><Icon name="X" size={16} /></button>}</div>
              <Cells cols={2}><NumIn id={"bc" + i} label="Base Customers" ph="50,000" value={s.bc} set={v => up(i, "bc", v)} /><NumIn id={"acv" + i} label="Base ACV (Avg Contract Value)" pre="$" ph="1,200" value={s.acv} set={v => up(i, "acv", v)} /></Cells>
              <Cells cols={2}><NumIn id={"cg" + i} label="Customer Growth Rate (%)" suf="%" dec ph="10" value={s.cg} set={v => up(i, "cg", v)} /><NumIn id={"ag" + i} label="ACV Growth Rate (%)" suf="%" dec ph="5" value={s.ag} set={v => up(i, "ag", v)} /></Cells>
              <Cells cols={2}><NumIn id={"sam" + i} label="SAM % of TAM" suf="%" dec ph="40" value={s.sam} set={v => up(i, "sam", v)} /><NumIn id={"som" + i} label="SOM % of SAM" suf="%" dec ph="10" value={s.som} set={v => up(i, "som", v)} /></Cells>
            </div>
          ))}
          {segs.length < 4 && <div className="cx-pad" style={{ borderTop: "1px solid var(--border-subtle)" }}><button type="button" className="cx-btn-s" onClick={() => setSegs(p => [...p, tamSeg(`Segment ${p.length + 1}`)])}><Icon name="Plus" size={15} />Add Segment</button></div>}
        </Box>
        <div className="cx-stick">
          <Box title="Results" right={<PdfButton ready={!!r} />}>
            {!r ? <Empty>Enter all required values above to see the calculated results.</Empty> : <>
              <div className="tm-rings" aria-hidden="true">
                <div className="t"><div className="s" style={{ width: Math.max(18, Math.sqrt(r.f.sam / r.f.tam) * 100) + "%" }}><div className="o" style={{ width: Math.max(28, Math.sqrt(r.f.som / r.f.sam) * 100) + "%" }}></div></div></div>
                <ul><li><i className="t"></i>TAM<b>{fmtShort(r.f.tam)}</b></li><li><i className="s"></i>SAM<b>{fmtShort(r.f.sam)}</b></li><li><i className="o"></i>SOM<b>{fmtShort(r.f.som)}</b></li></ul>
              </div>
              <Cells cols={3}><Res label={`Year 1 TAM (${r.f.year})`} value={fmtD(r.f.tam)} /><Res label="Year 1 SAM" value={fmtD(r.f.sam)} /><Res hi label="Year 1 SOM" value={fmtD(r.f.som)} /></Cells>
              <Cells cols={3}><Res label={`Year ${py} TAM (${r.l.year})`} value={fmtD(r.l.tam)} /><Res label={`Year ${py} SAM`} value={fmtD(r.l.sam)} /><Res hi label={`Year ${py} SOM`} value={fmtD(r.l.som)} /></Cells>
              <Cells cols={3}><Res label="TAM CAGR" value={fmtP(r.tc)} /><Res label="SAM CAGR" value={fmtP(r.sc)} /><Res hi label="SOM CAGR" value={fmtP(r.oc)} /></Cells>
            </>}
          </Box>
        </div>
      </div>
      {r && <Box title="Year-by-Year Projections">
        <ScrollX label="Year-by-year projections table"><table className="cx-tbl">
          <thead><tr>{["Year", "TAM", "SAM", "SOM"].map(h => <th key={h}>{h}</th>)}</tr></thead>
          <tbody>{r.yrs.map(y => <tr key={y.year}><td style={{ fontFamily: "var(--font-mono)" }}>{y.year}</td><td>{fmtD(y.tam)}</td><td>{fmtD(y.sam)}</td><td className="ct-pc">{fmtD(y.som)}</td></tr>)}</tbody>
        </table></ScrollX>
      </Box>}
    </div>
  );
}

mountCalc(
  <CalcPage slug="tam-calculator" title="TAM SAM SOM" hl="Calculator"
    lead={<><strong>TAM, SAM, and SOM</strong> are the three pillars of market sizing that every investor expects to see in your pitch deck. This calculator helps you build a bottom-up market model with multi-segment projections, growth assumptions, and automatic CAGR calculations.</>}
    how={<>
      <h2>Understanding TAM, SAM, and SOM</h2>
      <p><strong>TAM (Total Addressable Market)</strong> represents the total revenue opportunity available if you captured 100% of the market. It is the broadest measure of market size and answers the question: "How big is the universe of potential customers for this product or service?" TAM is calculated by multiplying the total number of potential customers by the average annual contract value (ACV) or revenue per customer.</p>
      <p><strong>SAM (Serviceable Addressable Market)</strong> is the portion of TAM that your product or business model can realistically serve. It accounts for geographic, regulatory, or technical limitations that narrow your addressable audience. For example, if your SaaS product only works in English-speaking markets, your SAM would exclude non-English-speaking regions. SAM is typically expressed as a percentage of TAM.</p>
      <p><strong>SOM (Serviceable Obtainable Market)</strong> is the share of SAM that you can realistically capture in the near term given your current resources, competitive landscape, and go-to-market strategy. SOM is the number investors care about most because it represents your actual revenue potential. It is expressed as a percentage of SAM and should be grounded in realistic assumptions about market penetration rates.</p>
      <p><strong>Bottom-Up vs. Top-Down Approach:</strong> This calculator uses a bottom-up methodology, which investors generally prefer. Instead of starting with a large industry report number and slicing it down (top-down), you start with specific customer segments, realistic customer counts, and actual pricing. This produces more credible estimates because each assumption can be individually validated and defended.</p>
      <p><strong>Multi-Segment Analysis:</strong> Most businesses serve multiple customer segments with different characteristics. An enterprise segment might have fewer customers but higher ACVs, while an SMB segment might have many more customers at lower price points. By modeling each segment independently with its own growth rates, you get a more accurate and nuanced picture of your total market opportunity.</p>
      <p><strong>CAGR (Compound Annual Growth Rate)</strong> measures the average annual growth rate of your market projections over the forecast period. Investors use CAGR to quickly assess the growth trajectory. A TAM CAGR of 15-25% is typical for attractive venture-backed markets. The CAGR shown here reflects the combined effect of customer base growth and ACV growth across all segments.</p>
      <p><strong>Tips for Your Pitch Deck:</strong> Present all three numbers (TAM, SAM, SOM) together. Use TAM to show the total opportunity, SAM to demonstrate you understand your addressable scope, and SOM to prove you have a realistic near-term revenue plan. Back every assumption with data sources. Investors will challenge your numbers — being able to walk through each input builds credibility.</p>
    </>}>
    <TamCalc />
  </CalcPage>
);
