/* global React */
const { useEffect, useState } = React;

// =================================================================
// §3.5 FROM THE BOOK — fanned cards (kept hidden — replaced by Results section)
// =================================================================
const BOOK_CARDS = [];
function FromTheBook() { return null; }

// =================================================================
// §4 ROI CALCULATOR — spend slider + dashboard panel
// =================================================================
const VERTICALS = [
  { id: "clinics", nm: "Clinics" },
  { id: "home",    nm: "Home Services" },
  { id: "agency",  nm: "Agencies / Coaches / Consultants" },
  { id: "ecom",    nm: "E-Commerce" },
];

// CPL & CPB locked per niche. ROAS values are realistic averages.
const SUB_NICHES = {
  clinics: [
    { id: "chiro",     nm: "Chiropractic",         cpl: 13, indCpl: 30, cpb: 37,  indCpb: 143, roas: 45, indRoas: 12, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "medspa",    nm: "Aesthetics / Med Spa", cpl: 15, indCpl: 35, cpb: 54,  indCpb: 208, roas: 42, indRoas: 11, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "regen",     nm: "Regenerative Medicine",cpl: 22, indCpl: 50, cpb: 100, indCpb: 379, roas: 38, indRoas: 10, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "mental",    nm: "Mental Health",        cpl: 10, indCpl: 25, cpb: 25,  indCpb: 104, roas: 50, indRoas: 13, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "physio",    nm: "Physiotherapy",        cpl: 15, indCpl: 32, cpb: 38,  indCpb: 133, roas: 44, indRoas: 12, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "massage",   nm: "Massage Therapy",      cpl: 15, indCpl: 32, cpb: 36,  indCpb: 127, roas: 40, indRoas: 11, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "weight",    nm: "Medical Weight Loss",  cpl: 16, indCpl: 80, cpb: 62,  indCpb: 533, roas: 35, indRoas: 9,  payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "dental",    nm: "Dental",               cpl: 22, indCpl: 50, cpb: 69,  indCpb: 260, roas: 41, indRoas: 11, payoutLabel: "Booking",  ourLabel: "Booking" },
  ],
  home: [
    { id: "hvac",      nm: "HVAC",                 cpl: 25, indCpl: 60, cpb: 67,  indCpb: 313, roas: 35, indRoas: 12, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "roofing",   nm: "Roofing",              cpl: 30, indCpl: 75, cpb: 80,  indCpb: 446, roas: 30, indRoas: 9,  payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "solar",     nm: "Solar",                cpl: 28, indCpl: 95, cpb: 79,  indCpb: 720, roas: 28, indRoas: 8,  payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "plumbing",  nm: "Plumbing",             cpl: 22, indCpl: 65, cpb: 58,  indCpb: 380, roas: 36, indRoas: 11, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "electric",  nm: "Electrical",           cpl: 20, indCpl: 58, cpb: 55,  indCpb: 340, roas: 34, indRoas: 10, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "landscape", nm: "Landscaping",          cpl: 20, indCpl: 55, cpb: 65,  indCpb: 320, roas: 32, indRoas: 10, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "perm",      nm: "Perm. Lighting",       cpl: 18, indCpl: 50, cpb: 56,  indCpb: 333, roas: 38, indRoas: 11, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "epoxy",     nm: "Epoxy Flooring",       cpl: 25, indCpl: 60, cpb: 89,  indCpb: 357, roas: 33, indRoas: 10, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "painting",  nm: "Painting",             cpl: 18, indCpl: 50, cpb: 52,  indCpb: 290, roas: 33, indRoas: 10, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "garage",    nm: "Garage Doors",         cpl: 15, indCpl: 40, cpb: 45,  indCpb: 250, roas: 38, indRoas: 12, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "pest",      nm: "Pest Control",         cpl: 14, indCpl: 38, cpb: 42,  indCpb: 220, roas: 36, indRoas: 11, payoutLabel: "Booking",  ourLabel: "Booking" },
    { id: "windows",   nm: "Window / Gutter",      cpl: 12, indCpl: 35, cpb: 38,  indCpb: 210, roas: 35, indRoas: 11, payoutLabel: "Booking",  ourLabel: "Booking" },
  ],
  agency: [
    { id: "agency",    nm: "Agency",               cpl: 8,  indCpl: 28, cpb: 48,  indCpb: 280, roas: 12, indRoas: 4,  payoutLabel: "Call",     ourLabel: "Call" },
    { id: "coaching",  nm: "Coaching",             cpl: 15, indCpl: 28, cpb: 75,  indCpb: 233, roas: 10, indRoas: 4,  payoutLabel: "Call",     ourLabel: "Call" },
    { id: "consult",   nm: "Consulting",           cpl: 7,  indCpl: 25, cpb: 44,  indCpb: 260, roas: 14, indRoas: 5,  payoutLabel: "Call",     ourLabel: "Call" },
  ],
  ecom: [
    { id: "consumer",  nm: "Consumer Goods",       cpl: 1,  indCpl: 2,  cpb: 15,  indCpb: 38,  roas: 5,  indRoas: 2,  payoutLabel: "Purchase", ourLabel: "Purchase" },
    { id: "apparel",   nm: "Apparel / Fashion",    cpl: 1,  indCpl: 2,  cpb: 20,  indCpb: 52,  roas: 5,  indRoas: 2,  payoutLabel: "Purchase", ourLabel: "Purchase" },
    { id: "baby",      nm: "Baby / Kids",          cpl: 1,  indCpl: 3,  cpb: 22,  indCpb: 58,  roas: 6,  indRoas: 2,  payoutLabel: "Purchase", ourLabel: "Purchase" },
    { id: "grooming",  nm: "Beauty / Grooming",    cpl: 1,  indCpl: 2,  cpb: 18,  indCpb: 48,  roas: 5,  indRoas: 2,  payoutLabel: "Purchase", ourLabel: "Purchase" },
    { id: "events",    nm: "Events / Tickets",     cpl: 1,  indCpl: 2,  cpb: 12,  indCpb: 35,  roas: 7,  indRoas: 3,  payoutLabel: "Purchase", ourLabel: "Purchase" },
  ],
};

