/* ============ EXPERIMENTERS PAGE COMPONENTS ============
   Hero · Manifesto · Tiers + Perks · Projects · University · Arcade · Cross-links
   ====================================================== */

const { useState, useRef, useEffect, useCallback } = React;

/* ---------- Experimenter subscription checkout ----------
   Calls the create-checkout-session edge function and redirects to the
   Stripe Checkout URL. Requires a logged-in session — opens the auth
   modal if the visitor isn't signed in yet. */
const PB_FN_BASE = "https://vbfwzpztnvfktydozgir.supabase.co/functions/v1";
const PB_ANON = "sb_publishable_5Xq5SHTnGvhp6mkauFXBHA_B_MEU0FX";

async function startExperimenterCheckout(cadence) {
  const pbAuth = window.pbAuth;
  if (!pbAuth) { window.alert("Still loading — try again in a moment."); return; }
  const session = pbAuth.getSession && pbAuth.getSession();
  if (!session || !session.access_token) {
    if (pbAuth.showAuthModal) pbAuth.showAuthModal();
    return;
  }
  try {
    const res = await fetch(PB_FN_BASE + "/create-checkout-session", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "apikey": PB_ANON,
        "Authorization": "Bearer " + session.access_token,
      },
      body: JSON.stringify({ cadence: cadence === "annual" ? "annual" : "monthly" }),
    });
    const data = await res.json().catch(() => ({}));
    if (data && data.url) { window.location.href = data.url; return; }
    window.alert((data && data.error) || "Could not start checkout. Please try again.");
  } catch (_e) {
    window.alert("Could not start checkout. Please try again.");
  }
}

/* ---------- Free-tier email capture ----------
   Registers the visitor on the free PickBits Substack tier (no payment).
   Mirrors the university-gate / experimenters-banner capture: Substack
   free endpoint + Supabase lead capture, and stamps pb_university_email
   so the University email gate recognises them. */
function subscribeFreeTier(email) {
  const v = (email || "").trim();
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return false;
  try { localStorage.setItem("pb_university_email", v); } catch (_e) {}
  const url = window.location.href;
  const ref = (typeof document !== "undefined" && document.referrer) || "";
  try {
    fetch("https://pickbitsai.substack.com/api/v1/free", {
      method: "POST",
      mode: "no-cors",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        email: v, first_url: url, first_referrer: ref,
        current_url: url, current_referrer: ref, referral_code: "", source: "embed",
      }),
    }).catch(() => {});
  } catch (_e) {}
  try {
    fetch(PB_FN_BASE + "/capture-lead", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "apikey": PB_ANON,
        "Authorization": "Bearer " + PB_ANON,
      },
      body: JSON.stringify({
        email: v, source: "experimenters_free_tier",
        substack_optin: true, page: "/experimenters", referrer: ref,
      }),
    }).catch(() => {});
  } catch (_e) {}
  return true;
}

function ExpFreeCapture() {
  const [email, setEmail] = useState("");
  const [state, setState] = useState("idle"); // idle | error | done
  const onSubmit = (e) => {
    e.preventDefault();
    setState(subscribeFreeTier(email) ? "done" : "error");
  };
  if (state === "done") {
    return <p className="exp-free-done">✓ You're on the free list — check your inbox to confirm.</p>;
  }
  return (
    <form className="exp-free-capture" onSubmit={onSubmit} noValidate>
      <input
        type="email"
        className="exp-free-input"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="you@example.com"
        aria-label="Email for free updates"
      />
      <button type="submit" className="btn ghost">Get free updates</button>
      {state === "error" && <span className="exp-free-err">Enter a valid email address.</span>}
    </form>
  );
}

