// Shared calculator kit: formatting, inputs, result cells, page shell, PDF export.
const CALCS = [
  { slug: "valuation-calculator", title: "Valuation Calculator", icon: "Calculator", desc: "Calculate pre-money and post-money valuations, share prices, and ownership percentages for your funding round." },
  { slug: "safe-conversion-calculator", title: "SAFE Conversion Calculator", icon: "FileText", desc: "Model YC Post-Money SAFE conversions with valuation caps, discounts, and MFN terms." },
  { slug: "dilution-simulator", title: "Founder Dilution Simulator", icon: "TrendingDown", desc: "Simulate cumulative founder dilution across multiple funding rounds with option pool expansion." },
  { slug: "cap-table-builder", title: "Cap Table Builder", icon: "Table2", desc: "Build and manage your cap table with shareholders, convertible securities, and pro forma views." },
  { slug: "option-pool-calculator", title: "Option Pool Impact Calculator", icon: "Layers", desc: "Understand the \"option pool shuffle\" and how pool carve-outs affect your effective pre-money valuation." },
  { slug: "convertible-note-calculator", title: "Convertible Note Calculator", icon: "PieChart", desc: "Calculate interest accrual, conversion prices, and share allocations for convertible notes." },
  { slug: "tam-calculator", title: "TAM SAM SOM Calculator", icon: "Target", desc: "Estimate your Total Addressable Market, Serviceable Addressable Market, and Serviceable Obtainable Market with multi-segment projections." },
  { slug: "runway-calculator", title: "Runway & Burn Rate Calculator", icon: "Gauge", desc: "Calculate your startup burn rate, runway in months, and project when you need to fundraise. Includes growth modeling." },
  { slug: "revenue-forecast", title: "12-Month Revenue Forecast", icon: "BarChart3", desc: "Build a 12-month revenue projection with multiple product categories, growth modeling, and investor-ready output." },
  { slug: "saas-valuation-calculator", title: "SaaS Valuation Calculator", icon: "LineChart", desc: "Estimate your SaaS company valuation using the SaaS Capital 7-step method based on ARR, growth, retention, and margins." },
  { slug: "due-diligence-checker", title: "Due Diligence Readiness Checker", icon: "ClipboardCheck", desc: "Assess your due diligence readiness across 10 categories and 38 documents. Identify gaps before investor scrutiny begins." },
  { slug: "fundraising-stage-finder", title: "Fundraising Stage Fit Finder", icon: "Compass", desc: "Determine whether your startup fits Pre-Seed, Seed, or Series A based on revenue, team size, product maturity, and traction." },
  { slug: "negotiation-leverage", title: "Negotiation Leverage Assessment", icon: "Scale", desc: "Score 31 weighted negotiation factors across BATNA, deal terms, traction, and investor intel for VC or Angel fundraising." },
  { slug: "investor-readiness-scorecard", title: "Investor Readiness Scorecard", icon: "Award", desc: "Score your startup across 5 weighted dimensions — Product, Market, Team, Strategy, and Economics — with 50 criteria total." },
];
const CALC_LIVE = CALCS.map(c => c.slug);

const parseNum = raw => { const n = parseFloat(String(raw).replace(/[^0-9.\-]/g, "")); return Number.isFinite(n) ? n : 0; };
const fmtD = (n, d = 2) => (n < 0 ? "-$" : "$") + Math.abs(n).toLocaleString("en-US", { minimumFractionDigits: d, maximumFractionDigits: d });
const fmtN = (n, d = 2) => n.toLocaleString("en-US", { minimumFractionDigits: 0, maximumFractionDigits: d });
const fmtP = (n, d = 2) => (n * 100).toFixed(d) + "%";
const fmtInput = raw => { const c = String(raw).replace(/[^0-9]/g, ""); return c ? Number(c).toLocaleString("en-US") : ""; };
const fmtDec = raw => String(raw).replace(/[^0-9.]/g, "");