function fmt(n) {
  if (n >= 1000000) return `$${(n / 1000000).toFixed(1)}M`;
  if (n >= 1000) return `$${(n / 1000).toFixed(0)}K`;
  return `$${Math.round(n).toLocaleString()}`;
}

function Calculator({ defaultVert = "clinics", lockedVert = null, heading = null, subheading = null }) {
  const activeDefault = lockedVert || defaultVert;
  const [vert, setVert] = useState(activeDefault);
  const [subId, setSubId] = useState(SUB_NICHES[activeDefault][0].id);
  const [spend, setSpend] = useState(5000);

  const subs = SUB_NICHES[vert];
  const sub = subs.find(s => s.id === subId) || subs[0];

  const handleVert = (v) => {
    setVert(v);
    setSubId(SUB_NICHES[v][0].id);
  };

  // Wire nav-links data-vert clicks
  useEffect(() => {
    const onClick = (e) => {
      const a = e.target.closest('a[data-vert]');
      if (!a) return;
      const v = a.dataset.vert;
      if (SUB_NICHES[v]) {
        setVert(v);
        setSubId(SUB_NICHES[v][0].id);
      }
    };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, []);

  // Derived numbers
  const ourLeads = Math.round(spend / sub.cpl);
  const indLeads = Math.round(spend / sub.indCpl);
  const ourBookings = Math.round(spend / sub.cpb);
  const indBookings = Math.round(spend / sub.indCpb);

  const cplLowerPct = Math.round((1 - sub.cpl / sub.indCpl) * 100);
  const cpbLowerPct = Math.round((1 - sub.cpb / sub.indCpb) * 100);

  // Slider position (1k – 50k log-ish for nicer feel)
  const SPEND_MIN = 1000;
  const SPEND_MAX = 50000;
  const sliderPct = ((spend - SPEND_MIN) / (SPEND_MAX - SPEND_MIN)) * 100;

  const callsLabel = sub.payoutLabel === "Call" ? "Calls / mo" : sub.payoutLabel === "Purchase" ? "Purchases / mo" : "Bookings / mo";
  const cpbLabelTitle = sub.payoutLabel === "Call" ? "Cost Per Call" : sub.payoutLabel === "Purchase" ? "Cost Per Purchase" : "Cost Per Booking";

  return (
    <section className="sec calc-sec" id="niches">
      <div className="sec-inner">
        <div style={{ textAlign: "center" }}>
          <span className="eyebrow"><span className="dot" /> ROI CALCULATOR</span>
          <h2 className="display" style={{ marginTop: 24 }}>
            {heading || <>Find out your ROI.<br/><span className="v" style={{fontFamily:"'Instrument Serif', serif", fontStyle:"italic", fontWeight:400}}>See what we deliver.</span></>}
          </h2>
          <p className="lede" style={{ maxWidth: 64 + "ch", margin: "20px auto 0" }}>
            {subheading || "Pick your niche, drag your monthly ad spend, see the actual numbers we deliver vs. industry. Every CPL and CPB below is pulled from our live book of 385+ accounts."}
          </p>
        </div>

        <div className="calc2-card">
          {/* Vertical tabs — hidden when lockedVert is set */}
          {!lockedVert && (
            <div className="calc2-tabs">
              {VERTICALS.map(v => (
                <button
                  key={v.id}
                  className={"calc2-tab" + (vert === v.id ? " active" : "")}
                  onClick={() => handleVert(v.id)}
                >
                  {v.nm}
                </button>
              ))}
            </div>
          )}

          {/* Sub-niche pills */}
          <div className="calc2-subs">
            {subs.map(s => (
              <button
                key={s.id}
                className={"calc2-sub" + (subId === s.id ? " active" : "")}
                onClick={() => setSubId(s.id)}
              >
                {s.nm}
              </button>
            ))}
          </div>

          {/* Spend block */}
          <div className="calc2-spend">
            <div className="calc2-spend-top">
              <span className="lab">MONTHLY AD SPEND</span>
              <span className="hint">DRAG ↓</span>
            </div>
            <div className="calc2-amount">${spend.toLocaleString()}</div>
            <div className="calc2-slider-wrap">
              <input
                type="range"
                min={SPEND_MIN}
                max={SPEND_MAX}
                step={500}
                value={spend}
                onChange={e => setSpend(parseInt(e.target.value))}
                className="calc2-slider"
                style={{ ["--pct"]: sliderPct + "%" }}
              />
            </div>
            <div className="calc2-slider-marks">
              <span>$1,000</span>
              <span>$50,000+</span>
            </div>
          </div>

          {/* Top metrics row */}
          <div className="calc2-metrics">
            <div className="calc2-metric">
              <div className="lab">LEADS / MO</div>
              <div className="val">{ourLeads.toLocaleString()}</div>
              <div className="sub"><s>{indLeads.toLocaleString()}</s> typical</div>
            </div>
            <div className="calc2-metric">
              <div className="lab">{callsLabel.toUpperCase()}</div>
              <div className="val">{ourBookings.toLocaleString()}</div>
              <div className="sub"><s>{indBookings.toLocaleString()}</s> typical</div>
            </div>
            <div className="calc2-metric">
              <div className="lab">{vert === 'ecom' ? 'AVG ROAS' : 'AVG ROI'}</div>
              <div className="val v-violet">{sub.roas}<span style={{ fontSize: '0.75em', marginLeft: 3, opacity: 1, display: 'inline', fontWeight: 900 }}>×</span></div>
              <div className="sub"><s>{sub.indRoas}×</s> typical</div>
            </div>
          </div>

          {/* Cost row */}
          <div className="calc2-costs">
            <div className="calc2-cost">
              <div className="cost-top">
                <span className="lab">COST PER LEAD</span>
                <span className="badge-lower">{cplLowerPct}% lower</span>
              </div>
              <div className="cost-row">
                <span className="big-num">${sub.cpl}</span>
                <span className="strike">${sub.indCpl}</span>
              </div>
              <div className="cost-sub">industry typical</div>
            </div>
            <div className="calc2-cost">
              <div className="cost-top">
                <span className="lab">{cpbLabelTitle.toUpperCase()}</span>
                <span className="badge-lower">{cpbLowerPct}% lower</span>
              </div>
              <div className="cost-row">
                <span className="big-num">${sub.cpb}</span>
                <span className="strike">${sub.indCpb}</span>
              </div>
              <div className="cost-sub">industry typical</div>
            </div>
          </div>

          {/* Exclusivity callout */}
          <div className="calc2-exclusive">
            <span className="calc2-exclusive-dot" />
            <span>Want this for <b>your</b> market? <span className="hl">We only take 1 business per market.</span></span>
          </div>

          {/* Footer / CTA */}
          <div className="calc2-foot">
            <div className="calc2-foot-line">
              <span>BACKED BY 385+ LIVE ACCOUNTS</span>
              <span className="dot" />
              <span>$117M+ AD SPEND MANAGED</span>
              <span className="dot" />
              <span>UPDATED Q2 2026</span>
            </div>
            <a href="book.html" className="btn btn-violet">Run my account →</a>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { FromTheBook, Calculator });
