/* BasedMTA site - v3. */

const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;
const CheckoutModal = window.CheckoutModal;

// =====================================================================
// Tweaks
// =====================================================================
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "blue"
}/*EDITMODE-END*/;

// =====================================================================
// Data
// =====================================================================
const TIERS = [
  {
    id: "basic",
    name: "Basic",
    tagline: "Visual coverage",
    durations: { "1d": 1, "7d": 5, "30d": 10 },
    pros: [
      { t: "Aimbot",   d: "every mode, every bone & FOV control" },
      { t: "ESP",      d: "players, NPCs, vehicles, projectiles, chams & radar" },
      { t: "Spoofer",  d: "new identity on every launch" },
      { t: "Comfy, easy to use UI" },
    ],
    cons: [
      { t: "Lua execution" },
      { t: "Resource management and autoexec" },
      { t: "Bot fleet and swarm coverage" },
      { t: "Exploit suite" },
    ],
    visual: {
      type: "image-pair",
      primary:   { src: "site/img/esp-1.png",         tag: "" },
      secondary: { src: "site/img/esp-targeting.png", tag: "" },
    },
  },
  {
    id: "pro",
    name: "Pro",
    featured: true,
    tagline: "Scripting utilities",
    durations: { "1d": 2, "7d": 10, "30d": 20 },
    pros: [
      { t: "Lua executor",   d: "blazingly fast, secure bytecode-based VM" },
      { t: "Autoexec",       d: "global + per-server scripts, runs code inside any loaded resource" },
      { t: "Script tools",   d: "decompiler for any .luac MTA script + dumper" },
      { t: "PktLib",         d: "state of the art Lua library for packet manipulation, injection and hooking" },
      { t: "Everything in Basic" },
    ],
    cons: [
      { t: "Bot fleet and swarm coverage" },
      { t: "Exploit suite" },
    ],
    visual: {
      type: "image-pair",
      primary:   { src: "site/img/decompiler.png",   tag: "" },
      secondary: { src: "site/img/exec-console.png", tag: "" },
    },
  },
  {
    id: "vip",
    name: "VIP",
    tagline: "Bots, exploits and scripting",
    durations: { "1d": 3, "7d": 15, "30d": 30 },
    pros: [
      { t: "Everything in Pro" },
      { t: "Bot fleet",       d: "Up to 20 instances with proxy support" },
      { t: "Swarm coverage",  d: "Shared blackboard across the fleet" },
      { t: "Private exploits", d: "Exclusive to this tier" },
    ],
    cons: [],
    visual: {
      type: "image-single",
      primary: { src: "site/img/bots-running.png", tag: "" },
    },
  },
];

const DURATIONS = [
  { id: "1d",  label: "1 day",   days: 1 },
  { id: "7d",  label: "7 days",  days: 7 },
  { id: "30d", label: "30 days", days: 30 },
];

const ADDONS = [
  { id: "exploits", name: "Extra 10 exploit uses",  sub: "Top up your exploit budget",  price: 5, vipOnly: true  },
  { id: "bots",     name: "Extra bots (>20)",       sub: "Open a ticket on Discord",     price: null, vipOnly: true, contact: true },
];

// =====================================================================
// Checkout context
// =====================================================================
const CheckoutCtx = createContext(null);
const useCheckout = () => useContext(CheckoutCtx);

function CheckoutProvider({ children }) {
  const [order, setOrder] = useState(null);
  const open = (tier, duration, addonIds = []) => {
    const addons = ADDONS.filter((a) => addonIds.includes(a.id) && a.price);
    const base = tier.durations[duration.id];
    const addonTotal = addons.reduce((s, a) => s + a.price, 0);
    setOrder({ tier, duration, addons, total: base + addonTotal });
  };
  const close = () => setOrder(null);
  return (
    <CheckoutCtx.Provider value={{ order, open, close }}>
      {children}
      <CheckoutModal open={!!order} order={order} onClose={close} />
    </CheckoutCtx.Provider>
  );
}

// =====================================================================
// Brand
// =====================================================================
function Brand({ size = "sm" }) {
  return (
    <span className={"brand brand-" + size}>
      <span className="brand-b">B</span>
      <span className="brand-rest">asedMTA</span>
    </span>
  );
}

// =====================================================================
// Nav
// =====================================================================
function useScrolled(threshold = 40) {
  const [s, setS] = useState(false);
  useEffect(() => {
    const f = () => setS(window.scrollY > threshold);
    f();
    window.addEventListener("scroll", f, { passive: true });
    return () => window.removeEventListener("scroll", f);
  }, [threshold]);
  return s;
}

function Nav() {
  const scrolled = useScrolled();
  const { open } = useCheckout();
  const quickBuy = (e) => {
    e.preventDefault();
    const tier = TIERS.find((t) => t.id === "pro");
    const duration = DURATIONS.find((d) => d.id === "30d");
    open(tier, duration, []);
  };
  return (
    <nav className={"nav" + (scrolled ? " scrolled" : "")}>
      <div className="nav-inner">
        <a href="#top" className="brand-link"><Brand /></a>
        <div className="nav-links">
          <a href="#capabilities">Tiers</a>
          <a href="#compare">Compare</a>
          <a href="#demo">Demo</a>
          <a href="#pricing">Pricing</a>
          <a href="#status">Check key</a>
          <a href="#faq">FAQ</a>
          <a href="tos.html">Terms</a>
        </div>
        <div className="nav-spacer" />
        <div className="nav-cta">
          <a className="btn" href="#demo">Demo</a>
          <a className="btn btn-primary" href="#" onClick={quickBuy}>Get a key</a>
        </div>
      </div>
    </nav>
  );
}

