/* ExploiTable — added sections: product shots, leak explorer, compare table,
   sticky mobile CTA, player traits, download card.
   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.</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">PLAYER PROFILE</span>
            </div>
            <div className="shot-body">
              <image-slot id="shot-profile" shape="rect" placeholder="Drop a player-profile screenshot"></image-slot>
            </div>
            <figcaption className="shot-cap">Every regular, with their biggest deviations from the pool.</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: "Folds to flop bets far more often than the pool, and gives up his big blind to steals.",
  },
  {
    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: "Rarely calls a river bet and seldom leads one; his 3-bets are much tighter than the pool's.",
  },
  {
    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: "Calls flop bets far more than the pool, bets the river often, and folds to most 4-bets.",
  },
];

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 player. See the profile.</h2>
          </div>
          <p className="sec-sub">Three example profiles. Click through them to see what a profile shows.</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">TAKEAWAY</span>
              <p>{v.exploit}</p>
            </div>
            <a href="pricing.html#final" className="btn btn-primary explorer-cta">Study your own pool →</a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ───────── comparison table ───────── */
const COMPARE_ROWS = [
  ["Per-player stats from your hand histories", "yes", "yes", "no"],
  ["Plain-English note on each leak", "yes", "no", "no"],
  ["Profile of every regular in your pool", "yes", "no", "no"],
  ["Deviation vs field baseline (+/-)", "yes", "no", "no"],
  ["Optimal strategy when you have no reads", "yes", "no", "yes"],
  ["Setup effort", "one evening", "days of config", "per spot"],
];

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 player.</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() {
  return (
    <div className="sticky-cta">
      <div className="sticky-cta-txt">
        <span className="mono sticky-cta-k">PLO &amp; NLH STUDY · FREE DURING BETA</span>
      </div>
      <a href="pricing.html#final" className="btn btn-primary">Request access</a>
    </div>
  );
}

/* ───────── player traits ───────── */
const TRAITS = [
  { key: "sticky",   name: "Sticky",              tip: "Won't let go once they're in — keeps calling bets on early streets.", stat: "Fold to Cbet 34% · Fold to Turn 29%", n: "412 hands" },
  { key: "aggpre",   name: "Aggressive preflop",  tip: "Raises and re-raises before the flop instead of just calling.",       stat: "PFR 24% · 3Bet 11%", n: "412 hands" },
  { key: "aggpost",  name: "Aggressive postflop", tip: "Keeps betting and raising on flop and turn — fights for pots.",        stat: "Flop Raise 14% · Turn Bet 71%", n: "388 hands" },
  { key: "loosepre", name: "Loose preflop",       tip: "Plays far too many starting hands.",                                   stat: "VPIP 41% · field 27%", n: "412 hands" },
  { key: "aggriver", name: "Aggressive river",    tip: "Fires the last, biggest bet — not afraid of the final street.",        stat: "Bet River 61% · field 38%", n: "204 hands" },
  { key: "hero",     name: "Hero caller",         tip: "Pays off big river bets with weak hands to keep you honest.",          stat: "Fold to River Bet 31% · field 55%", n: "204 hands" },
  { key: "trappy",   name: "Trappy",              tip: "Checks strong hands to spring a check-raise — danger behind passivity.", stat: "Check-Raise 13% · Delayed Cbet 22%", n: "388 hands" },
];

const TRAIT_PLAYERS = [
  { name: "MidnightTilt", verdict: "Fish", tag: "STATION · 5/10",
    scores: { sticky: 94, aggpre: 41, aggpost: 58, loosepre: 78, aggriver: 88, hero: 91, trappy: 22 } },
  { name: "ShovItAll", verdict: "Fish", tag: "LAG · 5/10",
    scores: { sticky: 12, aggpre: 89, aggpost: 84, loosepre: 82, aggriver: 71, hero: 8, trappy: 31 } },
  { name: "river_rat99", verdict: "Reg", tag: "NIT · 2/5",
    scores: { sticky: 18, aggpre: 47, aggpost: 52, loosepre: 9, aggriver: 44, hero: 15, trappy: 63 } },
];

function TraitBar({ trait, score }) {
  const [hover, setHover] = useState(false);
  // loud only at the extremes; quiet in the mid-range
  const extreme = score >= 80 || score <= 20;
  let cls = "trait-mid";
  if (score >= 80) cls = "trait-hot";
  else if (score <= 20) cls = "trait-cold";
  return (
    <div className={"trait" + (extreme ? " is-extreme" : "")}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
      <div className="trait-top">
        <span className="trait-name">{trait.name}</span>
        <span className="trait-score mono">{score}</span>
      </div>
      <div className="trait-track">
        <span className="trait-mid-tick" aria-hidden="true"></span>
        <span className={"trait-fill " + cls} style={{ width: score + "%" }}></span>
      </div>
      {hover && (
        <div className="trait-pop" role="tooltip">
          <div className="trait-pop-tip">{trait.tip}</div>
          <div className="trait-pop-stat mono">{trait.stat}</div>
          <div className="trait-pop-n mono">{trait.n} · vs pool baseline</div>
        </div>
      )}
    </div>
  );
}