function NumIn({ id, label, value, set, pre, suf, ph, dec, hint }) {
  return (
    <label className="cx-in" htmlFor={id}>
      <span className="cx-lb">{label}</span>
      <span className="cx-fld">{pre && <i>{pre}</i>}<input id={id} type="text" inputMode={dec ? "decimal" : "numeric"} value={value} placeholder={ph} onChange={e => set(dec ? fmtDec(e.target.value) : fmtInput(e.target.value))} />{suf && <i>{suf}</i>}</span>
      {hint && <small>{hint}</small>}
    </label>
  );
}
function TxtIn({ id, label, value, set, ph }) {
  return <label className="cx-in" htmlFor={id}><span className="cx-lb">{label}</span><span className="cx-fld"><input id={id} type="text" value={value} placeholder={ph} onChange={e => set(e.target.value)} style={{ fontFamily: "var(--font-body)" }} /></span></label>;
}
function SelIn({ id, label, value, set, options }) {
  return (
    <label className="cx-in" htmlFor={id}>
      <span className="cx-lb">{label}</span>
      <span className="cx-fld sel"><select id={id} value={value} onChange={e => set(e.target.value)}>{options.map(([v, l]) => <option key={v} value={v}>{l}</option>)}</select><Icon name="ChevronDown" size={16} /></span>
    </label>
  );
}
function Seg({ value, set, options }) {
  return <div className="cx-seg" role="tablist">{options.map(([v, l]) => <button key={v} type="button" role="tab" aria-selected={value === v} className={value === v ? "on" : ""} onClick={() => set(v)}>{l}</button>)}</div>;
}
function Box({ title, sub, right, children, className = "" }) {
  return (
    <div className={"cx-box " + className}>
      {(title || right) && <div className="cx-bh"><div><h2>{title}</h2>{sub && <p>{sub}</p>}</div>{right}</div>}
      {children}
    </div>
  );
}
function Cells({ cols = 2, children }) { return <div className="cx-cells" data-c={cols} style={{ "--c": cols }}>{children}</div>; }
function Res({ label, value, hi, note }) { return <div className={"cx-res" + (hi ? " hi" : "")}><span className="cx-lb">{label}</span><b>{value}</b>{note && <small>{note}</small>}</div>; }
function Empty({ children }) { return <div className="cx-empty"><Icon name="Calculator" size={20} /><p>{children}</p></div>; }
function Bar({ parts }) {
  const tot = parts.reduce((s, p) => s + p[1], 0) || 1;
  return (
    <div className="cx-bar-w">
      <div className="cx-bar">{parts.map(([l, v, c]) => <i key={l} style={{ width: (v / tot) * 100 + "%", background: c }} title={l}></i>)}</div>
      <div className="cx-leg">{parts.map(([l, v, c]) => <span key={l}><i style={{ background: c }}></i>{l}<b>{fmtP(v / tot, 1)}</b></span>)}</div>
    </div>
  );
}
const CX_COL = ["var(--accent-primary)", "var(--accent-gold)", "#3B82F6", "#10B981", "#94A3B8", "#7C3AED", "#F97316"];

// Horizontally scrollable region (wide result tables): edge shadow + hint while content overflows, keyboard-focusable.
function ScrollX({ label, style, children }) {
  const ref = React.useRef(null);
  const [st, setSt] = React.useState({ over: false, l: false, r: false });
  React.useEffect(() => {
    const el = ref.current;
    const upd = () => {
      const over = el.scrollWidth > el.clientWidth + 1, l = el.scrollLeft > 1, r = over && el.scrollLeft + el.clientWidth < el.scrollWidth - 1;
      setSt(p => p.over === over && p.l === l && p.r === r ? p : { over, l, r });
    };
    upd();
    el.addEventListener("scroll", upd, { passive: true });
    const ro = window.ResizeObserver ? new ResizeObserver(upd) : null;
    if (ro) { ro.observe(el); if (el.firstElementChild) ro.observe(el.firstElementChild); }
    return () => { el.removeEventListener("scroll", upd); if (ro) ro.disconnect(); };
  }, []);
  return (
    <div className={"cx-scroll-w" + (st.l ? " l" : "") + (st.r ? " r" : "")} style={style}>
      {st.over && <span className="cx-scroll-hint" aria-hidden="true">Scroll for more<Icon name="ArrowRight" size={13} /></span>}
      <div ref={ref} className="cx-scroll" {...(st.over ? { role: "region", "aria-label": label, tabIndex: 0 } : {})}>{children}</div>
    </div>
  );
}

function PdfButton({ ready }) {
  return <button type="button" className="cx-pdf" disabled={!ready} onClick={() => window.print()}><Icon name="Download" size={15} />Download PDF</button>;
}