// =====================================================================
// Typed hero title
// =====================================================================
function TypedHeroTitle() {
  const PART1 = "Advanced Scripting";
  const PART2 = "Utilities for MTA:SA";
  const total = PART1.length + PART2.length;
  const [n, setN] = useState(0);
  useEffect(() => {
    if (n >= total) return;
    // Human-feeling rhythm: faster mid-word, slower on spaces and at the line break
    const just = (n === 0 ? PART1[0] : (n <= PART1.length ? PART1[n - 1] : PART2[n - PART1.length - 1])) || "";
    let delay = 38 + Math.random() * 30;
    if (just === " ") delay += 40;
    if (n === PART1.length) delay = 260; // pause before line 2
    const t = setTimeout(() => setN(n + 1), delay);
    return () => clearTimeout(t);
  }, [n, total]);
  const a = PART1.slice(0, Math.min(n, PART1.length));
  const b = n > PART1.length ? PART2.slice(0, n - PART1.length) : "";
  const done = n >= total;
  return (
    <h1 className="reveal in delay-1 typed">
      <span className="t-line">
        {a}
        {n < PART1.length && <span className="caret" />}
      </span>
      {n >= PART1.length && (
        <span className="t-line">
          <span className="accent">{b}</span>
          <span className={"caret" + (done ? " done" : "")} />
        </span>
      )}
    </h1>
  );
}

// =====================================================================
// Hero
// =====================================================================
const HERO_SLIDES = [
  "site/img/esp-targeting.png",
  "site/img/esp-1.png",
  "site/img/esp-2.png",
  "site/img/esp-3.png",
];

function Hero() {
  return (
    <header className="hero hero-cinema" id="top">
      <div className="hero-bg-img">
        <img src="site/img/esp-wireframe.png" alt="" />
      </div>
      <div className="hero-vignette" />
      <div className="container hero-content">
        <div className="hero-copy">
          <TypedHeroTitle />
          <p className="hero-sub reveal in delay-2">
            BasedMTA is a tiered scripting utility for Multi&nbsp;Theft&nbsp;Auto: San&nbsp;Andreas. Built to a standard most tools in this space don&rsquo;t reach.
          </p>
          <div className="hero-ctas reveal in delay-3">
            <a className="btn btn-primary btn-lg" href="#pricing">Get a key</a>
            <a className="btn btn-lg btn-ghost" href="#demo">Try the demo</a>
          </div>

          <div className="hero-meta reveal in delay-3">
            <div className="hero-meta-row">
              <div className="hero-meta-cell">
                <span className="k">Version</span>
                <span className="v">v1.6.24103</span>
              </div>
              <div className="hero-meta-cell">
                <span className="k">Payment</span>
                <span className="v">BTC  XMR  USDT  ETH  LTC</span>
              </div>
              <div className="hero-meta-cell">
                <span className="k">Status</span>
                <span className="v ok"><span className="live-dot" /> Live</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="hero-fade" />
    </header>
  );
}

// =====================================================================
// Process strip - "How it works" reassurance
// =====================================================================
const PROCESS_STEPS = [
  {
    n: "01",
    t: "Checkout in crypto",
    d: "Pick a tier and a duration. Pay in BTC, XMR, USDT, ETH or LTC. Every invoice is capped at $30.",
    icon: (
      <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
        <rect x="2.5" y="5" width="17" height="12" rx="1.5" stroke="currentColor" strokeWidth="1.4"/>
        <path d="M2.5 9H19.5" stroke="currentColor" strokeWidth="1.4"/>
        <path d="M5 13H9" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
      </svg>
    ),
  },
  {
    n: "02",
    t: "Bind your key",
    d: "Open a Discord ticket with your invoice ID. We bind the key to your HWID and deliver the DLL in minutes.",
    icon: (
      <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
        <rect x="4" y="9.5" width="14" height="9.5" rx="1.5" stroke="currentColor" strokeWidth="1.4"/>
        <path d="M6.5 9.5V6.5a4.5 4.5 0 0 1 9 0v3" stroke="currentColor" strokeWidth="1.4"/>
        <circle cx="11" cy="14" r="1.1" fill="currentColor"/>
      </svg>
    ),
  },
  {
    n: "03",
    t: "Inject and play",
    d: "Inject the DLL, launch MTA, press Insert to open the menu. Identity rotates on every launch.",
    icon: (
      <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
        <path d="M5 3.5H13L17 7.5V18.5H5V3.5Z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/>
        <path d="M13 3.5V7.5H17" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/>
        <path d="M7.5 11.5H14.5M7.5 14H12" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
      </svg>
    ),
  },
];

function ProcessStrip() {
  return (
    <div className="process-strip reveal">
      {PROCESS_STEPS.map((s, i) => (
        <React.Fragment key={s.n}>
          <div className="process-step">
            <div className="process-step-head">
              <span className="process-step-n">{s.n}</span>
              <span className="process-step-icon">{s.icon}</span>
            </div>
            <div className="process-step-title">{s.t}</div>
            <div className="process-step-desc">{s.d}</div>
          </div>
          {i < PROCESS_STEPS.length - 1 && <div className="process-rule" aria-hidden="true" />}
        </React.Fragment>
      ))}
    </div>
  );
}