function TraitRow({ p }) {
  const [open, setOpen] = useState(false);
  const vClass = p.verdict === "Reg" ? "v-reg" : p.verdict === "Fish" ? "v-fish" : "v-avg";
  return (
    <div className={"trow" + (open ? " open" : "")}>
      <button className="trow-head" onClick={() => setOpen((o) => !o)} aria-expanded={open}>
        <span className="trow-chev" aria-hidden="true">›</span>
        <span className="trow-avatar">{p.name.slice(0, 2)}</span>
        <span className="trow-id">
          <span className="trow-name">{p.name}</span>
          <span className="trow-tag mono">{p.tag}</span>
        </span>
        <span className={"trow-verdict " + vClass}>{p.verdict}</span>
      </button>
      {open && (
        <div className="trow-body">
          <div className="trow-body-lbl mono">PLAYER TRAITS · relative to this pool (50 = typical)</div>
          <div className="traits-grid">
            {TRAITS.map((t) => <TraitBar key={t.key} trait={t} score={p.scores[t.key]} />)}
          </div>
        </div>
      )}
    </div>
  );
}

function PlayerTraits() {
  return (
    <section className="section" id="traits" data-screen-label="07 Player traits">
      <div className="shell">
        <div className="sec-head">
          <div>
            <div className="sec-eyebrow">Player traits</div>
            <h2 className="sec-title">"Fish" tells you they lose.<br/>Traits tell you <span className="accent">how they play</span>.</h2>
          </div>
          <p className="sec-sub">Every player gets seven plain-English traits. Only the extremes light up — hover any bar for the meaning, stats, and sample size.</p>
        </div>
        <div className="trows">
          {TRAIT_PLAYERS.map((p) => <TraitRow key={p.name} p={p} />)}
        </div>
        <div className="trait-legend mono">
          <span><span className="dotk trait-hot"></span>90+ extreme high</span>
          <span><span className="dotk trait-mid"></span>~50 typical for this pool</span>
          <span><span className="dotk trait-cold"></span>10− extreme low</span>
        </div>
      </div>
    </section>
  );
}

/* ───────── download (gated: the Worker checks the access key before serving) ───────── */
function DownloadCard() {
  const WORKER = "https://exploitable-download.tomereinan.workers.dev";
  const [key, setKey] = useState("");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(false);
  const submit = async (e) => {
    e.preventDefault();
    const k = key.trim();
    if (!k) return;
    setBusy(true); setErr(false);
    try {
      // download-config.js (download.html) checks the key first; otherwise the
      // Worker's /get still refuses a bad key with a 403.
      const url = typeof window.requestDownload === "function"
        ? await window.requestDownload(k)
        : WORKER + "/get?key=" + encodeURIComponent(k);
      window.location.href = url;
    } catch (_) {
      setErr(true);
    } finally {
      setBusy(false);
    }
  };
  return (
    <section className="dl-wrap" data-screen-label="01 Download">
      <div className="dl-card">
        <img src="assets/wordmark.png" alt="ExploiTable" className="dl-logo" />
        <p className="dl-tag">PLO &amp; NLH study software for after the session.</p>
        <form className="dl-form" onSubmit={submit}>
          <label className="dl-label mono" htmlFor="dl-key">ACCESS KEY</label>
          <input id="dl-key" className={"dl-input mono" + (err ? " err" : "")} value={key}
                 onChange={(e) => { setKey(e.target.value); setErr(false); }}
                 placeholder="paste your key" autoComplete="off" spellCheck="false"
                 style={{ height: "48px", fontSize: "15px", letterSpacing: ".02em" }} />
          {err && <div className="dl-error">That key wasn’t recognised.</div>}
          <button className="btn btn-primary btn-lg dl-submit" type="submit" disabled={busy || !key.trim()}>
            <span className="dl-win" aria-hidden="true"></span>Download for Windows
          </button>
          <div className="dl-foot mono">Windows 10/11 · 64-bit · ~250 MB</div>
          <div className="dl-help mono" style={{ marginTop: "18px" }}>
            Downloads need an access key. <a href="pricing.html#final">Request access →</a>
          </div>
        </form>
      </div>
    </section>
  );
}

Object.assign(window, { ProductShots, LeakExplorer, CompareTable, StickyCTA, PlayerTraits, DownloadCard });
