/* ===================================================================
   GAME 01 — THE CRAWL  (trivia → loot box)
   End-of-quiz scoring (silent tally). Difficulty filters the pool
   toward deeper-lore questions. Score → box tier → weighted loot roll.
   window.CrawlGame
   =================================================================== */
const { useState: useStateC, useRef: useRefC } = React;
const GC = window.DCC_GAMES;

const DIFFS = [
  { id:'casual',   name:'Casual',   key:'TOURIST',  desc:"Crowd-pleasers and cover-of-the-book facts. A gentle warm-up." },
  { id:'crawler',  name:'Crawler',  key:'STANDARD', desc:"You've done a few floors. Names, classes, places, the works." },
  { id:'verified', name:'Verified', key:'DEEP CUT', desc:"Deep-lore only. The System assumes you've read every patch note." },
];

function shuffle(arr){
  const a = arr.slice();
  for (let i = a.length - 1; i > 0; i--){ const j = Math.floor(Math.random()*(i+1)); [a[i],a[j]] = [a[j],a[i]]; }
  return a;
}

/* Build a 10-question run drawn ENTIRELY from the chosen difficulty —
   no cross-tier top-up, so easy facts never surface in a hard run and
   vice-versa. Each tier has 12 questions; we shuffle and take 10 for
   variety between runs. Options are shuffled per question. */
function buildRun(difficulty){
  const pool = shuffle(GC.TRIVIA.filter(q => q.difficulty === difficulty));
  const picked = pool.slice(0, 10);
  return shuffle(picked).map(q => {
    const opts = shuffle(q.options.map((text, idx) => ({ text, correct: idx === q.answerIndex })));
    return { id:q.id, question:q.question, category:q.category, opts };
  });
}