// =====================================================================
// Capability rows
// =====================================================================
function CapabilityRow({ tier, flip, extra }) {
  return (
    <div className={"cap-row" + (flip ? " flip" : "")}>
      <div className="cap-visual reveal">
        <CapVisual visual={tier.visual} />
      </div>
      <div className="cap-copy reveal delay-1">
        <div className="cap-tier-label" data-tier={tier.id}>{tier.name} tier</div>
        <h3 className="cap-title">{tier.tagline}</h3>
        <div className="cap-cols">
          <div>
            <div className="cap-col-label">Included</div>
            <ul className="cap-list pros">
              {tier.pros.map((f, i) => (
                <li key={i}>
                  <span className="feat-t">{f.t}</span>
                  {f.d && <span className="feat-d">{f.d}</span>}
                </li>
              ))}
            </ul>
          </div>
          {tier.cons.length > 0 && (
            <div>
              <div className="cap-col-label">Not in this tier</div>
              <ul className="cap-list cons">
                {tier.cons.map((f, i) => (
                  <li key={i}>
                    <span className="feat-t">{f.t}</span>
                    {f.d && <span className="feat-d">{f.d}</span>}
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
        {extra}
      </div>
    </div>
  );
}

function CapVisual({ visual }) {
  if (visual.type === "image-single") {
    return (
      <div className="cap-shot">
        <span className="cap-shot-tag">{visual.primary.tag}</span>
        <img src={visual.primary.src} alt="" loading="lazy" />
      </div>
    );
  }
  if (visual.type === "image-pair") {
    return (
      <div className="cap-pair">
        <div className="cap-shot main">
          <span className="cap-shot-tag">{visual.primary.tag}</span>
          <img src={visual.primary.src} alt="" loading="lazy" />
        </div>
        <div className="cap-shot sub">
          <span className="cap-shot-tag">{visual.secondary.tag}</span>
          <img src={visual.secondary.src} alt="" loading="lazy" />
        </div>
      </div>
    );
  }
  if (visual.type === "code") {
    return <CapCodeVisual visual={visual} />;
  }
  if (visual.type === "fleet") {
    return <CapFleetVisual />;
  }
  return null;
}

function CapCodeVisual({ visual }) {
  return (
    <div className="cap-code">
      <div className="cap-code-bar">
        <div className="cap-code-dots"><span /><span /><span /></div>
        <div className="cap-code-name">{visual.filename}</div>
        <div className="cap-code-meta">{visual.meta}</div>
      </div>
      <div className="cap-code-body">
        {visual.lines.map((l, i) => (
          <div key={i} className="cap-code-line">
            <span className="ln">{String(i + 1).padStart(2, " ")}</span>
            <span className="src" dangerouslySetInnerHTML={{ __html: l.src || "&nbsp;" }} />
          </div>
        ))}
      </div>
      <div className="cap-code-foot">
        <span>{visual.footLeft}</span>
        <span className="ok"><span className="live-dot" /> {visual.footRight}</span>
      </div>
    </div>
  );
}

const FLEET_BOTS = [
  { id: "01", ip: "216.58.x.x",  region: "us-west-1", ping: 41 },
  { id: "02", ip: "172.217.x.x", region: "us-west-1", ping: 38 },
  { id: "03", ip: "104.18.x.x",  region: "us-east-1", ping: 54 },
  { id: "04", ip: "91.108.x.x",  region: "eu-west-1", ping: 67 },
  { id: "05", ip: "13.107.x.x",  region: "eu-west-1", ping: 71 },
  { id: "06", ip: "151.101.x.x", region: "eu-cent-1", ping: 79 },
  { id: "07", ip: "23.235.x.x",  region: "ap-south",  ping: 132 },
  { id: "08", ip: "199.232.x.x", region: "ap-south",  ping: 128 },
];

function CapFleetVisual() {
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setTick((x) => x + 1), 1400);
    return () => clearInterval(t);
  }, []);
  const jitter = (base) => base + ((tick * 7 + base) % 11) - 5;
  return (
    <div className="cap-fleet">
      <div className="cap-fleet-bar">
        <div className="cap-fleet-bar-l">
          <span className="cap-fleet-title">FLEET</span>
          <span className="cap-fleet-sub">srv-fleet-01.basedmta</span>
        </div>
        <div className="cap-fleet-bar-r">
          <span className="cap-fleet-stat"><span className="k">UP</span><span className="v">8 / 8</span></span>
          <span className="cap-fleet-stat"><span className="k">UPTIME</span><span className="v">99.8%</span></span>
          <span className="cap-fleet-stat"><span className="k">SHARED</span><span className="v ok">SYNCED</span></span>
        </div>
      </div>
      <div className="cap-fleet-head">
        <span>NODE</span>
        <span>PROXY</span>
        <span>REGION</span>
        <span>PING</span>
        <span>STATE</span>
      </div>
      <div className="cap-fleet-rows">
        {FLEET_BOTS.map((b) => (
          <div key={b.id} className="cap-fleet-row">
            <span className="node">bot-{b.id}</span>
            <span className="ip">{b.ip}</span>
            <span className="region">{b.region}</span>
            <span className="ping">{jitter(b.ping)}<span className="unit">ms</span></span>
            <span className="state"><span className="live-dot" /> live</span>
          </div>
        ))}
      </div>
      <div className="cap-fleet-foot">
        <span>blackboard / shared targeting</span>
        <span className="ok"><span className="live-dot" /> packets in sync</span>
      </div>
    </div>
  );
}

// =====================================================================
// Feature matrix
// =====================================================================
const MATRIX_GROUPS = [
  {
    g: "Visuals",
    rows: [
      { f: "Aimbot",                 b: true, p: true, v: true },
      { f: "ESP",                    b: true, p: true, v: true },
      { f: "Chams and radar",        b: true, p: true, v: true },
      { f: "Spoofer",                b: true, p: true, v: true },
    ],
  },
  {
    g: "Scripting",
    rows: [
      { f: "Lua executor (bytecode VM)", b: false, p: true, v: true },
      { f: "Autoexec",                   b: false, p: true, v: true },
      { f: "Resource code injection",    b: false, p: true, v: true },
      { f: "Decompiler and dumper",      b: false, p: true, v: true },
      { f: "PktLib",                     b: false, p: true, v: true },
    ],
  },
  {
    g: "Fleet and exploits",
    rows: [
      { f: "Bot fleet",              b: false, p: false, v: "up to 20" },
      { f: "Swarm coverage",         b: false, p: false, v: true },
      { f: "Private exploits",       b: false, p: false, v: true },
    ],
  },
];

function MatrixCell({ v }) {
  if (v === true)  return <span className="mx-yes" aria-label="included"><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2.5 7.5L5.5 10.5L11.5 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg></span>;
  if (v === false) return <span className="mx-no"  aria-label="not included">-</span>;
  return <span className="mx-note">{v}</span>;
}

function FeatureMatrix() {
  const { open } = useCheckout();
  const buy = (id) => {
    const tier = TIERS.find((t) => t.id === id);
    const duration = DURATIONS.find((d) => d.id === "30d");
    open(tier, duration, []);
  };
  return (
    <div className="matrix reveal">
      <div className="matrix-head">
        <div className="matrix-h-feature">
          <span className="matrix-title">Compare tiers</span>
        </div>
        <div className="matrix-h-tier" data-tier="basic">
          <span className="t-name">Basic</span>
          <span className="t-price">from $1 / day</span>
        </div>
        <div className="matrix-h-tier featured" data-tier="pro">
          <span className="t-name">Pro</span>
          <span className="t-price">from $2 / day</span>
        </div>
        <div className="matrix-h-tier" data-tier="vip">
          <span className="t-name">VIP</span>
          <span className="t-price">from $3 / day</span>
        </div>
      </div>
      {MATRIX_GROUPS.map((g, gi) => (
        <div key={gi} className="matrix-group">
          <div className="matrix-group-label">{g.g}</div>
          {g.rows.map((r, ri) => (
            <div key={ri} className="matrix-row">
              <div className="matrix-feature">{r.f}</div>
              <div className="matrix-cell"><MatrixCell v={r.b} /></div>
              <div className="matrix-cell featured"><MatrixCell v={r.p} /></div>
              <div className="matrix-cell"><MatrixCell v={r.v} /></div>
            </div>
          ))}
        </div>
      ))}
      <div className="matrix-foot">
        <div className="matrix-foot-label">Pick a tier</div>
        <div className="matrix-foot-cta">
          <button className="btn" onClick={() => buy("basic")}>Get Basic</button>
        </div>
        <div className="matrix-foot-cta featured">
          <button className="btn btn-primary" onClick={() => buy("pro")}>Get Pro</button>
        </div>
        <div className="matrix-foot-cta">
          <button className="btn" onClick={() => buy("vip")}>Get VIP</button>
        </div>
      </div>
    </div>
  );
}

// =====================================================================
// Pricing
// =====================================================================
function PricingCard({ tier, duration }) {
  const cardRef = useRef(null);
  const onMouseMove = (e) => {
    if (!cardRef.current) return;
    const r = cardRef.current.getBoundingClientRect();
    cardRef.current.style.setProperty("--mx", `${e.clientX - r.left}px`);
    cardRef.current.style.setProperty("--my", `${e.clientY - r.top}px`);
  };
  const { open } = useCheckout();
  const [addons, setAddons] = useState({});
  const [shownDuration, setShownDuration] = useState(duration);
  const [animPhase, setAnimPhase] = useState("idle");
  const [shownTotalDuration, setShownTotalDuration] = useState(duration);
  const [totalAnimPhase, setTotalAnimPhase] = useState("idle");

  useEffect(() => {
    if (duration === shownDuration) return;
    setAnimPhase("out");
    const priceSwap = setTimeout(() => { setShownDuration(duration); setAnimPhase("in"); }, 140);
    const priceDone = setTimeout(() => setAnimPhase("idle"), 290);
    const totalOut  = setTimeout(() => setTotalAnimPhase("out"), 50);
    const totalSwap = setTimeout(() => { setShownTotalDuration(duration); setTotalAnimPhase("in"); }, 190);
    const totalDone = setTimeout(() => setTotalAnimPhase("idle"), 340);
    return () => {
      clearTimeout(priceSwap); clearTimeout(priceDone);
      clearTimeout(totalOut); clearTimeout(totalSwap); clearTimeout(totalDone);
    };
  }, [duration]);

  const base = tier.durations[shownDuration];
  const totalBase = tier.durations[shownTotalDuration];
  const addonTotal = Object.entries(addons).reduce((sum, [id, on]) => {
    if (!on) return sum;
    const a = ADDONS.find((x) => x.id === id);
    return sum + (a && a.price ? a.price : 0);
  }, 0);
  const total = totalBase + addonTotal;
  const durLabel = DURATIONS.find((d) => d.id === shownDuration)?.label ?? "";

  const toggleAddon = (id, contact) => {
    if (contact) return;
    setAddons((a) => ({ ...a, [id]: !a[id] }));
  };

  const checkout = () => {
    const enabledAddonIds = Object.entries(addons).filter(([_, on]) => on).map(([id]) => id);
    const dur = DURATIONS.find((d) => d.id === shownTotalDuration);
    open(tier, dur, enabledAddonIds);
  };

  const visibleAddons = ADDONS.filter((a) => !a.vipOnly || tier.id === "vip");

  return (
    <div ref={cardRef} onMouseMove={onMouseMove} className={`pcv2 ${tier.id} ${tier.featured ? "featured" : ""} reveal`}>
      {tier.featured && <span className="pcv2-badge">Most popular</span>}
      <div className="pcv2-head">
        <div className="pcv2-tier" data-tier={tier.id}>{tier.name}</div>
      </div>
      <p className="pcv2-tagline">{tier.tagline}</p>

      <div className={`pcv2-price-display phase-${animPhase}`}>
        <span className="pcv2-price-big"><span className="cur">$</span>{base}</span>
        <span className="pcv2-price-unit">/ {durLabel}</span>
      </div>

      <div className="pcv2-divider" />

      <div className="pcv2-features">
        <div className="pcv2-section-label">Includes</div>
        <ul className="pcv2-list pros">
          {tier.pros.map((f, i) => (
            <li key={i}>
              <span className="feat-t">{f.t}</span>
              {f.d && <span className="feat-d">{f.d}</span>}
            </li>
          ))}
        </ul>
        {tier.cons.length > 0 && (
          <React.Fragment>
            <div className="pcv2-section-label">Not in this tier</div>
            <ul className="pcv2-list cons">
              {tier.cons.map((f, i) => (
                <li key={i}>
                  <span className="feat-t">{f.t}</span>
                  {f.d && <span className="feat-d">{f.d}</span>}
                </li>
              ))}
            </ul>
          </React.Fragment>
        )}
      </div>

      {visibleAddons.length > 0 && (
        <div className="pcv2-addons-open">
          <div className="pcv2-section-label">Add-ons</div>
          {visibleAddons.map((a) => {
            if (a.contact) {
              return (
                <p key={a.id} className="pcv2-addon-disclaimer">
                  {a.name} available on request. Open a <a href="https://discord.gg/basedmta" target="_blank" rel="noopener">Discord ticket</a>.
                </p>
              );
            }
            const added = !!addons[a.id];
            return (
              <div
                key={a.id}
                className={"pcv2-addon" + (added ? " added" : "")}
                onClick={() => toggleAddon(a.id, a.contact)}
              >
                <div className="pcv2-addon-meta">
                  <div className="pcv2-addon-name">{a.name}</div>
                  <div className="pcv2-addon-sub">{a.sub}</div>
                </div>
                <span className="pcv2-addon-price">+${a.price}</span>
                <span className="pcv2-addon-action">{added ? "Added" : "Add"}</span>
              </div>
            );
          })}
        </div>
      )}

      <div className="pcv2-foot">
        <div className="pcv2-total">
          <span className="lbl">Total</span>
          <span className={`val phase-${totalAnimPhase}`}><span className="cur">$</span>{total}</span>
        </div>
        <button className="btn btn-primary pcv2-cta" onClick={checkout}>Checkout</button>
      </div>
    </div>
  );
}

function PricingMatrix() {
  const [duration, setDuration] = useState("30d");
  return (
    <div className="pricing-shell">
      <div className="dur-toggle">
        {DURATIONS.map((d) => (
          <button
            key={d.id}
            className={"dur-tab" + (duration === d.id ? " active" : "")}
            onClick={() => setDuration(d.id)}
          >
            {d.label}
          </button>
        ))}
      </div>
      <div className="pricing-grid reveal-stagger">
        {TIERS.map((t) => <PricingCard key={t.id} tier={t} duration={duration} />)}
      </div>
      <div className="hwid-row reveal">
        <div className="hwid-row-left">
          <span className="hwid-row-name">HWID Reset</span>
          <span className="hwid-row-sub">First 14 days of resets included free with any active key.</span>
        </div>
        <div className="hwid-row-right">
          <span className="hwid-row-price"><span className="cur">$</span>2</span>
          <span className="hwid-row-unit">per reset after quota</span>
        </div>
        <a className="btn hwid-row-cta" href="https://discord.gg/basedmta" target="_blank" rel="noopener">Open ticket</a>
      </div>
    </div>
  );
}

// =====================================================================
// Demo
// =====================================================================
function DemoSection() {
  return (
    <React.Fragment>
      <div className="s-head">
        <div className="s-head-stack">
          <h2 className="section-title reveal">Try it in the browser.</h2>
        </div>
        <p className="s-head-aside reveal delay-1">
          Same ImGui shell that ships with the DLL. Click anything.
        </p>
      </div>

      <div className="demo-frame reveal">
        <div className="demo-mount">
          <BasedMTA initialTab="aimbot" hideClose />
        </div>
      </div>

      <p className="demo-disclaimer">
        Prototype. All data is simulated.
      </p>
    </React.Fragment>
  );
}

// =====================================================================
// FAQ
// =====================================================================
const FAQ_ITEMS = [
  { q: "How does payment work?",        a: "Crypto only. BTC, XMR, USDT (TRC-20 or ERC-20), ETH, LTC. Each invoice covers one tier for 1, 7, or 30 days and is capped at $30. On every launch, the DLL receives a session-bound capability ticket that authorizes your tier." },
  { q: "What does HWID-bound mean?",    a: "Your license is tied to a single machine's HWID. After 14 days of usage you may reset your HWID for free. Before that, resets cost $2 each." },
  { q: "Will I get banned using this?", a: "We protect against any hardware detection so you remain anonymous. Identity rotates on every launch and the DLL signature is randomized per session." },
  { q: "What operating systems are supported?", a: "Windows is currently the only supported OS. Linux support may be added if you say \"pretty please\"." },
  { q: "Can I resell BasedMTA?",        a: "Yes. Open a ticket on our Discord for reselling terms." },
  { q: "Are updates included?",         a: "Updates are free for the entire duration of any active key." },
  { q: "What is your refund policy?",   a: "No refunds. All sales are final." },
  { q: "How do I reach support?",       a: "Open a ticket on our Discord for billing, license key delivery, HWID resets, and contact-priced add-ons. Keep your invoice ID private; do not share it publicly." },
];

function FAQ() {
  const [open, setOpen] = useState(0);
  return (
    <div className="faq-grid reveal-stagger">
      {FAQ_ITEMS.map((item, i) => (
        <div key={i} className={"faq-item reveal" + (open === i ? " open" : "")} onClick={() => setOpen(open === i ? -1 : i)}>
          <div className="faq-q">
            <span className="num">{String(i + 1).padStart(2, "0")}</span>
            <span>{item.q}</span>
            <span className="icon">+</span>
          </div>
          <div className="faq-a">{item.a}</div>
        </div>
      ))}
    </div>
  );
}

// =====================================================================
// Key status checker
//   Public, read-only license oracle. POST /v1/license/status with
//   {key, captcha} served same-origin via the Caddy reverse-proxy (no
//   CORS, no secrets in the page). Server-side rate limit is 0.5/s
//   burst 10, and every successful query consumes a verified hCaptcha
//   token, so brute-force probing is both rate-bounded AND has to
//   solve a fresh challenge per attempt.
// =====================================================================
const KEYCHK_API_BASE  = (typeof window !== "undefined" && window.BMTA_API_BASE) || "";
const HCAPTCHA_SITEKEY = (typeof window !== "undefined" && window.BMTA_HCAPTCHA_SITE_KEY) || "";

function fmtTs(unix) {
  if (!unix || unix <= 0) return null;
  try {
    return new Date(unix * 1000).toLocaleString(undefined, {
      year: "numeric", month: "short", day: "numeric",
      hour: "2-digit", minute: "2-digit",
    });
  } catch (_) { return null; }
}

function fmtRemaining(expiresUnix) {
  if (!expiresUnix || expiresUnix <= 0) return null;
  const secs = expiresUnix - Math.floor(Date.now() / 1000);
  if (secs <= 0) return null;
  const days  = Math.floor(secs / 86400);
  const hours = Math.floor((secs % 86400) / 3600);
  const mins  = Math.floor((secs % 3600) / 60);
  if (days  >= 2) return `${days} days remaining`;
  if (days  === 1) return `1 day ${hours}h remaining`;
  if (hours >= 1) return `${hours}h ${mins}m remaining`;
  return `${mins}m remaining`;
}

function maskKey(k) {
  if (!k || k.length < 16) return k || "";
  return k.slice(0, 8) + "…" + k.slice(-8);
}

const KEYCHK_TONES = {
  Active:  { tone: "ok",   title: "Active",   blurb: "This key is live." },
  Unused:  { tone: "info", title: "Unused",   blurb: "Valid key, not activated yet. The clock starts on first launch." },
  Expired: { tone: "warn", title: "Expired",  blurb: "This key's duration has elapsed. Grab a new one any time." },
  Revoked: { tone: "bad",  title: "Revoked",  blurb: "This key has been revoked or banned and can't be used." },
  Invalid: { tone: "bad",  title: "Not found", blurb: "No license matches that value. Double-check for typos." },
};

function KeyStatusChecker() {
  const [key, setKey] = useState("");
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [checkedKey, setCheckedKey] = useState("");
  const [err, setErr] = useState("");
  const captchaHostRef = useRef(null);
  const widgetIdRef = useRef(null);
  const [captchaReady, setCaptchaReady] = useState(false);

  // Render the invisible hCaptcha widget once. The script tag in
  // index.html loads js.hcaptcha.com/1/api.js asynchronously, so we
  // poll briefly until window.hcaptcha is defined.
  useEffect(() => {
    if (!HCAPTCHA_SITEKEY) return;
    let cancelled = false;
    let tries = 0;
    const attempt = () => {
      if (cancelled) return;
      const hc = window.hcaptcha;
      if (!hc || !captchaHostRef.current) {
        if (tries++ < 50) setTimeout(attempt, 200);
        return;
      }
      try {
        widgetIdRef.current = hc.render(captchaHostRef.current, {
          sitekey: HCAPTCHA_SITEKEY,
          size: "invisible",
        });
        setCaptchaReady(true);
      } catch (_) {
        if (tries++ < 5) setTimeout(attempt, 400);
      }
    };
    attempt();
    return () => { cancelled = true; };
  }, []);

  const normalized = key.trim().toLowerCase();
  const looksValid = /^[0-9a-f]{64}$/.test(normalized);

  const check = async () => {
    setErr("");
    setResult(null);
    setCheckedKey("");
    if (!looksValid) {
      setErr("A license key is exactly 64 hexadecimal characters (0-9, a-f).");
      return;
    }
    setLoading(true);

    // Get a fresh hCaptcha token. With size="invisible" this shows no
    // challenge for legitimate users and pops a challenge modal only
    // when hCaptcha thinks the visitor is suspicious.
    let token = "";
    const hc = window.hcaptcha;
    if (HCAPTCHA_SITEKEY && hc && widgetIdRef.current !== null) {
      try {
        const exec = await hc.execute(widgetIdRef.current, { async: true });
        token = exec && exec.response ? exec.response : "";
      } catch (_) {
        setErr("Captcha check was cancelled. Try again.");
        setLoading(false);
        return;
      }
    } else if (HCAPTCHA_SITEKEY) {
      setErr("Captcha is still loading. Try again in a second.");
      setLoading(false);
      return;
    }

    try {
      const resp = await fetch(KEYCHK_API_BASE + "/v1/license/status", {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({ key: normalized, captcha: token }),
      });
      const data = await resp.json().catch(() => ({}));
      if (resp.status === 429) {
        setErr("Too many checks. Wait a few seconds and try again.");
      } else if (data && data.error === "captcha_failed") {
        setErr("Captcha verification failed. Please try again.");
      } else if (!resp.ok && !data.Status) {
        setErr(data.error || "Couldn't check that key right now. Try again shortly.");
      } else {
        setResult(data);
        setCheckedKey(normalized);
      }
    } catch (_) {
      setErr("Network error. Check your connection and try again.");
    }
    try { if (hc && widgetIdRef.current !== null) hc.reset(widgetIdRef.current); } catch (_) {}
    setLoading(false);
  };

  const onKeyDown = (e) => { if (e.key === "Enter") check(); };

  const meta = result ? (KEYCHK_TONES[result.Status] || { tone: "info", title: result.Status || "Unknown", blurb: "" }) : null;
  const expiryStr    = result ? fmtTs(result.Expires) : null;
  const activatedStr = result ? fmtTs(result.ActivatedAt) : null;
  const remaining    = result && result.Status === "Active" ? fmtRemaining(result.Expires) : null;
  const durationLbl  = result && result.DurationDays > 0 ? `${result.DurationDays}-day key` : null;

  return (
    <div className="keychk reveal">
      <div className="keychk-form">
        <input
          type="text"
          className={"keychk-input" + (err ? " err" : "") + (looksValid ? " ok" : "")}
          placeholder="Paste your 64-character license key"
          value={key}
          onChange={(e) => { setKey(e.target.value); if (err) setErr(""); }}
          onKeyDown={onKeyDown}
          autoComplete="off"
          autoCapitalize="off"
          autoCorrect="off"
          spellCheck="false"
          maxLength={80}
          aria-label="License key"
        />
        <button
          className="btn btn-primary keychk-btn"
          onClick={check}
          disabled={loading || !looksValid}
        >
          {loading ? "Checking…" : "Check status"}
        </button>
      </div>
      <div className="keychk-hint">
        Read-only. Protected by hCaptcha. We never store what you paste here.
      </div>
      {/* Invisible hCaptcha host — only ever visible if hCaptcha decides to challenge */}
      <div ref={captchaHostRef} className="keychk-captcha-host" aria-hidden="true" />
      {err && <div className="keychk-err">{err}</div>}
      {result && meta && (
        <div className={"keychk-result " + meta.tone}>
          <div className="keychk-result-head">
            <span className="keychk-badge"><span className="live-dot" />{meta.title}</span>
            {result.Tier && result.Tier !== "Unknown" && (
              <span className="keychk-tier">{result.Tier} tier</span>
            )}
          </div>
          {meta.blurb && <p className="keychk-result-blurb">{meta.blurb}</p>}
          <div className="keychk-result-rows">
            {checkedKey && (
              <div className="keychk-result-row">
                <span className="k">Key</span>
                <span className="v mono">{maskKey(checkedKey)}</span>
              </div>
            )}
            {durationLbl && (
              <div className="keychk-result-row">
                <span className="k">Duration</span>
                <span className="v">{durationLbl}</span>
              </div>
            )}
            {activatedStr && (
              <div className="keychk-result-row">
                <span className="k">Activated</span>
                <span className="v mono">{activatedStr}</span>
              </div>
            )}
            {expiryStr && (
              <div className="keychk-result-row">
                <span className="k">{result.Status === "Expired" ? "Expired" : "Expires"}</span>
                <span className="v mono">{expiryStr}</span>
              </div>
            )}
            {remaining && (
              <div className="keychk-result-row">
                <span className="k">Remaining</span>
                <span className="v">{remaining}</span>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

// =====================================================================
// Footer
// =====================================================================
function Footer() {
  return (
    <footer className="footer">
      <div className="container-wide">
        <div className="footer-grid">
          <div className="footer-brand">
            <Brand size="lg" />
            <p className="blurb">
              A precision scripting utility for Multi&nbsp;Theft&nbsp;Auto: San&nbsp;Andreas.
            </p>
          </div>
          <div className="footer-col">
            <h4>Product</h4>
            <ul>
              <li><a href="#capabilities">Tiers</a></li>
              <li><a href="#demo">Live demo</a></li>
              <li><a href="#pricing">Pricing</a></li>
              <li><a href="#">Changelog</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Support</h4>
            <ul>
              <li><a href="https://discord.gg/basedmta" target="_blank" rel="noopener">Discord</a></li>
              <li><a href="https://discord.gg/basedmta" target="_blank" rel="noopener">HWID reset (ticket)</a></li>
              <li><a href="https://discord.gg/basedmta" target="_blank" rel="noopener">Open a ticket</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Legal</h4>
            <ul>
              <li><a href="tos.html">Terms of Service</a></li>
              <li><a href="tos.html#04">Refund policy</a></li>
              <li><a href="tos.html#09">Privacy</a></li>
              <li><a href="tos.html#10">Reselling</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>(c) Based Software. All rights reserved.</span>
          <span>v1.6 build 24103</span>
        </div>
      </div>
    </footer>
  );
}

// =====================================================================
// Tweaks
// =====================================================================
function TweaksWrapper({ children }) {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useEffect(() => {
    document.documentElement.setAttribute("data-accent", t.accent || "blue");
  }, [t.accent]);
  return (
    <React.Fragment>
      {children}
      <TweaksPanel title="Tweaks">
        <TweakSection title="Accent">
          <TweakColor
            label="Accent color"
            value={t.accent}
            onChange={(v) => setTweak("accent", v)}
            options={[
              { value: "blue",  color: "#5b9eff" },
              { value: "amber", color: "#e0a458" },
              { value: "green", color: "#4dd699" },
              { value: "mono",  color: "#e7e9ee" },
            ]}
          />
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
}

// =====================================================================
// Page
// =====================================================================
function Page() {
  // Smooth anchor scroll
  useEffect(() => {
    const ease = (t) => t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
    const scrollTo = (target) => {
      const navH = document.querySelector(".nav")?.offsetHeight || 0;
      const start = window.scrollY;
      const end = target.getBoundingClientRect().top + start - navH - 16;
      const duration = 700;
      let startTime = null;
      const step = (now) => {
        if (!startTime) startTime = now;
        const elapsed = Math.min((now - startTime) / duration, 1);
        window.scrollTo(0, start + (end - start) * ease(elapsed));
        if (elapsed < 1) requestAnimationFrame(step);
      };
      requestAnimationFrame(step);
    };
    const onClick = (e) => {
      const a = e.target.closest("a[href^='#']");
      if (!a) return;
      const href = a.getAttribute("href");
      if (href === "#" || href.length < 2) return;
      const id = href.slice(1);
      const el = document.getElementById(id);
      if (!el) return;
      e.preventDefault();
      scrollTo(el);
    };
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);

  // Reveal animations
  useEffect(() => {
    const obs = new IntersectionObserver(
      (entries) => {
        for (const e of entries) {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            obs.unobserve(e.target);
          }
        }
      },
      { threshold: 0.06, rootMargin: "0px 0px -5% 0px" }
    );
    document.querySelectorAll(".reveal").forEach((el) => {
      const inView = el.getBoundingClientRect().top < window.innerHeight * 0.92;
      if (inView) {
        el.classList.add("in");
      } else {
        el.classList.add("preanim");
        obs.observe(el);
      }
    });
    document.querySelectorAll(".reveal-stagger").forEach((parent) => {
      Array.from(parent.children).forEach((child, i) => {
        child.style.transitionDelay = `${i * 60}ms`;
      });
    });
    return () => obs.disconnect();
  }, []);

  return (
    <TweaksWrapper>
      <CheckoutProvider>
        <Nav />
        <Hero />

        <section id="process" className="s s-tight">
          <div className="container">
            <ProcessStrip />
          </div>
        </section>

        <section id="capabilities" className="s">
          <div className="container">
            <div className="s-head">
              <div className="s-head-stack">
                <h2 className="section-title reveal">
                  Three tiers.
                </h2>
              </div>
              <p className="s-head-aside reveal delay-1">
                Start with visual coverage. Move up when you need the Lua runtime, bots, or the exploit suite.
              </p>
            </div>
            <div className="cap-rows">
              <CapabilityRow tier={TIERS[0]} flip={false} />
              <CapabilityRow tier={TIERS[1]} flip={true} />
              <CapabilityRow tier={TIERS[2]} flip={false} />
            </div>
          </div>
        </section>

        <section id="compare" className="s s-tight">
          <div className="container">
            <FeatureMatrix />
          </div>
        </section>

        <section id="demo" className="s">
          <div className="container">
            <DemoSection />
          </div>
        </section>

        <section id="pricing" className="s">
          <div className="container">
            <div className="s-head">
              <div className="s-head-stack">
                <h2 className="section-title reveal">
                  Pay by the day.
                </h2>
              </div>
              <p className="s-head-aside reveal delay-1">
                Pick a tier, pick a duration. Crypto only. Every invoice is capped at $30.
              </p>
            </div>
            <div className="reveal"><PricingMatrix /></div>

            <div className="pay-strip reveal" style={{ marginTop: 28 }}>
              <div className="pay-strip-label">Accepted</div>
              <div className="pay-strip-coins">
                {["BTC", "XMR", "USDT", "ETH", "LTC"].map((c) => (
                  <span key={c} className="coin"><CoinGlyph c={c} />{c}</span>
                ))}
              </div>
              <div className="pay-strip-label" style={{ color: "var(--ok)" }}><span className="live-dot" /> Live</div>
            </div>
          </div>
        </section>

        <section id="status" className="s s-tight">
          <div className="container">
            <div className="s-head">
              <div className="s-head-stack">
                <h2 className="section-title reveal">
                  Check your key.
                </h2>
              </div>
              <p className="s-head-aside reveal delay-1">
                Already bought? Paste your license key to see its status, tier, and expiry. No login required.
              </p>
            </div>
            <KeyStatusChecker />
          </div>
        </section>

        <section id="faq" className="s">
          <div className="container">
            <div className="s-head">
              <div className="s-head-stack">
                <h2 className="section-title reveal">
                  Questions
                </h2>
              </div>
              <p className="s-head-aside reveal delay-1">
                For anything not covered, <a href="https://discord.gg/basedmta" target="_blank" rel="noopener" style={{ color: "var(--accent)" }}>open a Discord ticket</a>.
              </p>
            </div>
            <div className="reveal"><FAQ /></div>
          </div>
        </section>

        <Footer />
      </CheckoutProvider>
    </TweaksWrapper>
  );
}

function CoinGlyph({ c }) {
  const props = { width: 14, height: 14, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: 1.4 };
  const map = {
    BTC:  <svg {...props}><circle cx="8" cy="8" r="7"/><path d="M6 4v8M7 4h2.5a1.5 1.5 0 0 1 0 3H7M7 7h3a1.5 1.5 0 0 1 0 3H7"/></svg>,
    XMR:  <svg {...props}><circle cx="8" cy="8" r="7"/><path d="M2 12 8 4l6 8M5 12l3-4 3 4"/></svg>,
    USDT: <svg {...props}><circle cx="8" cy="8" r="7"/><path d="M4 6h8M8 6v6"/></svg>,
    ETH:  <svg {...props}><path d="M8 1 3 8l5 3 5-3-5-7zM3 9l5 6 5-6-5 3-5-3z"/></svg>,
    LTC:  <svg {...props}><circle cx="8" cy="8" r="7"/><path d="M6 4 5 11l6-2M4 8h7"/></svg>,
  };
  return map[c] || null;
}

ReactDOM.createRoot(document.getElementById("root")).render(<Page />);
