const { useState, useEffect, useRef } = React;

/* ============================================================
   DEFAULT CONTENT — fallback if API fetch fails
   ============================================================ */
const DEFAULT_CONTENT = {
  hero: {
    tag: "Last played <strong>2h ago</strong> · +0.42 BTC",
    title_line1: "Roll with",
    title_line2: "the <em>house.</em>",
    lede: "I play crypto casinos so you don't have to <em>lose first.</em> Hand-picked drops, verified mirrors, and the only promo codes that <em>still pay out.</em>",
  },
  stats: [
    { v: '$2.4<span class="small">M</span>', l: "Lifetime wagered" },
    { v: '48<sup>K</sup>', l: "Subscribers across platforms" },
    { v: "x4,210", l: "Biggest verified multiplier" },
  ],
  casinos: [
    { name:"NovaSpin", tag:"Originals · Slots · Live", desc:"My main casino. Provably-fair house games, <em>instant BTC payouts</em>, and they actually answer support tickets within the hour.", code:"VAULT", bonus:"200% / 5 BTC", rank:"01", tone:"tone-a", siteUrl:"novaspin.io", refUrl:"#", mirrors:[{url:"novaspin.io",refUrl:"#",status:"live",note:"primary"},{url:"novaspin.cc",refUrl:"#",status:"live",note:"backup"},{url:"n1.novaspin.net",refUrl:"#",status:"warn",note:"slow"}] },
    { name:"Stakeline", tag:"Originals · Crash · Plinko", desc:"Lowest house edge I've found on crash. Fully <em>on-chain seed verification</em> — you can audit any round I play after the fact.", code:"VAULTDROP", bonus:"15% Cashback", rank:"02", tone:"tone-b", siteUrl:"stakeline.com", refUrl:"#", mirrors:[{url:"stakeline.com",refUrl:"#",status:"live",note:"primary"},{url:"stakeline.bet",refUrl:"#",status:"live",note:"backup"}] },
  ],
  socials: [
    { key:"twitter",  handle:"@staketel",       sub:"48.2K followers",  icon:"twitter",  url:"#" },
    { key:"telegram", handle:"@staketel_drop",  sub:"12.4K members",    icon:"telegram", url:"#" },
    { key:"youtube",  handle:"/staketel",       sub:"94K subscribers",  icon:"youtube",  url:"#" },
    { key:"kick",     handle:"/staketel.live",  sub:"Live · 2.1K view", icon:"kick",     url:"#" },
  ],
  footer: {
    blurb: "Independent creator. <em>Not a casino operator.</em> Bonuses are tested before they're shared. 18+ only — gamble in amounts you'd <em>happily lose.</em>",
    legal: "© 2026 STAKETEL · 18+ · play responsibly",
  },
  faq: [
    { q: "How do I use a promo code?", a: "Click the casino banner, then paste the code during signup or in the cashier." },
    { q: "Are these casinos safe?", a: "Yes — I only list casinos I personally play on, all with provably fair games and instant withdrawals." },
  ],
};

const html = (s) => ({ __html: String(s || "") });

// GA4 event helper — safe even before gtag loads
const track = (name, params) => {
  if (typeof window !== "undefined" && typeof window.track === "function") {
    window.track(name, params);
  }
};

/* ============================================================
   ICONS
   ============================================================ */
