// Header (shared) + Hero + Ticker + Featured games + Demos

function Header({ active }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const links = [
    { href: "index.html", label: "Home", id: "home" },
    { href: "games.html", label: "Games", id: "games" },
    { href: "cv.html", label: "CV", id: "cv" },
    { href: "press.html", label: "Press", id: "press" },
    { href: "contact.html", label: "Contact", id: "contact" },
  ];

  return (
    <nav className={`topnav ${scrolled ? "scrolled" : ""}`}>
      <a href="index.html" className="topnav-brand">
        <window.MartenMark size={32} animate={false} />
        <span>MAPLE MARTEN</span>
      </a>
      <div className="topnav-links">
        {links.map((l) => (
          <a key={l.id} href={l.href} className={`topnav-link ${active === l.id ? "active" : ""}`}>{l.label}</a>
        ))}
      </div>
    </nav>
  );
}

function Hero() {
  return (
    <section className="hero" data-screen-label="01 Hero">
      <div className="hero-grid-bg" />
      <div className="hero-scanlines" />
      <div className="hero-inner">
        <div className="hero-text">
          <div className="hero-eyebrow">
            <span>Vancouver, BC · Est. 2024</span>
          </div>
          <h1 className="hero-title">
            <span className="l1">MAPLE</span>
            <span className="l1">MARTEN</span>
            <span className="l2">studios.</span>
          </h1>
          <p className="hero-tagline">
            Fiercely Canadian · <em>Seriously fun.</em>
          </p>
          <div className="hero-ctas">
            <a href="games.html" className="btn btn-primary">
              Play our games <span className="arrow">→</span>
            </a>
            <a href="cv.html" className="btn btn-ghost">
              Hire the engineer <span className="arrow">→</span>
            </a>
          </div>
        </div>
        <div className="hero-side">
          <div style={{ display: "flex", justifyContent: "center", marginBottom: 8 }}>
            <window.MartenMark size={260} />
          </div>
          <div className="hero-card">
            <div className="hero-card-label">
              <span>// NOW BUILDING</span>
              <span style={{ color: "var(--maple)" }}>● LIVE</span>
            </div>
            <div className="hero-card-value">
              <strong>Loonie Trouble</strong> — first studio title, in active development. Vertical slice 2026.
            </div>
          </div>
          <div className="hero-card">
            <div className="hero-card-label">
              <span>// AVAILABLE</span>
            </div>
            <div className="hero-card-value">
              Open to senior engineering roles. <strong>C++ · Python · Cloud.</strong>
            </div>
          </div>
        </div>
      </div>
      <div className="hero-bottom">
        <span>// 50.4452°N, 123.7314°W</span>
        <div className="scroll-indicator">
          <span>SCROLL</span>
          <div className="line" />
        </div>
        <span>v2.6.04 / 2026</span>
      </div>
    </section>
  );
}

function Ticker() {
  const items = [
    ["BUILDING", "Loonie Trouble — first studio title"],
    ["LATEST COMMIT", "feat: AI pathfinding now respects fog-of-war"],
    ["LISTENING TO", "Disasterpeace — Hyper Light Drifter OST"],
    ["READING", "Game Engine Architecture, 3rd ed."],
    ["BREW", "Phillips Blue Buck"],
    ["FORECAST", "Vancouver — 11°C, light rain"],
    ["UPTIME", "5+ years shipping production systems"],
    ["MOOD", "Caffeinated and hopeful"],
  ];
  const repeated = [...items, ...items];
  return (
    <div className="ticker">
      <div className="ticker-track">
        {repeated.map(([k, v], i) => (
          <span key={i}>
            <span className="dot" />
            <span className="key">{k}</span>
            <span>{v}</span>
          </span>
        ))}
      </div>
    </div>
  );
}

function GameCard({ game, wishlisted, onWishlist, href }) {
  const Cover = game.cover;
  return (
    <article className="game-card">
      <a href={href} style={{ display: "contents", color: "inherit", textDecoration: "none" }}>
        <div className="game-card-art">
          <Cover />
          <div className={`game-card-status ${game.statusClass}`}>
            ● {game.statusLabel}
          </div>
        </div>
        <div className="game-card-body">
          <div className="game-card-tags">
            {game.tags.map((t) => <span key={t} className="tag">{t}</span>)}
          </div>
          <h3 className="game-card-title">{game.title}</h3>
          <p className="game-card-desc">{game.desc}</p>
        </div>
      </a>
      <div className="game-card-cta" style={{ padding: "0 24px 24px" }}>
        {game.fundingNeeded ? (
          <button
            className="wishlist-btn"
            onClick={(e) => { e.stopPropagation(); window.location = "contact.html?topic=funding&game=" + encodeURIComponent(game.title); }}
            style={{ background: "var(--amber)", color: "#1A1410", borderColor: "var(--amber)" }}
          >
            <svg className="check" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M8 1 L8 15 M1 8 L15 8" />
            </svg>
            Back this project
          </button>
        ) : (
          <button
            className={`wishlist-btn ${wishlisted ? "added" : ""}`}
            onClick={(e) => { e.stopPropagation(); onWishlist(game.id); }}
          >
            {wishlisted ? (
              <>
                <svg className="check" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M3 8 L7 12 L13 4" />
                </svg>
                Wishlisted
              </>
            ) : (
              <>
                <svg className="check" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M8 14s-6-4-6-9a3 3 0 0 1 6-1 3 3 0 0 1 6 1c0 5-6 9-6 9Z" />
                </svg>
                Wishlist
              </>
            )}
          </button>
        )}
        <a href={href} className="devlog-btn" title="Game page">→</a>
      </div>
    </article>
  );
}