/* ---------- Hero ---------- */
function ExpHero() {
  const stats = window.EXP_HERO_STATS || {};
  const projects = stats.projects ?? (window.EXP_PROJECTS || []).length;
  const arcadeGames = stats.arcadeGames
    ?? (window.EXP_ARCADE || []).filter((g) => g.status !== 'tool').length;
  const universityTracks = stats.universityTracks ?? 5;
  const experimenters = stats.experimenters ?? 0;

  const heroStats = [
    { num: projects,         lbl: 'Projects' },
    { num: arcadeGames,      lbl: 'Arcade Games' },
    { num: universityTracks, lbl: 'University Tracks' },
    { num: experimenters,    lbl: 'Experimenters' }
  ];

  return (
    <section className="exp-hero" data-screen-label="01 Hero">
      <div className="exp-hero-bg" aria-hidden="true">
        <div className="exp-hero-grid"></div>
        <div className="exp-hero-scan"></div>
      </div>
      <div className="wrap exp-hero-wrap">
        <h1 className="exp-hero-title">
          The <span className="accent-text">Experimenters</span>
        </h1>
        <p className="exp-hero-sub">
          Not influencers. Not theorists. <strong>Practitioners.</strong> The room where everything we build gets shared, broken, fixed, and reshipped. Every premium feature on every project — yours. Every public repo — yours to fork.
        </p>
        <div className="exp-hero-stats">
          {heroStats.map((s) => (
            <div className="stat" key={s.lbl}>
              <span className="num">{s.num}</span>
              <span className="lbl">{s.lbl}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Manifesto ---------- */
function ExpManifesto({ style }) {
  if (style === "compact") {
    return (
      <section className="exp-manifesto compact" data-screen-label="02 Manifesto">
        <div className="wrap">
          <p className="manifesto-line">
            <span className="eyebrow">// manifesto</span>
            <span>We <em>are</em> the tutorials. We ship ugly prototypes, break them in public, fix them live, share the receipts. <strong>If you've ever started a project at midnight because you had an idea and an AI that could keep up — you're already one of us.</strong></span>
          </p>
        </div>
      </section>
    );
  }
  return (
    <section className="exp-manifesto split" data-screen-label="02 Manifesto">
      <div className="wrap exp-manifesto-grid">
        <div className="exp-manifesto-left">
          <div className="eyebrow">// manifesto</div>
          <h2 className="h-display">
            We ship.<br/>
            They <em>talk</em>.
          </h2>
        </div>
        <div className="exp-manifesto-right">
          <p>
            While everyone else debates which AI tool is best, we're building with <strong>all of them</strong>. We don't wait for tutorials — we <em>are</em> the tutorials. We ship ugly prototypes, break them in public, fix them live, and share the receipts.
          </p>
          <p className="exp-manifesto-close">
            <strong>If you've ever started a project at midnight because you had an idea and an AI that could keep up — you're already one of us.</strong>
          </p>
        </div>
      </div>
    </section>
  );
}

/* ---------- Generic carousel scaffold ----------
   Snap-scrolling track + arrow + dot navigation. Renders children
   as cards (one per child). */
function ExpCarousel({ id, ariaLabel, eyebrow, heading, sub, headRight, cards, dotAccent = "var(--accent)" }) {
  const trackRef = useRef(null);
  const [idx, setIdx] = useState(0);

  const goTo = useCallback((i) => {
    const track = trackRef.current;
    if (!track) return;
    const clamped = Math.max(0, Math.min(cards.length - 1, i));
    const card = track.children[clamped];
    if (!card) return;
    const target = card.offsetLeft - track.offsetLeft;
    const prevSnap = track.style.scrollSnapType;
    track.style.scrollSnapType = 'none';
    track.scrollLeft = target;
    requestAnimationFrame(() => { track.style.scrollSnapType = prevSnap || ''; });
    setIdx(clamped);
  }, [cards.length]);

  useEffect(() => {
    const track = trackRef.current;
    if (!track) return;
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const center = track.scrollLeft + track.clientWidth / 2;
        let nearest = 0;
        let nearestD = Infinity;
        for (let i = 0; i < track.children.length; i++) {
          const c = track.children[i];
          const mid = c.offsetLeft + c.clientWidth / 2 - track.offsetLeft;
          const d = Math.abs(mid - center);
          if (d < nearestD) { nearestD = d; nearest = i; }
        }
        setIdx(nearest);
      });
    };
    track.addEventListener("scroll", onScroll, { passive: true });
    return () => { track.removeEventListener("scroll", onScroll); cancelAnimationFrame(raf); };
  }, []);

  const onKeyDown = (e) => {
    if (e.key === "ArrowRight") { e.preventDefault(); goTo(idx + 1); }
    else if (e.key === "ArrowLeft") { e.preventDefault(); goTo(idx - 1); }
  };

  return (
    <div className="exp-carousel-wrap">
      <div className="section-head exp-carousel-head">
        <div className="left">
          {eyebrow && <div className="eyebrow">{eyebrow}</div>}
          {heading && <h2 className="h-display">{heading}</h2>}
          {sub && <p>{sub}</p>}
        </div>
        <div className="exp-carousel-head-right">
          {headRight}
          <div className="exp-carousel-controls">
            <button className="exp-arrow" aria-label="Previous" onClick={() => goTo(idx - 1)} disabled={idx === 0}>
              <span aria-hidden="true">‹</span>
            </button>
            <span className="exp-counter">
              <span className="exp-counter-current">{String(idx + 1).padStart(2, "0")}</span>
              <span className="exp-counter-sep">/</span>
              <span className="exp-counter-total">{String(cards.length).padStart(2, "0")}</span>
            </span>
            <button className="exp-arrow" aria-label="Next" onClick={() => goTo(idx + 1)} disabled={idx === cards.length - 1}>
              <span aria-hidden="true">›</span>
            </button>
          </div>
        </div>
      </div>

      <div
        className="exp-carousel"
        tabIndex="0"
        onKeyDown={onKeyDown}
        role="region"
        aria-roledescription="carousel"
        aria-label={ariaLabel}
      >
        <div className="exp-carousel-track" ref={trackRef}>
          {cards.map((c, i) => (
            <div key={c.key || i} className="exp-carousel-slot">
              {React.cloneElement(c, { active: i === idx })}
            </div>
          ))}
        </div>
      </div>

      <div className="exp-dots" role="tablist" aria-label={`${ariaLabel} navigation`}>
        {cards.map((c, i) => {
          const accent = c.props.project ? c.props.project.accent : dotAccent;
          return (
            <button
              key={c.key || i}
              role="tab"
              aria-selected={i === idx}
              aria-label={(c.props.project && c.props.project.name) || (c.props.game && c.props.game.name) || `Slide ${i+1}`}
              className={`exp-dot ${i === idx ? "active" : ""}`}
              onClick={() => goTo(i)}
              style={i === idx ? { background: accent, boxShadow: `0 0 12px ${accent}` } : undefined}
            />
          );
        })}
      </div>
    </div>
  );
}

/* ---------- Project Carousel (uses ExpCarousel) ---------- */
function ExpProjectCarousel() {
  const projects = window.EXP_PROJECTS;
  const cards = projects.map((p, i) => (
    <ExpProjectCard key={p.id} project={p} index={i} />
  ));
  return (
    <section className="exp-carousel-section" data-screen-label="04 Projects">
      <div className="wrap">
        <ExpCarousel
          id="projects"
          ariaLabel="PickBits projects"
          eyebrow="// every project, premium"
          heading="Seven products. One subscription."
          sub={<>Each PickBits project ships a free tier and an Experimenters tier. Subscribe once and you unlock the premium feature set on every one of them — present <em>and</em> future. Browse the lineup below.</>}
          cards={cards}
        />
      </div>
    </section>
  );
}

function ExpProjectCard({ project, index, active }) {
  const isShowcase = project.kind === "showcase";
  return (
    <article
      className={`exp-project-card ${active ? "active" : ""} ${isShowcase ? "is-showcase" : "is-service"}`}
      style={{ '--project-accent': project.accent }}
    >
      <div className="exp-project-media">
        <div className="exp-project-frame">
          <img
            src={project.image}
            alt={project.name}
            loading="lazy"
            style={project.imagePosition ? { objectPosition: project.imagePosition } : undefined}
          />
        </div>
        <span className={`exp-project-status status-${project.status}`}>{project.statusLabel}</span>
        <div className="exp-project-tags">
          {project.tags.map((t) => <span key={t}>{t}</span>)}
        </div>
      </div>

      <div className="exp-project-body">
        <div className="exp-project-head">
          <div className="exp-project-eyebrow">// project_{String((index ?? 0) + 1).padStart(2, "0")}</div>
          <h3 className="exp-project-name">{project.name}</h3>
          <p className="exp-project-tagline">{project.tagline}</p>
          <p className="exp-project-blurb">{project.blurb}</p>
        </div>

        {isShowcase ? (
          <div className="exp-project-premium exp-project-showcase">
            <div className="exp-premium-head">
              <span className="exp-premium-eyebrow" style={{ color: project.accent }}>
                {project.showcaseHeadline}
              </span>
              <span className="exp-premium-lock">BUILD GUIDE</span>
            </div>
            <ul className="exp-premium-list">
              {project.showcase.map((feature, i) => (
                <li key={i}>
                  <span className="exp-premium-check" style={{ color: project.accent }}>+</span>
                  <span>{feature}</span>
                </li>
              ))}
            </ul>
          </div>
        ) : (
          <div className="exp-project-premium">
            <div className="exp-premium-head">
              <span className="exp-premium-eyebrow" style={{ color: project.accent }}>
                {project.premiumHeadline}
              </span>
              <span className="exp-premium-lock">EXPERIMENTERS</span>
            </div>
            <ul className="exp-premium-list">
              {project.premium.map((feature, i) => (
                <li key={i}>
                  <span className="exp-premium-check" style={{ color: project.accent }}>+</span>
                  <span>{feature}</span>
                </li>
              ))}
            </ul>
            <div className="exp-founder-row">
              <span className="exp-founder-icon">⚡</span>
              <span>{project.founderPerk}</span>
            </div>
          </div>
        )}

        <div className="exp-project-ctas">
          <a className="btn primary exp-project-cta" href={project.url} target="_blank" rel="noopener noreferrer" style={{ background: project.accent, color: '#07080d' }}>
            {isShowcase ? `Visit ${project.name}` : `Try ${project.name}`} <span aria-hidden="true">→</span>
          </a>
          {isShowcase ? (
            project.guideUrl ? (
              <a className="btn ghost exp-project-cta" href={project.guideUrl}>
                Read the build guide
              </a>
            ) : (
              <span className="btn ghost exp-project-cta" aria-disabled="true" style={{ opacity: 0.55, cursor: 'default' }}>
                Build guide · coming soon
              </span>
            )
          ) : (
            <a className="btn ghost exp-project-cta" href="#pick-tier">
              Unlock premium
            </a>
          )}
        </div>
      </div>
    </article>
  );
}

/* ---------- University card + carousel ---------- */
function ExpUniversityCard({ track, index, active }) {
  return (
    <article
      className={`exp-project-card exp-uni-card ${active ? "active" : ""}`}
      style={{ '--project-accent': track.accent }}
    >
      <div className="exp-project-media">
        <div className="exp-project-frame">
          <img src={track.image} alt={track.name} loading="lazy" />
        </div>
        <span className="exp-project-status status-live">Track</span>
        <div className="exp-project-tags">
          <span>University</span>
          <span>Experimenter unlocks</span>
        </div>
      </div>

      <div className="exp-project-body">
        <div className="exp-project-head">
          <div className="exp-project-eyebrow">// track_{String((index ?? 0) + 1).padStart(2, "0")}</div>
          <h3 className="exp-project-name">{track.name}</h3>
          <p className="exp-project-tagline">{track.tagline}</p>
          <p className="exp-project-blurb">{track.blurb}</p>
        </div>

        <div className="exp-project-premium exp-uni-parts">
          <div className="exp-premium-head">
            <span className="exp-premium-eyebrow" style={{ color: track.accent }}>
              // video curriculum · {track.parts.length} parts · {track.totalLessons} lessons
            </span>
            <span className="exp-premium-lock">WATCH</span>
          </div>
          <ul className="exp-uni-parts-list">
            {track.parts.map((p) => (
              <li key={p.n}>
                <a
                  className="exp-uni-part"
                  href={`${track.watchUrl}#${track.id}/p${p.n}`}
                  style={{ '--part-accent': p.accent }}
                >
                  <span className="exp-uni-part-num">{p.num}</span>
                  <span className="exp-uni-part-title">{p.title}</span>
                  <span className="exp-uni-part-meta">
                    {p.lessons} lesson{p.lessons === 1 ? "" : "s"}
                    {p.runtime ? ` · ${p.runtime}` : " · videos drafting"}
                  </span>
                  <span className="exp-uni-part-play" aria-hidden="true">▶</span>
                </a>
              </li>
            ))}
          </ul>
        </div>

        <div className="exp-project-ctas">
          <a className="btn primary exp-project-cta" href={`${track.watchUrl}#${track.id}/p1`} style={{ background: track.accent, color: '#07080d' }}>
            ▶ Watch {track.name} <span aria-hidden="true">→</span>
          </a>
          <a className="btn ghost exp-project-cta" href={track.hubUrl}>
            Browse the hub
          </a>
        </div>
      </div>
    </article>
  );
}

function ExpUniversityCarousel() {
  const tracks = window.EXP_UNIVERSITY || [];
  if (tracks.length === 0) return null;
  const cards = tracks.map((t, i) => (
    <ExpUniversityCard key={t.id} track={t} index={i} />
  ));
  return (
    <section className="exp-carousel-section exp-uni-section" data-screen-label="05 University">
      <div className="wrap">
        <ExpCarousel
          id="university"
          ariaLabel="PickBits University tracks"
          eyebrow="// experimenters get the whole curriculum"
          heading="University. Every track. Unlocked."
          sub={<>Your subscription unlocks every premium module on every track — present <em>and</em> future. Each track is a multi-part curriculum you can binge in <a href="/university/vibe-coder/watch/">the watch viewer</a> or read at your own pace.</>}
        cards={cards}
        />
      </div>
    </section>
  );
}

/* ---------- Tiers + Perks (one section, two bands) ----------
   "Pick your tier" (the three doors) and "This is how we operate"
   (what's behind the Experimenter/Founder door) share one section so
   they read as a single value story. Two background bands inside keep
   the page's section-to-section colour rhythm. */
function ExpTiersPerks() {
  const perks = window.EXP_PERKS || [];
  return (
    <section className="exp-tiers-perks" id="pick-tier" data-screen-label="03 Tiers">
      <div className="exp-tp-band exp-tp-tiers">
        <div className="wrap">
          <div className="section-head exp-tier-head">
            <div className="left">
              <div className="eyebrow">// three doors in</div>
              <h2 className="h-display">Pick your tier.</h2>
              <p>Free is generous. Experimenter unlocks every premium feature on every project. Founder is included free for a year with any Track Pack on <a href="/level-up#packs">Level Up</a>.</p>
            </div>
          </div>
          <div className="exp-tier-grid">
            {window.EXP_TIERS.map((t) => (
              <div key={t.id} className={`exp-tier ${t.best ? "best" : ""}`} style={{ '--tier-color': t.color }}>
                {t.best && <span className="exp-tier-ribbon">RECOMMENDED</span>}
                <div className="exp-tier-eyebrow">{t.eyebrow}</div>
                <h3 className="exp-tier-name">{t.name}</h3>
                <p className="exp-tier-blurb">{t.blurb}</p>
                <ul className="exp-tier-bullets">
                  {t.bullets.map((b, i) => <li key={i}>{b}</li>)}
                </ul>
                {t.id === "free" && (
                  <div className="exp-tier-cta">
                    <ExpFreeCapture />
                  </div>
                )}
                {t.id === "experimenter" && (
                  <div className="exp-tier-cta">
                    <button type="button" className="btn primary" onClick={() => startExperimenterCheckout("annual")}>
                      Subscribe — $45/yr
                    </button>
                    <button type="button" className="btn ghost" onClick={() => startExperimenterCheckout("monthly")}>
                      or $5/mo
                    </button>
                  </div>
                )}
                {t.id === "founder" && (
                  <div className="exp-tier-cta">
                    <a className="btn ghost" href="/level-up#packs">Buy a Track Pack →</a>
                  </div>
                )}
              </div>
            ))}
          </div>

          {perks.length > 0 && (
            <div className="exp-tier-perks">
              <div className="exp-tier-perks-label">// every paid tier also gets</div>
              <div className="exp-tier-perks-grid">
                {perks.map((perk, i) => (
                  <div className="exp-perk" key={i}>
                    {perk.image && (
                      <img className="exp-perk-hero" src={perk.image} alt="" loading="lazy" />
                    )}
                    <div className="exp-perk-body">
                      <h4>{perk.h}</h4>
                      <p>{perk.p}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

/* ---------- Game card (mirrors project card; pitch is fork-the-repo) ---------- */
function ExpGameCard({ game, index, active }) {
  return (
    <article
      className={`exp-project-card exp-game-card ${active ? "active" : ""}`}
      style={{ '--project-accent': game.accent }}
    >
      <div className="exp-project-media">
        <div className="exp-project-frame">
          {game.image ? (
            <img src={game.image} alt={game.name} loading="lazy" />
          ) : (
            <div className="exp-game-placeholder" aria-hidden="true">
              <span className="exp-game-glyph">⌬</span>
              <span className="exp-game-placeholder-label">{game.name}</span>
            </div>
          )}
        </div>
        <span className={`exp-project-status status-${game.status}`}>{game.statusLabel}</span>
        <div className="exp-project-tags">
          {game.tags.map((t) => <span key={t}>{t}</span>)}
        </div>
      </div>

      <div className="exp-project-body">
        <div className="exp-project-head">
          <div className="exp-project-eyebrow">// game_{String((index ?? 0) + 1).padStart(2, "0")} · {game.license}</div>
          <h3 className="exp-project-name">{game.name}</h3>
          <p className="exp-project-tagline">{game.tagline}</p>
          <p className="exp-project-blurb">{game.blurb}</p>
        </div>

        <div className="exp-project-premium exp-game-premium">
          <div className="exp-premium-head">
            <span className="exp-premium-eyebrow" style={{ color: game.accent }}>
              // {game.tech}
            </span>
            <span className="exp-premium-lock">PUBLIC REPO</span>
          </div>
          <ul className="exp-premium-list">
            <li>
              <span className="exp-premium-check" style={{ color: game.accent }}>+</span>
              <span>Open PRs welcome — fork and ship a variant</span>
            </li>
            <li>
              <span className="exp-premium-check" style={{ color: game.accent }}>+</span>
              <span>Priority review for experimenter contributions</span>
            </li>
            <li>
              <span className="exp-premium-check" style={{ color: game.accent }}>+</span>
              <span>Ship-credit in release notes if it merges</span>
            </li>
            <li>
              <span className="exp-premium-check" style={{ color: game.accent }}>+</span>
              <span>Beta builds + Steam keys for testers</span>
            </li>
          </ul>
          <div className="exp-founder-row">
            <span className="exp-founder-icon">{game.status === 'tool' ? '⚡' : '🎮'}</span>
            <span>
              {game.status === 'tool'
                ? 'Founder: priority access to new tools + early API quotas'
                : 'Arcade Tier-2 (Founders): bonus levels + secret tables'}
            </span>
          </div>
        </div>

        <div className="exp-project-ctas">
          {game.play && (
            <a className="btn primary exp-project-cta" href={game.play} style={{ background: game.accent, color: '#07080d' }}>
              ▶ Play in arcade
            </a>
          )}
          <a className="btn ghost exp-project-cta" href={game.repo} target="_blank" rel="noopener noreferrer">
            <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="currentColor" style={{ marginRight: '0.4rem' }}><path d="M8 .2a8 8 0 0 0-2.5 15.6c.4.1.5-.2.5-.4v-1.5c-2.2.5-2.7-1-2.7-1-.4-.9-.9-1.2-.9-1.2-.7-.5.1-.5.1-.5.8.1 1.2.8 1.2.8.7 1.2 1.9.9 2.4.7.1-.5.3-.9.5-1.1-1.8-.2-3.6-.9-3.6-3.9 0-.9.3-1.6.8-2.2-.1-.2-.4-1 .1-2.1 0 0 .7-.2 2.2.8.6-.2 1.3-.3 2-.3.7 0 1.4.1 2 .3 1.5-1 2.2-.8 2.2-.8.4 1.1.2 1.9.1 2.1.5.6.8 1.3.8 2.2 0 3.1-1.9 3.7-3.7 3.9.3.3.5.8.5 1.5v2.2c0 .2.1.5.5.4A8 8 0 0 0 8 .2Z"/></svg>
            Fork the repo
          </a>
        </div>
      </div>
    </article>
  );
}

/* ---------- Game Carousel (mirrors project carousel format) ---------- */
function ExpGameCarousel({ visible }) {
  if (!visible) return null;
  const games = window.EXP_ARCADE;
  const cards = games.map((g, i) => (
    <ExpGameCard key={g.id} game={g} index={i} />
  ));
  return (
    <section className="exp-carousel-section exp-game-section" data-screen-label="06 Arcade Games">
      <div className="wrap">
        <ExpCarousel
          id="games"
          ariaLabel="PickBits arcade games"
          eyebrow="// fork the arcade · every repo public"
          heading="Fifteen games. One toolkit."
          sub={<>The arcade isn't just for playing. Experimenters can <strong>contribute to any public PickBits repo</strong> — open a PR, get priority review, and if it ships your handle goes in the release notes. Plus the dev tool we use to build them.</>}
          headRight={
            <a href="https://github.com/pickbitsai" target="_blank" rel="noopener noreferrer" className="exp-arcade-org-btn">
              <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="currentColor"><path d="M8 .2a8 8 0 0 0-2.5 15.6c.4.1.5-.2.5-.4v-1.5c-2.2.5-2.7-1-2.7-1-.4-.9-.9-1.2-.9-1.2-.7-.5.1-.5.1-.5.8.1 1.2.8 1.2.8.7 1.2 1.9.9 2.4.7.1-.5.3-.9.5-1.1-1.8-.2-3.6-.9-3.6-3.9 0-.9.3-1.6.8-2.2-.1-.2-.4-1 .1-2.1 0 0 .7-.2 2.2.8.6-.2 1.3-.3 2-.3.7 0 1.4.1 2 .3 1.5-1 2.2-.8 2.2-.8.4 1.1.2 1.9.1 2.1.5.6.8 1.3.8 2.2 0 3.1-1.9 3.7-3.7 3.9.3.3.5.8.5 1.5v2.2c0 .2.1.5.5.4A8 8 0 0 0 8 .2Z"/></svg>
              Browse the org
            </a>
          }
          cards={cards}
          dotAccent="var(--accent-2)"
        />
      </div>
    </section>
  );
}

/* ---------- Cross-links ---------- */
function ExpCTA() {
  return (
    <section className="exp-cta-section" id="join" data-screen-label="07 Join CTA">
      <div className="wrap">
        <div className="exp-cross-links">
          <a href="/coaching" className="exp-cross-link">
            <span className="glyph">⌖</span>
            <span>1:1 Coaching</span>
            <span className="arrow">→</span>
          </a>
          <a href="/university" className="exp-cross-link">
            <span className="glyph">⌬</span>
            <span>Browse University</span>
            <span className="arrow">→</span>
          </a>
          <a href="/arcade" className="exp-cross-link">
            <span className="glyph">◈</span>
            <span>Play the Arcade</span>
            <span className="arrow">→</span>
          </a>
        </div>
      </div>
    </section>
  );
}

/* ---------- App shell ---------- */
function ExpApp() {
  const [tweaks, setTweaks] = useState(window.EXP_TWEAK_DEFAULS);
  const setTweak = useCallback((keyOrObj, val) => {
    setTweaks((cur) => {
      const next = typeof keyOrObj === "string"
        ? { ...cur, [keyOrObj]: val }
        : { ...cur, ...keyOrObj };
      try {
        window.parent.postMessage({ type: '__edit_mode_set_keys', edits: next }, '*');
      } catch (_e) {}
      return next;
    });
  }, []);

  // Apply theme-ish density
  useEffect(() => {
    document.documentElement.dataset.accentDensity = tweaks.accentDensity || 'loud';
  }, [tweaks.accentDensity]);

  return (
    <div className="exp-page" data-screen-label="Experimenters page">
      <ExpHero />
      <ExpManifesto style={tweaks.manifestoStyle} />
      <ExpTiersPerks />
      <ExpProjectCarousel />
      <ExpUniversityCarousel />
      <ExpGameCarousel visible={tweaks.showArcade !== false} />
      <ExpCTA />

      {window.ExpTweaks && <window.ExpTweaks tweaks={tweaks} setTweak={setTweak} />}
    </div>
  );
}

Object.assign(window, {
  ExpHero, ExpManifesto, ExpProjectCarousel, ExpTiersPerks,
  ExpGameCarousel, ExpCTA, ExpApp, ExpCarousel,
  ExpProjectCard, ExpGameCard, ExpUniversityCarousel, ExpUniversityCard
});