const Icon = {
  twitter: () => (
    <svg viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2H21.5l-7.5 8.57L23 22h-6.797l-5.32-6.94L4.8 22H1.54l8.02-9.17L1 2h6.92l4.81 6.36L18.244 2Zm-1.193 18.155h1.838L7.05 3.745H5.08l11.97 16.41Z"/></svg>
  ),
  instagram: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/></svg>
  ),
  telegram: () => (
    <svg viewBox="0 0 24 24" fill="currentColor"><path d="M22 4.5 18.5 20.2c-.3 1.2-1 1.5-2 1l-5.5-4.05-2.7 2.6c-.3.3-.55.55-1.15.55l.4-5.75 10.55-9.55c.45-.4-.1-.62-.7-.22L4.6 12.55l-5.55-1.75c-1.2-.4-1.25-1.2.25-1.8L21 2.7c1-.4 1.9.25 1.7 1.8Z" transform="translate(1 0)"/></svg>
  ),
  discord: () => (
    <svg viewBox="0 0 24 24" fill="currentColor"><path d="M20.3 4.4A19 19 0 0 0 15.7 3l-.3.5a14 14 0 0 0-6.8 0L8.3 3a18.9 18.9 0 0 0-4.6 1.4C.9 8.6 0 12.7.4 16.8c1.9 1.4 3.8 2.2 5.6 2.8.4-.6.8-1.2 1.1-1.9-.6-.2-1.3-.5-1.9-.9.2-.1.3-.2.5-.3 3.6 1.7 7.5 1.7 11.1 0l.5.3c-.6.4-1.2.6-1.9.9.3.6.7 1.3 1.1 1.9 1.8-.6 3.7-1.4 5.6-2.8.5-4.7-.8-8.8-3.7-12.4ZM8.5 14.4c-1.1 0-2-1-2-2.3 0-1.2.9-2.3 2-2.3s2 1 2 2.3-.9 2.3-2 2.3Zm7.1 0c-1.1 0-2-1-2-2.3 0-1.2.9-2.3 2-2.3s2 1 2 2.3-.9 2.3-2 2.3Z"/></svg>
  ),
  youtube: () => (
    <svg viewBox="0 0 24 24" fill="currentColor"><path d="M23 7.5a3 3 0 0 0-2.1-2.1C19 5 12 5 12 5s-7 0-8.9.4A3 3 0 0 0 1 7.5C.6 9.5.6 12 .6 12s0 2.6.4 4.5a3 3 0 0 0 2.1 2.1C5 19 12 19 12 19s7 0 8.9-.4a3 3 0 0 0 2.1-2.1c.4-1.9.4-4.5.4-4.5s0-2.5-.4-4.5ZM10 15.5v-7l6 3.5-6 3.5Z"/></svg>
  ),
  kick: () => (
    <svg viewBox="0 0 24 24" fill="currentColor"><path d="M3 3h5v6h2V6h2V3h5v3h-2v3h-2v3h2v3h2v3h-5v-3h-2v-3H8v6H3V3Z"/></svg>
  ),
  external: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17 17 7"/><path d="M9 7h8v8"/></svg>
  ),
  arrow: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14"/><path d="m13 5 7 7-7 7"/></svg>
  ),
  copy: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>
  ),
  check: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5 9-11"/></svg>
  ),
};

/* ============================================================
   NAV
   ============================================================ */
function Nav({ socials }) {
  const order = ["twitter","telegram","youtube","instagram"];
  const navIcons = order
    .map((k) => (socials || []).find((s) => s.icon === k))
    .filter(Boolean);
  return (
    <header className="nav">
      <div className="brand">Staketel<em>.</em></div>
      <div className="nav-icons">
        {navIcons.map((s) => {
          const I = Icon[s.icon] || (() => null);
          return (
            <a className="icon-btn" href={s.url || "#"} target="_blank" rel="noopener noreferrer" aria-label={s.icon} key={s.icon}
               onClick={() => track("social_click", { icon: s.icon, handle: s.handle, location: "nav" })}><I/></a>
          );
        })}
      </div>
    </header>
  );
}

/* ============================================================
   HERO
   ============================================================ */
