// Live Quiz — HOST view (projector / laptop first; collapses to phone).
// Renders purely from `game` state; its buttons call game.advance / game.start.

const { useState: hUseState } = React;

function lvPrompt(text, opts = {}) {
  const parts = text.split("___");
  return parts.map((p, i) => (
    <React.Fragment key={i}>
      <span>{p}</span>
      {i < parts.length - 1 && (opts.fill
        ? <span className="lv-blank" style={{ borderBottomColor: "var(--ok)", color: "var(--accent-ink)", fontWeight: 800 }}>{opts.fill}</span>
        : <span className="lv-blank">&nbsp;</span>)}
    </React.Fragment>
  ));
}

// Real, scannable QR for the lobby. Encodes the join deep-link so a phone's
// camera opens straight into Join with the PIN filled. Null if the lib is absent.
function LiveQR({ text, size = 176 }) {
  const data = React.useMemo(() => {
    if (typeof window.qrcode !== "function") return null;
    try {
      const qr = window.qrcode(0, "M");
      qr.addData(text); qr.make();
      const n = qr.getModuleCount();
      let path = "";
      for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) if (qr.isDark(r, c)) path += `M${c} ${r}h1v1h-1z`;
      return { n, path };
    } catch (e) { return null; }
  }, [text]);
  if (!data) return null;
  const m = 4; // quiet zone
  return (
    <div className="lv-qr-box">
      <svg width={size} height={size} viewBox={`${-m} ${-m} ${data.n + 2 * m} ${data.n + 2 * m}`} shapeRendering="crispEdges" aria-label="Join QR code">
        <rect x={-m} y={-m} width={data.n + 2 * m} height={data.n + 2 * m} fill="#fff" />
        <path d={data.path} fill="#141615" />
      </svg>
    </div>
  );
}

function HostView({ game, tooSmall }) {
  if (tooSmall) {
    return (
      <div className="lv-host lv">
        <div className="lv-guard">
          <div className="lv-guard-mark">
            <svg width="38" height="38" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
              <rect x="2.5" y="4" width="19" height="13" rx="2" /><path d="M8 21h8M12 17v4" />
            </svg>
          </div>
          <h2>Host from a bigger screen</h2>
          <p>Running a live game needs a laptop, tablet, or the projector — there's a lot to show the room. Players join from any phone.</p>
          <div className="lv-guard-hint">Want to play instead? Join a game from your phone.</div>
        </div>
      </div>
    );
  }
  const inGame = game.phase === "intermission" || game.phase === "question" || game.phase === "reveal";
  return (
    <div className="lv-host lv">
      {inGame && game.pin ? (
        <div className="lv-pin-chip" title="Players can still join with this PIN">
          <span className="lv-pin-chip-l">Join · PIN</span>
          <span className="lv-pin-chip-n">{String(game.pin).replace(/(\d{3})(\d{3})/, "$1 $2")}</span>
        </div>
      ) : null}
      <div className="lv-host-pad">
        {game.phase === "entry" && <HostHome game={game} />}
        {game.phase === "setup" && <HostSetup game={game} />}
        {game.phase === "lobby" && <HostLobby game={game} />}
        {(game.phase === "intermission" || game.phase === "question") && <HostQuestion game={game} />}
        {game.phase === "reveal" && <HostReveal game={game} />}
        {game.phase === "final" && <HostFinal game={game} />}
      </div>
    </div>
  );
}

// Entry point in the MAIN app (not buried in Class): a "Live" item in the top nav
// + a prominent card on Home. Anyone can start a game; classes are optional.
function HostHome({ game }) {
  const tabs = [["Home", true, false], ["Tests", false, false], ["Live", false, true], ["Mistakes", false, false], ["Stats", false, false]];
  return (
    <div className="lv-setup" style={{ maxWidth: 860 }}>
      <div className="lv-topnav">
        <span className="lv-tn-brand"><span>iri</span><span className="a">kos</span></span>
        <div className="lv-tn-tabs">
          {tabs.map(([l, on, live]) => (
            <span key={l} className={`lv-tn-tab ${on ? "is-on" : ""}`}>{live && <span className="lv-tn-dot" />}{l}</span>
          ))}
        </div>
        <span className="lv-tn-avatar">D</span>
      </div>

      <div>
        <div className="lv-setup-eyebrow">Today</div>
        <h1 className="lv-setup-title lv-display">A short set, whenever you can.</h1>
      </div>

      <div className="lv-field" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 18, background: "var(--accent-tint)", borderColor: "color-mix(in oklab, var(--accent) 28%, var(--rule))" }}>
        <div>
          <div className="lv-field-label" style={{ color: "var(--accent-ink)", fontSize: 13, textTransform: "uppercase", letterSpacing: "0.1em" }}>Live</div>
          <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.01em", margin: "4px 0 4px" }}>Host a live quiz</div>
          <div className="lv-field-sub">Run a game on the board — anyone joins from their phone with a PIN. Pick a class to auto-score it, or just play.</div>
        </div>
        <button className="cta-primary lg" onClick={game.advance}><span>Host a live quiz</span><span className="cta-arrow">→</span></button>
      </div>

      <div className="lv-field" style={{ opacity: 0.72 }}>
        <div className="lv-field-row">
          <div><div className="lv-field-label">Continue practice</div><div className="lv-field-sub">Last set 8/10 · word formation</div></div>
          <span className="cta-secondary" style={{ pointerEvents: "none" }}>Resume</span>
        </div>
        <div className="lv-field-row">
          <div><div className="lv-field-label">Mistakes</div><div className="lv-field-sub">7 collected to review</div></div>
          <span className="cta-secondary" style={{ pointerEvents: "none" }}>Open</span>
        </div>
      </div>
    </div>
  );
}

