/* ExploiTable — added sections: product shots, leak explorer, social proof,
   compare table, sticky mobile CTA, exit-intent modal.
   Loads BEFORE app.jsx; components are referenced by App at render time. */

const { useState, useEffect, useRef } = React;

/* ───────── product screenshots (user drops real captures) ───────── */
function ProductShots() {
  return (
    <section className="section" id="shots" data-screen-label="03 Product shots">
      <div className="shell">
        <div className="sec-head">
          <div>
            <div className="sec-eyebrow">The real thing</div>
            <h2 className="sec-title">This is what it looks like at your table.</h2>
          </div>
          <p className="sec-sub">Actual captures from the app — no mockups, no renders.</p>
        </div>
        <div className="shots-grid">
          <figure className="shot">
            <div className="shot-chrome">
              <span className="shot-dot"></span><span className="shot-dot"></span><span className="shot-dot"></span>
              <span className="shot-title mono">LIVE HUD · 4 TABLES</span>
            </div>
            <div className="shot-body">
              <image-slot id="shot-live" shape="rect" placeholder="Drop a live-HUD screenshot"></image-slot>
            </div>
            <figcaption className="shot-cap">Popups attach to every villain the engine has studied.</figcaption>
          </figure>
          <figure className="shot">
            <div className="shot-chrome">
              <span className="shot-dot"></span><span className="shot-dot"></span><span className="shot-dot"></span>
              <span className="shot-title mono">STUDY MODE · LEAK REPORT</span>
            </div>
            <div className="shot-body">
              <image-slot id="shot-study" shape="rect" placeholder="Drop a study-mode screenshot"></image-slot>
            </div>
            <figcaption className="shot-cap">Every regular, ranked by how much their leaks are worth to you.</figcaption>
          </figure>
        </div>
      </div>
    </section>
  );
}

/* ───────── interactive leak explorer ───────── */
const EXPLORER_VILLAINS = [
  {
    name: "ShovItAll", tag: "LAG · 5/10", hands: "4,318 hands",
    leaks: [
      { stat: "Fold to Cbet IP", val: "68%", dev: "+17", dir: "up", field: "field 51%" },
      { stat: "Cbet Flop", val: "39%", dev: "-7", dir: "dn", field: "field 46%" },
      { stat: "Fold to Steal BB", val: "71%", dev: "+13", dir: "up", field: "field 58%" },
    ],
    exploit: "Cbet 100% on dry boards. Open any two from the button when he's in the blinds.",
  },
  {
    name: "river_rat99", tag: "NIT · 2/5", hands: "2,911 hands",
    leaks: [
      { stat: "Fold to River Bet", val: "74%", dev: "+19", dir: "up", field: "field 55%" },
      { stat: "Donk River", val: "2%", dev: "-6", dir: "dn", field: "field 8%" },
      { stat: "3Bet", val: "4%", dev: "-5", dir: "dn", field: "field 9%" },
    ],
    exploit: "Barrel rivers relentlessly. When he raises, fold everything but the nuts — his 3Bets are nutted.",
  },
  {
    name: "MidnightTilt", tag: "STATION · 5/10", hands: "6,102 hands",
    leaks: [
      { stat: "Bet River", val: "61%", dev: "+23", dir: "up", field: "field 38%" },
      { stat: "Fold to Cbet", val: "31%", dev: "-20", dir: "dn", field: "field 51%" },
      { stat: "Fold to 4Bet", val: "82%", dev: "+21", dir: "up", field: "field 61%" },
    ],
    exploit: "Value bet thin, never bluff the flop. 4Bet small with any premium — he folds or stacks off.",
  },
];