function Hero({ hero }) {
  const cta1 = hero.cta1 || { text: "See the casinos", url: "#casinos" };
  const cta2 = hero.cta2 || { text: "Latest session", url: "#sessions" };
  const isInternal = (u) => !u || u.startsWith("#") || u.startsWith("/");
  const targetAttrs = (u) =>
    isInternal(u) ? {} : { target: "_blank", rel: "noopener noreferrer" };

  return (
    <section className="hero" data-screen-label="01 Hero">
      <div className="wrap">
        <div className="hero-copy">
          <div className="hero-tag">
            <span className="pulse"></span>
            <span dangerouslySetInnerHTML={html(hero.tag)} />
          </div>
          <h1 className="display">
            <span dangerouslySetInnerHTML={html(hero.title_line1)} />
            <br/>
            <span dangerouslySetInnerHTML={html(hero.title_line2)} />
          </h1>
          <p className="hero-lede" dangerouslySetInnerHTML={html(hero.lede)} />
          <div className="hero-cta">
            {cta1.text && (
              <a className="btn" href={cta1.url || "#"} {...targetAttrs(cta1.url)}
                 onClick={() => track("hero_cta_click", { slot: 1, text: cta1.text, url: cta1.url })}>
                {cta1.text} <Icon.arrow/>
              </a>
            )}
            {cta2.text && (
              <a className="btn btn-ghost" href={cta2.url || "#"} {...targetAttrs(cta2.url)}
                 onClick={() => track("hero_cta_click", { slot: 2, text: cta2.text, url: cta2.url })}>
                {cta2.text}
              </a>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   STATS
   ============================================================ */
function Stats({ stats }) {
  return (
    <section className="wrap" data-screen-label="02 Stats">
      <div className="stats">
        {(stats || []).map((s, i) => (
          <div className="stat" key={i}>
            <div className="v" dangerouslySetInnerHTML={html(s.v)} />
            <div className="l">{s.l}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ============================================================
   CASINOS
   ============================================================ */
function CasinoCard({ c }) {
  const [copied, setCopied] = useState(false);

  function copy() {
    try {
      navigator.clipboard.writeText(c.code);
    } catch (e) {}
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  }

  const mirrors = c.mirrors || [];
  const ctaHref = c.refUrl || c.url || "#";
  const ctaLabel = c.siteUrl || c.name;

  return (
    <div className="casino-card" data-comment-anchor={`casino-${c.name}`}>
      <a className={`casino-banner ${c.tone || "tone-a"}`} href={ctaHref} target="_blank" rel="noopener noreferrer"
         onClick={() => track("casino_click", { casino: c.name, site_url: c.siteUrl, ref_url: c.refUrl, rank: c.rank })}>
        <div className="banner-glow"></div>
        <div className="frost"></div>
        <div className="live-pill"><span className="d"></span>Live</div>
        <div className="rank"><strong>{c.rank}</strong> / partner</div>
        <div className="stamp">{c.name}<em>.</em></div>
        <div className="banner-cta">
          <span className="domain">{ctaLabel}</span>
          <span className="go">Go <Icon.arrow/></span>
        </div>
      </a>

      <div className="casino-body">
        <div className="casino-name-row">
          <div>
            <div className="casino-name">{c.name}<em>.</em></div>
            <div className="casino-tag">{c.tag}</div>
          </div>
          <div className="casino-bonus">
            <div className="k">Bonus</div>
            <div className="v">{c.bonus}</div>
          </div>
        </div>

        <p className="casino-desc" dangerouslySetInnerHTML={html(c.desc)} />

        <div className="code-row">
          <div>
            <div className="label">Promo code</div>
            <div className="code">{c.code}</div>
          </div>
          <button className="copy-btn" onClick={() => { copy(); track("promo_code_copy", { casino: c.name, code: c.code }); }}>
            {copied ? <><Icon.check/> Copied</> : <><Icon.copy/> Copy</>}
          </button>
        </div>

        {mirrors.length > 0 && (
          <div className="mirrors-block">
            <div className="head">
              <div className="h">Working mirrors</div>
              <div className="meta">Updated <strong>2 min ago</strong></div>
            </div>
            <div className="mirrors">
              {mirrors.map((m, i) => (
                <a className="mirror" key={i} href={m.refUrl || m.url || "#"} target="_blank" rel="noopener noreferrer"
                   onClick={() => track("mirror_click", { casino: c.name, mirror: m.url, status: m.status, note: m.note })}>
                  <span className="url">
                    <Icon.external/> {m.url}
                  </span>
                  <span className={`status ${m.status === "warn" ? "warn" : m.status === "dead" ? "warn" : ""}`}>
                    <span className="d"></span>{m.note}
                  </span>
                </a>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function Casinos({ casinos }) {
  const list = casinos || [];
  return (
    <section className="wrap" data-screen-label="03 Casinos" id="casinos">
      <div className="casinos">
        <div className="casinos-head">
          <h2>The <em>casinos.</em></h2>
          <div className="right">
            <div className="eyebrow"><span className="dot"></span>{list.length} active partners</div>
            <p>Every casino I actually <em>play</em> — with my code, the working mirrors,
            and a one-paragraph <em>honest take</em> on why it's here.</p>
          </div>
        </div>

        <div className="casino-grid">
          {list.map((c, i) => <CasinoCard key={c.name + i} c={c}/>)}
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   TERMINAL — live wins (animation only, no editable data)
   ============================================================ */
const LIVE_FEED = [
  { tag: "win",  user: "0x4a…91c2",  game: "Plinko",    amt: "+ 4.82 BTC"   },
  { tag: "win",  user: "phantom.42", game: "Crash",     amt: "+ 18,400 USDT"},
  { tag: "spin", user: "0xfee…d10",  game: "Dice",      amt: "+ 0.91 BTC"   },
  { tag: "win",  user: "drago.eth",  game: "Mines",     amt: "+ 92.5 SOL"   },
  { tag: "win",  user: "0xbe…a7f",   game: "Roulette",  amt: "+ 21,000 USDC"},
  { tag: "win",  user: "lambo.sol",  game: "Blackjack", amt: "+ 3.4 ETH"    },
  { tag: "spin", user: "satoshi.kr", game: "Slots",     amt: "+ 740 USDT"   },
];

function Terminal() {
  const [visible, setVisible] = useState(3);
  useEffect(() => {
    const t = setInterval(() => {
      setVisible((v) => (v >= LIVE_FEED.length ? 3 : v + 1));
    }, 1400);
    return () => clearInterval(t);
  }, []);
  return (
    <section className="wrap" data-screen-label="04 Terminal">
      <div className="terminal-section">
        <div className="terminal-grid">
          <div>
            <h2>Watch once.<br/><em>Win it back.</em></h2>
            <p>
              Every wager I make is logged, hashed, and replayable. <em>No staged wins,</em>
              no fake balances — what you see is <em>what hit the chain.</em>
            </p>
          </div>

          <div className="terminal">
            <div className="terminal-head">
              <span className="dot"></span><span className="dot"></span><span className="dot"></span>
              <span className="title">staketel@live — wins.log</span>
            </div>
            <div className="terminal-body">
              <div className="tline">
                <span className="prompt">{'>'}</span>
                <span className="cmd">staketel watch --live --hash-verify</span>
              </div>
              <div className="tline">
                <span className="tag">[ init ]</span>
                <span className="user">play session</span>
                <span className="game">started · seed locked</span>
                <span className="ok">ok</span>
              </div>
              {LIVE_FEED.slice(0, visible).map((it, i) => (
                <div className="tline" key={i}>
                  <span className="tag">[ {it.tag} ]</span>
                  <span className="user">{it.user}</span>
                  <span className="game">on {it.game}</span>
                  <span className="amt">{it.amt}</span>
                </div>
              ))}
              <div className="tline cursor">
                <span className="prompt">{'>'}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   SOCIALS
   ============================================================ */
function Socials({ socials }) {
  return (
    <section className="wrap" data-screen-label="05 Socials">
      <div className="socials">
        <div className="socials-head">
          <h2>Find me<br/><em>everywhere.</em></h2>
          <p>Daily session recaps, hourly mirror updates, and the <em>alpha drops first</em>
          on Telegram. Nowhere else, <em>no DMs, ever.</em></p>
        </div>
        <div className="socials-grid">
          {(socials || []).map((s, i) => {
            const I = Icon[s.icon] || (() => null);
            return (
              <a className="social-card" href={s.url || "#"} target="_blank" rel="noopener noreferrer" key={s.key || s.handle || i}
                 onClick={() => track("social_click", { icon: s.icon, handle: s.handle, location: "footer" })}>
                <div className="icon-wrap"><I/></div>
                <span className="arrow"><Icon.external/></span>
                <div className="meta">
                  <div className="h">{s.handle}</div>
                  <div className="s">{s.sub}</div>
                </div>
              </a>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   FAQ
   ============================================================ */
function FAQ({ items }) {
  if (!items || !items.length) return null;
  return (
    <section className="wrap" id="faq" data-screen-label="FAQ">
      <div className="faq-section">
        <div className="faq-head">
          <h2>Questions <em>&amp; answers.</em></h2>
          <p>The stuff people <em>actually ask</em> before they sign up.</p>
        </div>
        <div className="faq-list">
          {items.map((f, i) => (
            <details className="faq-item" key={i} open={i === 0}>
              <summary>{f.q}</summary>
              <div className="faq-answer" dangerouslySetInnerHTML={html(f.a)} />
            </details>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   FOOTER
   ============================================================ */
function Footer({ footer }) {
  return (
    <footer className="footer" data-screen-label="06 Footer">
      <div className="wrap">
        <div className="footer-top">
          <div className="footer-mega">staketel<em>.</em></div>
          <p className="footer-blurb" dangerouslySetInnerHTML={html(footer.blurb)} />
        </div>

        <div className="footer-bottom">
          <div className="legal">{footer.legal}</div>
          <div className="crypto-chips">
            <span className="crypto-chip"><span className="d"></span>BTC</span>
            <span className="crypto-chip"><span className="d"></span>ETH</span>
            <span className="crypto-chip"><span className="d"></span>SOL</span>
            <span className="crypto-chip"><span className="d"></span>USDT</span>
            <span className="crypto-chip"><span className="d"></span>LTC</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ============================================================
   APP
   ============================================================ */
function mergeContent(data) {
  if (!data || typeof data !== "object") return DEFAULT_CONTENT;
  return {
    hero: { ...DEFAULT_CONTENT.hero, ...(data.hero || {}) },
    stats: data.stats && data.stats.length ? data.stats : DEFAULT_CONTENT.stats,
    casinos: data.casinos || DEFAULT_CONTENT.casinos,
    socials: data.socials || DEFAULT_CONTENT.socials,
    footer: { ...DEFAULT_CONTENT.footer, ...(data.footer || {}) },
    faq: data.faq || DEFAULT_CONTENT.faq,
  };
}

function App() {
  const initial = (typeof window !== "undefined" && window.__INITIAL_CONTENT__) || DEFAULT_CONTENT;
  const [content, setContent] = useState(initial);

  // If we somehow rendered before fetch completed, still try to refresh once.
  useEffect(() => {
    if (window.__INITIAL_CONTENT__) return;
    let alive = true;
    fetch("/api/content?t=" + Date.now())
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => {
        if (alive && data) setContent(mergeContent(data));
      })
      .catch(() => {});
    return () => { alive = false; };
  }, []);

  return (
    <>
      <div className="ambient">
        <div className="orb a"></div>
        <div className="orb b"></div>
        <div className="orb c"></div>
        <div className="orb d"></div>
      </div>
      <div className="shimmer-veil"></div>
      <div className="grain"></div>
      <Nav socials={content.socials}/>
      <main>
        <Casinos casinos={content.casinos}/>
        <Hero hero={content.hero}/>
        <Stats stats={content.stats}/>
        <Terminal/>
        <FAQ items={content.faq}/>
        <Socials socials={content.socials}/>
      </main>
      <Footer footer={content.footer}/>
    </>
  );
}

// Fetch content FIRST, then render — avoids flash of default content
(async function init() {
  let data = null;
  try {
    const r = await fetch("/api/content?t=" + Date.now());
    if (r.ok) data = await r.json();
  } catch (e) {}
  window.__INITIAL_CONTENT__ = mergeContent(data);
  ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
})();