const CX_KEY = "ch_calc_access";
const CX_CONSENT = "I agree to receive updates and the newsletter.";
function hasCalcAccess() { try { return JSON.parse(localStorage.getItem(CX_KEY) || "null")?.saved === true; } catch (x) { return false; } }
function CalcGate({ name, slug, onDone, onClose }) {
  const [email, setEmail] = React.useState("");
  const [ok, setOk] = React.useState(false);
  const [err, setErr] = React.useState({});
  const [busy, setBusy] = React.useState(false);
  React.useEffect(() => {
    document.body.style.overflow = "hidden";
    const k = e => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", k);
    return () => { document.body.style.overflow = ""; window.removeEventListener("keydown", k); };
  }, []);
  const go = e => {
    e.preventDefault();
    const er = {};
    if (!email) er.email = "Email is required";
    else if (!/^\S+@\S+\.\S+$/.test(email)) er.email = "Please enter a valid email address";
    if (!ok) er.ok = "Please tick the box to continue";
    setErr(er);
    if (Object.keys(er).length) return;
    setBusy(true);
    CH_API.post("subscribe", { email: email.trim(), consent: true, consentText: CX_CONSENT, source: "calculator-gate", calculator: slug }).then(() => {
      try { localStorage.setItem(CX_KEY, JSON.stringify({ saved: true })); } catch (x) {}
      onDone();
    }).catch(x => { setBusy(false); setErr({ email: x.field === "email" ? x.message : "Something went wrong. Please try again." }); });
  };
  return (
    <div className="cx-dlg-bg gate" role="dialog" aria-modal="true" aria-labelledby="cx-gate-h" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <form className="cx-dlg" onSubmit={go} noValidate>
        <button type="button" className="x" aria-label="Close" onClick={onClose}><Icon name="X" size={18} /></button>
        <span className="cx-ic on" aria-hidden="true"><Icon name="Calculator" size={18} /></span>
        <h3 id="cx-gate-h">Unlock the {name}</h3>
        <label className="cx-in"><span className="cx-lb">Work email</span><span className="cx-fld"><input type="email" value={email} placeholder="you@company.com" autoComplete="email" onChange={e => { setEmail(e.target.value); setErr({ ...err, email: null }); }} style={{ fontFamily: "var(--font-body)" }} autoFocus /></span>{err.email && <small className="err">{err.email}</small>}</label>
        <label className={"cx-chk" + (err.ok ? " bad" : "")}><input type="checkbox" checked={ok} onChange={e => { setOk(e.target.checked); setErr({ ...err, ok: null }); }} /><span className="bx"><Icon name="Check" size={12} strokeWidth={3} /></span><span>I agree to receive updates and the newsletter. <a href="privacy.html" target="_blank" rel="noopener">Privacy Policy</a></span></label>
        {err.ok && <small className="err" style={{ marginTop: -6 }}>{err.ok}</small>}
        <Button variant="primary" size="lg" arrow type="submit" loading={busy} style={{ width: "100%", justifyContent: "center" }}>Unlock Calculator</Button>
      </form>
    </div>
  );
}