function CrawlGame({ go, toHub }){
  const [phase, setPhase] = useStateC('intro');   // intro | quiz | tier | loot
  const [difficulty, setDifficulty] = useStateC('crawler');
  const [run, setRun] = useStateC([]);
  const [qi, setQi] = useStateC(0);
  const [picked, setPicked] = useStateC(null);     // index picked on current question
  const [pickRight, setPickRight] = useStateC(null); // was the picked answer correct? (green/red, no reveal)
  const [correct, setCorrect] = useStateC(0);
  const [tier, setTier] = useStateC(null);
  const [loot, setLoot] = useStateC(null);
  const [opening, setOpening] = useStateC(false);
  const [copied, share] = window.useShare();
  const lockRef = useRefC(false);

  function start(){
    setRun(buildRun(difficulty));
    setQi(0); setPicked(null); setPickRight(null); setCorrect(0); setTier(null); setLoot(null); setOpening(false);
    lockRef.current = false;
    setPhase('quiz');
  }

  function answer(idx){
    if (lockRef.current) return;
    lockRef.current = true;
    const wasRight = run[qi].opts[idx].correct;
    setPicked(idx);
    setPickRight(wasRight);   // flash the chosen answer green/red — the correct one is NOT revealed
    setTimeout(() => {
      const nextCorrect = correct + (wasRight ? 1 : 0);
      if (qi + 1 < run.length){
        setCorrect(nextCorrect);
        setQi(qi + 1); setPicked(null); setPickRight(null);
        lockRef.current = false;
      } else {
        setCorrect(nextCorrect);
        setTier(GC.tierForScore(nextCorrect));
        setPhase('tier');
      }
    }, 820);
  }

  function openBox(){
    if (opening) return;
    setOpening(true);
    setTimeout(() => {
      setLoot(GC.rollLoot(tier.id));
      setPhase('loot');
    }, 560);
  }

  function shareResult(){
    const rar = GC.RARITY_META[loot.rarity].name;
    share(`SYSTEM LOG // I scored ${correct}/10 on The Crawl and pulled "${loot.name}" [${rar}] from a ${tier.name} box. ` +
          `— System AI's Unofficial DCC Index`);
  }

  /* ---------------- INTRO ---------------- */
  let body;
  if (phase === 'intro'){
    body = (
      <div className="gstep">
        <div className="gintro-h">The <span className="em">Crawl</span></div>
        <div className="gintro-sub">Roll the tape, crawler.</div>
        <window.SysCard from="System // The Crawl">
          Ten questions pulled from the live dungeon feed. Each answer lights up <b style={{color:'var(--rar-uncommon)'}}>green</b> or
          <b style={{color:'var(--warn)'}}> red</b> the instant you commit — but I won't show you the right answer, and your
          running score stays sealed until the end, for the drama. Earn a box tier, then open it and we'll see what the
          odds shake loose. No saves. No second guesses logged.
        </window.SysCard>
        <div className="gdiff">
          <div className="gdiff-lab">Select clearance level</div>
          <div className="gdiff-opts">
            {DIFFS.map(d => (
              <button key={d.id} className={'gdiff-opt'+(difficulty===d.id?' on':'')} onClick={()=>setDifficulty(d.id)}>
                <div className="dn">{d.name} <span className="dk">{d.key}</span></div>
                <div className="dd">{d.desc}</div>
              </button>
            ))}
          </div>
        </div>
        <div className="gnext-wrap">
          <button className="btn" onClick={start}>Begin the run ▸</button>
        </div>
      </div>
    );
  }

  /* ---------------- QUIZ ---------------- */
  else if (phase === 'quiz'){
    const q = run[qi];
    body = (
      <div className="gstep" key={qi}>
        <window.GameProgress i={qi} n={run.length} />
        <div className="gq-cat">{q.category}</div>
        <div className="gq">{q.question}</div>
        <div className="gopts">
          {q.opts.map((o, idx) => (
            <button key={idx}
              className={'gopt'+(picked===idx ? (pickRight ? ' right' : ' wrong') : '')}
              onClick={()=>answer(idx)} disabled={picked!==null}>
              <span className="gk">{String.fromCharCode(65+idx)}</span>
              <span>{o.text}</span>
            </button>
          ))}
        </div>
      </div>
    );
  }

  /* ---------------- TIER REVEAL + BOX ---------------- */
  else if (phase === 'tier'){
    body = (
      <div className="gstep greveal" style={{['--tcol']: `var(${tier.cssvar})`}}>
        <div className="gr-kicker">Run complete · score tallied</div>
        <div className="gr-score"><span className="sl">{correct}</span><small> / {run.length}</small></div>
        <div className="gr-tiername">{tier.name}</div>
        <p className="gr-line">{tier.line}</p>
        <div className="gbox-wrap">
          <div className={'gbox'+(opening?' opening':'')} onClick={openBox} style={{['--tcol']: `var(${tier.cssvar})`}}>
            <span className="glyph">▲</span>
          </div>
        </div>
        <div className="gbox-hint">{opening ? 'Opening…' : 'Tap the box to open'}</div>
      </div>
    );
  }

  /* ---------------- LOOT REVEAL + RESULT ---------------- */
  else if (phase === 'loot'){
    const rm = GC.RARITY_META[loot.rarity];
    body = (
      <div className="gstep">
        <div className="gloot" style={{['--lc']: `var(${rm.cssvar})`}}>
          <span className="rar">{rm.name}</span>
          <div className="itemname">{loot.name}</div>
          <p className="itemblurb">“{loot.blurb}”</p>
          <div className="pulled">Pulled from a <b style={{color:`var(${tier.cssvar})`}}>{tier.name}</b> box · scored {correct}/10</div>
        </div>
        <div className="gactions">
          <button className="btn" onClick={start}>↻ Play again</button>
          <button className="btn amber" onClick={shareResult}>⧉ Transmit result</button>
          <button className="btn ghost" onClick={toHub}>Back to Arcade</button>
        </div>
        <div className="gshare-note" style={{opacity: copied?1:0}}>✓ Result copied to clipboard — paste it anywhere.</div>
        <div className="gmeta-foot">Loot is flavor only — no stats, no inventory. Every box re-rolls fresh.</div>
      </div>
    );
  }

  return (
    <div className="view"><div className="wrap">
      <div className="crumbs">
        <a onClick={()=>go({view:'home'})}>Home</a><span className="sep">/</span>
        <a onClick={toHub}>Arcade</a><span className="sep">/</span>
        <span style={{color:'var(--ink)'}}>The Crawl</span>
      </div>
      <window.GameStage accent={window.ACCENTS.crawl} title="The Crawl · Trivia Feed" onExit={toHub}>
        {body}
      </window.GameStage>
    </div></div>
  );
}
window.CrawlGame = CrawlGame;