function LeakExplorer() {
  const [sel, setSel] = useState(0);
  const v = EXPLORER_VILLAINS[sel];
  return (
    <section className="section" id="explorer" data-screen-label="05 Leak explorer">
      <div className="shell">
        <div className="sec-head">
          <div>
            <div className="sec-eyebrow">Try it</div>
            <h2 className="sec-title">Pick a villain. See the damage.</h2>
          </div>
          <p className="sec-sub">Three real profiles from a ClubGG database. Click through them — this is the exact popup you'd see live.</p>
        </div>
        <div className="explorer">
          <div className="explorer-picks" role="tablist" aria-label="Choose a villain">
            {EXPLORER_VILLAINS.map((p, i) => (
              <button key={p.name} role="tab" aria-selected={sel === i}
                className={"explorer-pick" + (sel === i ? " on" : "")}
                onClick={() => setSel(i)}>
                <span className="explorer-avatar">{p.name.slice(0, 2)}</span>
                <span className="col">
                  <span className="explorer-name">{p.name}</span>
                  <span className="explorer-tag mono">{p.tag} · {p.hands}</span>
                </span>
              </button>
            ))}
          </div>
          <div className="explorer-panel" key={v.name}>
            <div className="explorer-pops">
              {v.leaks.map((l) => (
                <div className="tshow-pop explorer-pop" key={l.stat}>
                  <div className="tpop-stat">{l.stat} {l.val} <span className={l.dir}>({l.dev})</span></div>
                  <div className="tpop-sub">{v.name} · {l.field}</div>
                </div>
              ))}
            </div>
            <div className="explorer-exploit">
              <span className="mono explorer-exploit-k">EXPLOIT</span>
              <p>{v.exploit}</p>
            </div>
            <a href="pricing.html#final" className="btn btn-primary explorer-cta">Scan your own pool — free →</a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ───────── social proof ───────── */
const QUOTES = [
  { q: "I stopped guessing on rivers. The popup told me the reg over-folds and I just took the pot down, over and over.", who: "beta user #041", meta: "NLH 2/5 → 5/10 in 6 weeks" },
  { q: "Set it up in one evening. Next session it flagged three regs I'd been playing against for a year. I had no idea.", who: "beta user #007", meta: "6-max reg, ClubGG" },
  { q: "The study mode alone is worth it. It ranked my whole pool by exploitability and I just work down the list.", who: "beta user #113", meta: "multi-tabling 8 tables" },
];

function SocialProof() {
  const [hands, setHands] = useState(41_286_907);
  useEffect(() => {
    const id = setInterval(() => setHands((h) => h + Math.floor(Math.random() * 37) + 4), 900);
    return () => clearInterval(id);
  }, []);
  return (
    <section className="section" id="proof" data-screen-label="06 Social proof">
      <div className="shell">
        <div className="proof-counter">
          <span className="proof-num mono">{hands.toLocaleString("en-US")}</span>
          <span className="proof-lbl mono">HANDS ANALYZED BY THE ENGINE · AND COUNTING</span>
        </div>
        <div className="quotes">
          {QUOTES.map((x) => (
            <figure className="quote" key={x.who}>
              <blockquote>“{x.q}”</blockquote>
              <figcaption>
                <span className="quote-who">{x.who}</span>
                <span className="quote-meta mono">{x.meta}</span>
              </figcaption>
            </figure>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ───────── comparison table ───────── */
const COMPARE_ROWS = [
  ["Shows stats at decision time", "yes", "yes", "no"],
  ["Tells you the exploit, not just the number", "yes", "no", "no"],
  ["Pre-computed per villain, ready in <2s", "yes", "no", "no"],
  ["Deviation vs field baseline (+/-)", "yes", "no", "no"],
  ["Optimal strategy when you have no reads", "yes", "no", "yes"],
  ["Works across every table at once", "yes", "yes", "no"],
  ["Setup effort", "one evening", "days of config", "study only"],
];

function CompareCell({ v }) {
  if (v === "yes") return <td className="cmp-yes">✓</td>;
  if (v === "no") return <td className="cmp-no">—</td>;
  return <td className="cmp-txt mono">{v}</td>;
}

function CompareTable() {
  return (
    <section className="section" id="compare" data-screen-label="04 Comparison">
      <div className="shell">
        <div className="sec-head">
          <div>
            <div className="sec-eyebrow">Versus</div>
            <h2 className="sec-title">HUDs show numbers. Solvers show theory.<br/>This shows the move.</h2>
          </div>
        </div>
        <div className="cmp-wrap">
          <table className="cmp">
            <thead>
              <tr>
                <th></th>
                <th className="cmp-hero">ExploiTable</th>
                <th>Generic HUD</th>
                <th>Solver</th>
              </tr>
            </thead>
            <tbody>
              {COMPARE_ROWS.map((r) => (
                <tr key={r[0]}>
                  <th scope="row">{r[0]}</th>
                  <CompareCell v={r[1]} /><CompareCell v={r[2]} /><CompareCell v={r[3]} />
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </section>
  );
}

/* ───────── sticky mobile CTA ───────── */
function StickyCTA() {
  const T = window.Timer;
  return (
    <div className="sticky-cta">
      <div className="sticky-cta-txt">
        <span className="mono sticky-cta-k">FREE ENDS IN</span>
        {T ? <T /> : null}
      </div>
      <a href="pricing.html#final" className="btn btn-primary">Start free</a>
    </div>
  );
}

/* ───────── exit-intent modal ───────── */
function ExitIntent() {
  const [open, setOpen] = useState(false);
  const T = window.Timer;
  useEffect(() => {
    let armed = true;
    try { if (sessionStorage.getItem("xt_exit_shown")) armed = false; } catch (_) {}
    if (!armed) return;
    const onLeave = (e) => {
      if (e.clientY > 8) return;
      try { sessionStorage.setItem("xt_exit_shown", "1"); } catch (_) {}
      setOpen(true);
      document.removeEventListener("mouseout", onLeave);
    };
    const t = setTimeout(() => document.addEventListener("mouseout", onLeave), 12000);
    return () => { clearTimeout(t); document.removeEventListener("mouseout", onLeave); };
  }, []);
  if (!open) return null;
  return (
    <div className="exit-veil" onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}>
      <div className="exit-modal" role="dialog" aria-modal="true" aria-label="Free seat expiring">
        <button className="exit-x" aria-label="Close" onClick={() => setOpen(false)}>✕</button>
        <div className="mono exit-k">BEFORE YOU GO</div>
        <h3 className="exit-h">Your free seat expires with the timer.</h3>
        {T ? <div className="exit-timer"><T size="lg" /></div> : null}
        <p className="exit-p">Everything is free until it hits zero — full engine, unlimited tables, no card. After that, it's paid.</p>
        <a href="pricing.html#final" className="btn btn-primary btn-lg" style={{ width: "100%" }} onClick={() => setOpen(false)}>Claim my free seat →</a>
        <button className="exit-skip" onClick={() => setOpen(false)}>I'll risk losing it</button>
      </div>
    </div>
  );
}

Object.assign(window, { ProductShots, LeakExplorer, SocialProof, CompareTable, StickyCTA, ExitIntent });
