/* ===================================================================
   THE ARCADE — shared "System Interface" shell + games hub.
   Exports to window: GameStage, GameProgress, SysCard, useShare,
   ACCENTS, GamesPage. Game implementations live in
   games-crawl.jsx (window.CrawlGame) and games-class.jsx (window.ClassGame).
   =================================================================== */
const { useState: useStateA, useEffect: useEffectA, useRef: useRefA } = React;
const G = window.DCC_GAMES;

/* per-game accent colors (kept on-palette) */
const ACCENTS = {
  crawl: 'var(--mag)',       // the show / loot energy
  class: 'var(--t-spell)',   // cold cyan — "the System is determining your nature"
};
window.ACCENTS = ACCENTS;

/* ---- copy-to-clipboard share helper ---- */
function useShare(){
  const [copied, setCopied] = useStateA(false);
  const tRef = useRefA(null);
  function share(text){
    const done = () => { setCopied(true); clearTimeout(tRef.current); tRef.current = setTimeout(()=>setCopied(false), 2600); };
    try {
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(done, ()=>fallback(text, done));
      } else { fallback(text, done); }
    } catch(e){ fallback(text, done); }
  }
  function fallback(text, done){
    try {
      const ta = document.createElement('textarea');
      ta.value = text; ta.style.position='fixed'; ta.style.opacity='0';
      document.body.appendChild(ta); ta.select(); document.execCommand('copy');
      document.body.removeChild(ta); done();
    } catch(e){ /* no-op */ }
  }
  useEffectA(()=>()=>clearTimeout(tRef.current),[]);
  return [copied, share];
}
window.useShare = useShare;

/* ---- the HUD console frame both games render inside ---- */
function GameStage({ accent, title, onExit, children }){
  return (
    <div className="gstage" style={{['--gc']: accent}}>
      <div className="gconsole">
        <span className="gscan"></span>
        <div className="gtop">
          <span className="glive"><i></i>System</span>
          <span className="gtitle">{title}</span>
          <span className="gexit" onClick={onExit}>✕ Exit</span>
        </div>
        <div className="gbody">{children}</div>
      </div>
    </div>
  );
}
window.GameStage = GameStage;

/* ---- progress indicator (question X of N) ---- */
function GameProgress({ i, n }){
  const pct = Math.round((i / n) * 100);
  return (
    <div className="gprog">
      <span className="gp-label">Q{Math.min(i+1, n)} / {n}</span>
      <div className="gp-track"><div className="gp-fill" style={{width: `${(i/n)*100}%`}}></div></div>
      <div className="gp-dots">
        {Array.from({length:n}).map((_,k)=>(
          <i key={k} className={k < i ? 'done' : (k === i ? 'cur' : '')}></i>
        ))}
      </div>
    </div>
  );
}
window.GameProgress = GameProgress;

/* ---- System notification card ---- */
function SysCard({ from, center, children }){
  return (
    <div className={'syscard'+(center?' center':'')}>
      <div className="sys-from"><span className="dot"></span>{from || 'System Notification'}</div>
      <div className="sys-body">{children}</div>
    </div>
  );
}
window.SysCard = SysCard;

/* ===================================================================
   GAMES HUB — landing page with one tile per game
   =================================================================== */
function GamesPage({ game, go }){
  const goGame = g => go({ view:'games', game:g });
  const toHub  = () => go({ view:'games', game:null });

  if (game === 'crawl' && window.CrawlGame) return <window.CrawlGame go={go} toHub={toHub} />;
  if (game === 'class' && window.ClassGame) return <window.ClassGame go={go} toHub={toHub} />;

  return (
    <div className="view"><div className="wrap">
      <div className="crumbs">
        <a onClick={()=>go({view:'home'})}>Home</a><span className="sep">/</span>
        <span style={{color:'var(--ink)'}}>Arcade</span>
      </div>
      <div className="sec-top">
        <h2>The <span className="am">Arcade</span></h2>
        <p className="note">Two quick games, no save file. The System is watching either way.</p>
      </div>
      <p className="games-intro">
        Step into the feed, crawler. Answer for the cameras, open what you've earned, and let the System
        decide what you're really made of. Nothing here is saved — every run starts fresh, just the way the
        production likes it.
      </p>
      <div className="gtiles">
        <div className="gtile" style={{['--gc']: ACCENTS.crawl}} onClick={()=>goGame('crawl')}>
          <div className="gt-tag">Game 01 · Trivia → Loot</div>
          <div className="gt-glyph">◈</div>
          <h3>The Crawl</h3>
          <p>Ten questions from the dungeon feed. Your score earns a loot-box tier — then a weighted roll
            decides what's inside. Score a perfect run and the Showrunner picks your reward personally.</p>
          <div className="gt-meta">
            <span className="chip"><b>{G.TRIVIA.length}</b> in the bank</span>
            <span className="chip"><b>5</b> box tiers</span>
            <span className="chip"><b>{G.LOOT.length}</b> loot items</span>
          </div>
          <div className="gt-go">Enter the feed ▸</div>
        </div>

        <div className="gtile" style={{['--gc']: ACCENTS.class}} onClick={()=>goGame('class')}>
          <div className="gt-tag">Game 02 · Personality Quiz</div>
          <div className="gt-glyph">⧈</div>
          <h3>Class Selection</h3>
          <p>The System wants to determine your nature. Seven questions match you to a crawler, then
            "System recommends" three classes — one earned, one wildcard, and one you very much cannot have.</p>
          <div className="gt-meta">
            <span className="chip"><b>{G.QUIZ.length}</b> questions</span>
            <span className="chip"><b>{G.CHAR_ORDER.length}</b> matches</span>
            <span className="chip">wildcard <b>re-rolls</b></span>
          </div>
          <div className="gt-go">Determine my nature ▸</div>
        </div>
      </div>
    </div></div>
  );
}
window.GamesPage = GamesPage;