function HostSetup({ game }) {
  const [fams, setFams] = hUseState({ "Word Formation": true, "Grammar": true, "Lexical Choice": true });
  const [len, setLen] = hUseState("10");
  const [time, setTime] = hUseState("20");
  return (
    <div className="lv-setup">
      <div>
        <div className="lv-setup-eyebrow">Class · Live quiz</div>
        <h1 className="lv-setup-title lv-display">Set up a live game</h1>
      </div>

      <div className="lv-field">
        <div className="lv-field-label">Question families</div>
        <div className="lv-field-sub">Drawn from your active tests, same as practice.</div>
        <div className="lv-fam-grid">
          {Object.keys(fams).map(f => (
            <button key={f} className={`lv-fam ${fams[f] ? "is-on" : ""}`} onClick={() => setFams(s => ({ ...s, [f]: !s[f] }))}>
              <span className="lv-fam-name">{f}</span>
              <span className={`switch ${fams[f] ? "is-on" : ""}`} style={{ pointerEvents: "none" }}><span /></span>
            </button>
          ))}
        </div>
      </div>

      <div className="lv-field">
        <div className="lv-field-row">
          <div><div className="lv-field-label">Questions</div><div className="lv-field-sub">How many rounds</div></div>
          <div className="segmented">
            {["10", "20", "30"].map(v => <button key={v} className={`segmented-btn ${len === v ? "is-on" : ""}`} onClick={() => setLen(v)}>{v}</button>)}
          </div>
        </div>
        <div className="lv-field-row">
          <div><div className="lv-field-label">Time per question</div><div className="lv-field-sub">Speed scoring rewards fast correct answers</div></div>
          <div className="segmented">
            {["10", "20", "30"].map(v => <button key={v} className={`segmented-btn ${time === v ? "is-on" : ""}`} onClick={() => setTime(v)}>{v}s</button>)}
          </div>
        </div>
      </div>

      <div style={{ display: "flex", justifyContent: "flex-end" }}>
        <button className="cta-primary lg" onClick={game.advance}>
          <span>Create game</span><span className="cta-arrow">→</span>
        </button>
      </div>
    </div>
  );
}

function HostLobby({ game }) {
  const joined = game.joined;
  return (
    <div className="lv-lobby">
      <div className="lv-lobby-top">
        <div className="lv-join-card">
          <div className="lv-join-where">
            <span className="l1">Join at</span>
            <span className="l2">practice.vinsight.ru</span>
          </div>
          <div className="lv-join-pin">
            <span className="pl">Game PIN</span>
            <span className="lv-pin-num">{String(game.pin || "").replace(/(\d{3})(\d{3})/, "$1 $2")}</span>
          </div>
          <div className="lv-join-tip">Open the app → <b>Live</b> → <b>Join</b>, or just scan →</div>
        </div>
        <div className="lv-qr-wrap">
          <LiveQR text={`${location.origin}/?live=${game.pin}`} />
          <span className="lv-qr-cap">Point your camera here to join</span>
        </div>
      </div>

      <div className="lv-lobby-center">
        <div className="lv-waiting">
          <span>Waiting for players</span>
          <span className="lv-count-pill">{joined.length}</span>
        </div>
        {joined.length === 0 ? (
          <div className="lv-lobby-empty">No one's joined yet — share the PIN to get started.</div>
        ) : (
          <div className="lv-players">
            {joined.map(p => (
              <div key={p.id} className="lv-player-chip">
                <span className="lv-avatar" style={{ background: avatarColor(p.name) }}>{p.name.slice(0, 1)}</span>
                <span>{p.name}</span>
              </div>
            ))}
          </div>
        )}
      </div>

      <div className="lv-lobby-foot">
        <span className="lv-lobby-empty">{game.questionCount} questions · {game.timePerQ}s each</span>
        <button className="cta-primary lg" onClick={game.advance} disabled={joined.length === 0}>
          <span>Start</span><span className="cta-arrow">→</span>
        </button>
      </div>
    </div>
  );
}