const GAMES = [
  {
    id: "loonies",
    title: "Loonie Trouble",
    statusLabel: "IN DEVELOPMENT",
    statusClass: "dev",
    tags: ["Shooter", "Survival", "Comedy"],
    desc: "Survival shooter in the Canadian wilderness. Precision mechanics meet wild humor and waterfowl with grudges.",
    cover: () => window.CoverLoonies(),
    href: "games/loonie-trouble.html",
    fundingNeeded: false,
  },
  {
    id: "echoes",
    title: "Echoes of Tomorrow",
    statusLabel: "SEEKING FUNDING",
    statusClass: "funding",
    tags: ["Strategy", "Survival", "Sci-Fi"],
    desc: "Lead the survivors of New Aurora, uncover the conspiracy, and decide if humanity deserves a second chance.",
    cover: () => window.CoverEchoes(),
    href: "games/echoes-of-tomorrow.html",
    fundingNeeded: true,
  },
  {
    id: "grocer",
    title: "Go Go Grocer",
    statusLabel: "SEEKING FUNDING",
    statusClass: "funding",
    tags: ["Simulation", "Physics", "Arcade"],
    desc: "High-octane shopper sim. Custom physics-based delivery mechanics where time is money and the cart has opinions.",
    cover: () => window.CoverGrocer(),
    href: "games/go-go-grocer.html",
    fundingNeeded: true,
  },
];

function GamesSection({ heading = true }) {
  const [wishlist, setWishlist] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem("mm_wl") || "[]"); } catch { return []; }
  });
  const toggle = (id) => {
    setWishlist((w) => {
      const next = w.includes(id) ? w.filter(x => x !== id) : [...w, id];
      try { localStorage.setItem("mm_wl", JSON.stringify(next)); } catch {}
      return next;
    });
  };

  return (
    <section className="section" id="games" data-screen-label="02 Games">
      <div className="container">
        {heading && (
          <>
            <div className="section-label"><span>02 / OUR TITLES</span></div>
            <h2 className="section-title">Studio <em>titles.</em></h2>
            <p className="section-sub">
              One in active development. Two seeking funding. All built with stubborn attention to feel.
            </p>
          </>
        )}
        <div className="games-grid">
          {GAMES.map((g) => (
            <GameCard
              key={g.id}
              game={g}
              href={g.href}
              wishlisted={wishlist.includes(g.id)}
              onWishlist={toggle}
            />
          ))}
        </div>
      </div>
    </section>
  );
}

function DemosSection() {
  return (
    <section className="section" id="demos" data-screen-label="03 Demos" style={{ background: "var(--bg-2)", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
      <div className="container">
        <div className="section-label"><span>03 / TECHNICAL SHOWCASE</span></div>
        <h2 className="section-title">Engineering <em>under the hood.</em></h2>
        <p className="section-sub">
          The systems work that powers both the studio and the day job — performance, scale, strongly-typed plumbing.
        </p>
        <div className="demos-grid">
          <article className="demo-card">
            <div className="demo-card-num">DEMO 01</div>
            <h3 className="demo-card-title">Real-Time Simulation Engine</h3>
            <div className="demo-card-stack">C++ · Unreal Engine 5 · Event-Driven Arch.</div>
            <p className="demo-card-desc">
              Engineered a performant C++ subsystem for real-time object state management, handling entity lifecycles and memory optimization. C++ bindings drive a reactive UI layer with sub-frame data flow.
            </p>
            <div className="demo-stats">
              <div><div className="demo-stat-num">10k+</div><div className="demo-stat-label">Entities / Frame</div></div>
              <div><div className="demo-stat-num">&lt;2ms</div><div className="demo-stat-label">State Tick</div></div>
              <div><div className="demo-stat-num">Zero</div><div className="demo-stat-label">Allocs / Tick</div></div>
            </div>
          </article>
          <article className="demo-card">
            <div className="demo-card-num">DEMO 02</div>
            <h3 className="demo-card-title">High-Volume Transaction Engine</h3>
            <div className="demo-card-stack">Python · GCP · Gradient Boosting</div>
            <p className="demo-card-desc">
              Production transaction processor handling 50M+ daily events, with gradient-boosting fraud detection wired directly into the request path. Reduced fraud losses by 23% without latency regression.
            </p>
            <div className="demo-stats">
              <div><div className="demo-stat-num">50M+</div><div className="demo-stat-label">Daily TPS</div></div>
              <div><div className="demo-stat-num">−23%</div><div className="demo-stat-label">Fraud Losses</div></div>
              <div><div className="demo-stat-num">99.97%</div><div className="demo-stat-label">Uptime</div></div>
            </div>
          </article>
        </div>
      </div>
    </section>
  );
}

window.Header = Header;
window.Hero = Hero;
window.Ticker = Ticker;
window.GamesSection = GamesSection;
window.DemosSection = DemosSection;
window.GAMES = GAMES;