function CalcPage({ slug, title, hl, lead, children, how }) {
  const me = CALCS.find(c => c.slug === slug);
  const more = CALCS.filter(c => c.slug !== slug && CALC_LIVE.includes(c.slug)).slice(0, 3);
  const [open, setOpen] = React.useState(hasCalcAccess);
  const [ask, setAsk] = React.useState(false);
  const [note, setNote] = React.useState(false);
  React.useEffect(() => { if (!note) return; const t = setTimeout(() => setNote(false), 5000); return () => clearTimeout(t); }, [note]);
  // Calculator stays fully visible and crawlable; the gate opens on first interaction.
  const trap = e => {
    if (open) return;
    if (e.type === "focus" && e.target.blur) e.target.blur();
    e.preventDefault(); e.stopPropagation();
    setAsk(true);
  };
  return (
    <>
      {!open && ask && <CalcGate name={me.title} slug={slug} onDone={() => { setOpen(true); setAsk(false); setNote(true); }} onClose={() => setAsk(false)} />}
      <div className="cx-toast-w" role="status" aria-live="polite">{note && <span className="cx-toast"><i aria-hidden="true"><Icon name="Check" size={14} strokeWidth={3} /></i>Unlocked. You're on the list.</span>}</div>
      <Phero eyebrow="Free Calculator" title={<>{title} <span className="hl">{hl}</span></>} lead={lead}>
        <div className="cx-crumb rv" style={{ "--d": "180ms" }}><a href="calculators.html">All calculators</a><Icon name="ChevronRight" size={14} /><span>{me.title}</span></div>
      </Phero>
      <div className="cx-print-h"><img src="assets/logos/logo-dark.png" alt="Capital Hunt" /><span>{me.title} · {new Date().toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" })}</span></div>
      <section className="block"><div className="wrap cx-wrap" onPointerDownCapture={trap} onFocusCapture={trap} onKeyDownCapture={trap}>{children}</div></section>
      {how && <section className="block cx-how-s"><div className="wrap cx-wrap"><div className="cx-how rv">{how}</div></div></section>}
      <section className="block cx-more-s"><div className="wrap">
        <div className="cx-more-h rv"><h2>More Free Calculators</h2><a href="calculators.html">View All Calculators →</a></div>
        <div className="cx-grid three">{more.map((c, i) => <CalcCard key={c.slug} c={c} i={i} />)}</div>
      </div></section>
      <CTAStrip title="Need More Than Calculators?" sub="These free tools are just the start. Find and reach the right investors with Capital Hunt." />
    </>
  );
}

function CalcCard({ c, i = 0 }) {
  const live = CALC_LIVE.includes(c.slug);
  const Tag = live ? "a" : "div";
  return (
    <div className="rv" style={{ "--d": (i % 3) * 70 + "ms", display: "flex", minWidth: 0 }}>
      <Tag className={"cx-card" + (live ? "" : " soon")} {...(live ? { href: c.slug + ".html" } : {})}>
        <span className="cx-ic" aria-hidden="true"><Icon name={c.icon} size={18} /></span>
        <h3>{c.title}</h3>
        <p>{c.desc}</p>
        {live ? <span className="go">Use Calculator<Icon name="ArrowRight" size={15} /></span> : <span className="soon-t">Coming soon</span>}
      </Tag>
    </div>
  );
}

function Rate({ max, min = 1, value, set, label }) {
  return <div className="cx-rate" role="radiogroup" aria-label={label} style={{ "--n": max - min > 5 ? Math.ceil((max - min + 1) / 2) : max - min + 1 }}>{Array.from({ length: max - min + 1 }, (_, i) => i + min).map(n => <button key={n} type="button" role="radio" aria-checked={value === n} className={value === n ? "on" : value != null && n < value ? "fill" : ""} onClick={() => set(n)}>{n}</button>)}</div>;
}
function Tri({ value, set, options, label }) {
  return <div className="cx-tri" role="radiogroup" aria-label={label}>{options.map(([v, l, tone]) => <button key={v} type="button" role="radio" aria-checked={value === v} className={(value === v ? "on " : "") + (tone || "")} onClick={() => set(v)}>{l}</button>)}</div>;
}
function Gauge({ pct, label, sub }) {
  const p = Math.max(0, Math.min(1, pct)), C = 2 * Math.PI * 52;
  const tone = p >= .8 ? "#10B981" : p >= .6 ? "var(--accent-primary)" : p >= .4 ? "var(--accent-gold)" : "#DC2626";
  return (
    <div className="cx-gauge">
      <svg viewBox="0 0 120 120" width="132" height="132" aria-hidden="true"><circle cx="60" cy="60" r="52" fill="none" stroke="#EEF0F5" strokeWidth="10" /><circle cx="60" cy="60" r="52" fill="none" stroke={tone} strokeWidth="10" strokeLinecap="round" strokeDasharray={C} strokeDashoffset={C * (1 - p)} transform="rotate(-90 60 60)" style={{ transition: "stroke-dashoffset .8s var(--ease-out-expo)" }} /></svg>
      <div className="v"><b>{label}</b>{sub && <small>{sub}</small>}</div>
    </div>
  );
}

function mountCalc(node) { mountPage(node, { current: "calculators" }); }

Object.assign(window, { CALCS, CALC_LIVE, parseNum, fmtD, fmtN, fmtP, fmtInput, fmtDec, NumIn, TxtIn, SelIn, Seg, Box, Cells, Res, Empty, Bar, CX_COL, Rate, Tri, Gauge, ScrollX, PdfButton, CalcGate, hasCalcAccess, CalcPage, CalcCard, mountCalc });