function HostQuestion({ game }) {
  const q = game.question;
  const isInter = game.phase === "intermission";
  const promptRef = React.useRef(null);
  // A long passage scrolls past the single blank — bring it into view on the board.
  React.useEffect(() => {
    if (!q || !q.passage) return;
    const el = promptRef.current && promptRef.current.querySelector(".lv-blank");
    if (el && el.scrollIntoView) { try { el.scrollIntoView({ block: "center" }); } catch (e) { el.scrollIntoView(); } }
  }, [q && q.prompt, isInter]);
  if (isInter) {
    return (
      <div className="lv-q" style={{ alignItems: "center", justifyContent: "center" }}>
        <div style={{ textAlign: "center" }}>
          <div className="lv-q-tag" style={{ display: "inline-block", marginBottom: 18 }}>{q.family}</div>
          <div className="lv-display" style={{ fontSize: 56 }}>Question {game.qIndex + 1}</div>
          <div style={{ fontSize: 22, color: "var(--ink-3)", marginTop: 10, fontWeight: 600 }}>Get ready…</div>
        </div>
      </div>
    );
  }
  return (
    <div className="lv-q">
      <div className="lv-q-head">
        <span className="lv-q-tag">{q.family}</span>
        <span className="lv-q-counter">{game.qIndex + 1} / {game.questionCount}</span>
      </div>

      {q.passage ? <div className="lv-context-label">Read for context — one word is missing</div> : null}
      <div ref={promptRef} className={`lv-q-prompt lv-display${q.passage ? " is-passage" : ""}`}>{q.passage ? <div className="lv-passage-inner">{lvPrompt(q.prompt)}</div> : <span className="lv-q-line">{lvPrompt(q.prompt)}</span>}</div>

      <div className="lv-q-sub">
        {game.timePerQ != null
          ? <CountdownRing remaining={game.remaining} total={game.timePerQ} />
          : <div className="lv-no-timer">No limit</div>}
        <div className="lv-answers-count">
          <span className="n">{game.answeredCount}</span>
          <span className="l">Answers</span>
        </div>
        <button className="cta-secondary lv-skip-btn" onClick={game.skip}>Skip<span className="cta-arrow">→</span></button>
      </div>

      {q.mode === "typed" ? (
        <div className="lv-typed-hint">
          <span className="lv-cue">{q.base}</span>
          <span>Players type their answer on their phones</span>
        </div>
      ) : (
        <div className="lv-grid">
          {q.options.map((o, i) => (
            <div key={i} className="lv-opt">
              <span className="lv-shape"><Shape i={i} size={34} /></span>
              <span className="lv-opt-num">{i + 1}</span>
              <span className="lv-opt-text">{o}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function HostReveal({ game }) {
  const q = game.question;
  const dist = game.distribution;
  const typed = q.mode === "typed";
  const max = Math.max(1, ...(typed ? dist.map(d => d.count) : dist));
  return (
    <div className="lv-q">
      <div className="lv-q-head">
        <span className="lv-q-tag">{q.family}</span>
        <span className="lv-q-counter">{game.qIndex + 1} / {game.questionCount}</span>
      </div>
      {q.passage ? (
        <div className="lv-reveal-word">
          {q.base ? <span className="lv-cue">{q.base}</span> : null}
          <span className="lv-reveal-answer lv-display">{q.answer}</span>
        </div>
      ) : (
        <div className="lv-q-prompt lv-display" style={{ fontSize: "clamp(22px,2.7vw,30px)", flex: "0 0 auto", padding: "4px 0 2px" }}>
          <span className="lv-q-line">{lvPrompt(q.prompt, { fill: typed ? q.answer : q.options[q.correct] })}</span>
        </div>
      )}

      <div className="lv-reveal">
        <div className="lv-reveal-main">
          <div className="lv-dist">
            {typed
              ? dist.map((e, i) => (
                  <div key={i} className={`lv-dist-col ${e.correct ? "is-correct" : ""}`}>
                    <div className="lv-dist-n">{e.count}</div>
                    <div className="lv-dist-track"><div className="lv-dist-bar" style={{ height: `${(e.count / max) * 100}%` }} /></div>
                    <div className="lv-dist-foot">
                      <span className={e.others ? "lv-dist-others" : ""}>{e.label}</span>
                      {e.correct && <span style={{ color: "var(--ok)" }}>✓</span>}
                    </div>
                  </div>
                ))
              : q.options.map((o, i) => (
                  <div key={i} className={`lv-dist-col ${i === q.correct ? "is-correct" : ""}`}>
                    <div className="lv-dist-n">{dist[i]}</div>
                    <div className="lv-dist-track"><div className="lv-dist-bar" style={{ height: `${(dist[i] / max) * 100}%` }} /></div>
                    <div className="lv-dist-foot"><Shape i={i} size={18} /><span>{o}</span>{i === q.correct && <span style={{ color: "var(--ok)" }}>✓</span>}</div>
                  </div>
                ))}
          </div>
        </div>

        <div className="lv-board">
          <div className="lv-board-title">Leaderboard</div>
          {game.leaderboard.slice(0, 5).map((p, i) => (
            <LeaderboardRow key={p.id} rank={i + 1} name={p.name} score={p.score} delta={p.delta} you={p.you} />
          ))}
          <div style={{ flex: 1 }} />
          <button className="cta-primary lg" style={{ alignSelf: "flex-end", marginTop: 14 }} onClick={game.advance}>
            <span>{game.qIndex + 1 >= game.questionCount ? "Final results" : "Next"}</span><span className="cta-arrow">→</span>
          </button>
        </div>
      </div>
    </div>
  );
}

function HostFinal({ game }) {
  const [tab, setTab] = hUseState("results");
  const top3 = game.leaderboard.slice(0, 3);
  const { perQuestion, perStudent } = game.review;
  return (
    <div className="lv-final">
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
        <h1 className="lv-final-title lv-display" style={{ textAlign: "left", fontSize: 30 }}>Great game.</h1>
        <div className="segmented">
          {[["results", "Results"], ["questions", "By question"], ["students", "By student"]].map(([v, l]) => (
            <button key={v} className={`segmented-btn ${tab === v ? "is-on" : ""}`} onClick={() => setTab(v)}>{l}</button>
          ))}
        </div>
      </div>

      {tab === "results" && (
        <>
          <Podium top3={top3} />
          <div className="lv-board" style={{ maxWidth: 620, margin: "0 auto", width: "100%" }}>
            <div className="lv-board-title">Final standings</div>
            {game.leaderboard.slice(0, 6).map((p, i) => (
              <LeaderboardRow key={p.id} rank={i + 1} name={p.name} score={p.score} you={p.you} />
            ))}
          </div>
        </>
      )}

      {tab === "questions" && (
        <div className="lv-review">
          {perQuestion.map((pq, r) => (
            <div key={r} className="lv-review-q">
              <div className="lv-review-q-top">
                <span className="lv-q-tag">{pq.family}</span>
                <span className="lv-review-pct" data-low={pq.pct < 50}>{pq.pct}% correct</span>
              </div>
              <div className={`lv-review-prompt${pq.passage ? " is-passage" : ""}`}>{lvPrompt(pq.prompt, { fill: pq.answer })}</div>
              <div className="lv-review-bar"><span style={{ width: `${pq.pct}%` }} /></div>
              <div className="lv-review-meta">{pq.correctN} of {pq.total} got it · answer <b>{pq.answer}</b></div>
            </div>
          ))}
        </div>
      )}

      {tab === "students" && (
        <div className="lv-review">
          <div className="lv-table">
            <div className="lv-table-head">
              <span className="lv-th-name">Student</span>
              {perQuestion.map((_, r) => <span key={r} className="lv-th-q">Q{r + 1}</span>)}
              <span className="lv-th-score">Correct</span>
              <span className="lv-th-score">Score</span>
            </div>
            {perStudent.map((p, i) => (
              <div key={p.id} className={`lv-table-row ${p.you ? "is-you" : ""}`}>
                <span className="lv-th-name"><span className="lv-rank" style={{ width: 18 }}>{i + 1}</span> {p.name}</span>
                {p.marks.map((m, r) => <span key={r} className="lv-th-q">{m ? <i className="lv-mk ok">✓</i> : <i className="lv-mk no">✗</i>}</span>)}
                <span className="lv-th-score">{p.correctN}/{perQuestion.length}</span>
                <span className="lv-th-score">{p.score.toLocaleString()}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      <div style={{ display: "flex", gap: 12, justifyContent: "center" }}>
        <button className="cta-secondary" onClick={game.reset}>Done</button>
        <button className="cta-primary" onClick={game.reset}><span>Play again</span><span className="cta-arrow">→</span></button>
      </div>
    </div>
  );
}

Object.assign(window, { HostView, lvPrompt });
