// Live Quiz — PLAYER view (phone-first; reuses .m-* + haptics + motion).

const { useState: plUseState, useEffect: plUseEffect } = React;

function PlayerView({ game, wide }) {
  const you = game.leaderboard.find(p => p.you) || { score: game.youScore || 0 };
  const youRank = (game.leaderboard.findIndex(p => p.you) + 1) || 1;

  // reconnecting overlay sits above everything
  const overlay = game.edge === "reconnecting" ? (
    <div className="lv-overlay">
      <div className="lv-spinner" />
      <div style={{ fontSize: 18, fontWeight: 700 }}>Reconnecting…</div>
      <div style={{ fontSize: 14, color: "var(--ink-3)" }}>Hang tight — we'll drop you back into the current question. Your score is safe.</div>
    </div>
  ) : null;

  // The join form lives in LiveJoin (live-game.jsx); by the time we're here the
  // player is connected. Render purely from the server-driven phase.
  let body;
  if (game.phase === "question") {
    body = game.youLocked ? <PlayerLocked game={game} /> : <PlayerQuestion game={game} />;
  } else if (game.phase === "reveal") {
    body = <PlayerReveal game={game} you={you} youRank={youRank} />;
  } else if (game.phase === "final") {
    body = <PlayerFinal game={game} you={you} youRank={youRank} />;
  } else {
    body = <PlayerLobby nick={game.youName} />; // lobby / waiting for the host
  }

  return <div className={`lv-p lv ${wide ? "is-wide" : ""}`}>{overlay}{body}</div>;
}

function PlayerLobby({ nick }) {
  return (
    <div className="lv-p-pad">
      <div className="lv-p-center">
        <div className="lv-pulse"><div className="lv-pulse-dot" /></div>
        <div style={{ fontSize: 26, fontWeight: 800, letterSpacing: "-0.02em" }}>You're in!</div>
        <div className="m-tasktag" style={{ fontSize: 14, padding: "8px 16px" }}>{nick}</div>
        <div style={{ fontSize: 15, color: "var(--ink-3)", marginTop: 4 }}>Waiting for the teacher to start…</div>
      </div>
    </div>
  );
}

function PlayerIntermission({ game }) {
  return (
    <div className="lv-p-pad">
      <div className="lv-p-center">
        <div style={{ fontSize: 15, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--accent-ink)" }}>Question {game.qIndex + 1}</div>
        <div style={{ fontSize: 30, fontWeight: 800, letterSpacing: "-0.02em" }}>Get ready…</div>
        <div className="lv-pulse" style={{ width: 60, height: 60, marginTop: 8 }}><div className="lv-pulse-dot" style={{ width: 18, height: 18 }} /></div>
      </div>
    </div>
  );
}

function PlayerQuestion({ game }) {
  const q = game.question;
  const [text, setText] = plUseState("");
  const promptRef = React.useRef(null);
  // Long passages scroll past the blank — bring the missing-word gap into view.
  plUseEffect(() => {
    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]);
  const noTimer = game.timePerQ == null;
  const frac = noTimer ? 0 : Math.max(0, (game.remaining || 0) / game.timePerQ);
  const danger = !noTimer && game.remaining <= game.timePerQ * 0.25;
  const warn = !noTimer && !danger && game.remaining <= game.timePerQ * 0.5;
  return (
    <div className="lv-p-pad">
      {!noTimer && <div className="lv-p-bar"><div className={`lv-p-bar-fill ${danger ? "is-danger" : warn ? "is-warn" : ""}`} style={{ width: `${frac * 100}%` }} /></div>}
      <div className="lv-p-tags">
        <span className="m-tasktag">{q.family}</span>
        {q.base ? <span className="lv-cue">{q.base}</span> : null}
      </div>
      {q.passage ? <div className="lv-context-label">Read for context — one word is missing</div> : null}
      <div ref={promptRef} className={`lv-p-prompt${q.passage ? " is-passage" : ""}`}>{lvPrompt(q.prompt)}</div>
      {q.passage && q.base ? <div className="lv-form-word">Form the word <span className="lv-cue">{q.base}</span></div> : null}
      {q.mode === "typed" ? (
        <form onSubmit={(e) => { e.preventDefault(); game.playerSubmitText(text); }}>
          <input className="m-answer" value={text} onChange={e => setText(e.target.value)} autoFocus
            placeholder={q.family === "Grammar" ? "Type the correct form…" : "Type the transformed word…"}
            type="text" autoComplete="off" autoCorrect="off" autoCapitalize="off" spellCheck={false} aria-label="Your answer" />
          <button type="submit" className="m-cta" style={{ marginTop: 14 }} disabled={!text.trim()}>
            <span>Submit answer</span><span className="arrow">→</span>
          </button>
        </form>
      ) : (
        <>
          <div className="lv-p-grid">
            {q.options.map((o, i) => (
              <button key={i} className="lv-p-opt" onClick={(e) => { tapFeedback("light", e); game.playerAnswer(i); }}>
                <Shape i={i} size={28} />
                <span className="lv-p-opt-text">{o}</span>
              </button>
            ))}
          </div>
          <div style={{ flex: 1 }} />
          <div style={{ textAlign: "center", fontSize: 13, color: "var(--ink-4)", marginTop: 12 }}>Tap your answer · shapes match the board</div>
        </>
      )}
    </div>
  );
}

function PlayerLocked({ game }) {
  const q = game.question;
  return (
    <div className="lv-p-pad">
      <div className="lv-p-center">
        <div className="lv-pulse"><div className="lv-pulse-dot" /></div>
        <div style={{ fontSize: 24, fontWeight: 800 }}>Answer locked</div>
        <div className="lv-locked-card">
          {q.mode === "typed"
            ? <span style={{ fontSize: 18, fontWeight: 700, flex: 1 }}>{game.youText}</span>
            : <><Shape i={game.youChoice} size={28} /><span style={{ fontSize: 18, fontWeight: 700, flex: 1 }}>{q.options[game.youChoice]}</span></>}
          <span style={{ color: "var(--accent-ink)", fontWeight: 700, fontSize: 14 }}>✓ in</span>
        </div>
        <div style={{ fontSize: 14, color: "var(--ink-3)" }}>Waiting for everyone else…</div>
      </div>
    </div>
  );
}

function PlayerReveal({ game, you, youRank }) {
  const q = game.question;
  const typed = q.mode === "typed";
  // verdict is the server's — never recomputed on the client
  const answered = game.lastAnswered;
  const correct = game.lastCorrect;
  plUseEffect(() => { haptic(correct ? "success" : "error"); }, []);
  if (!answered) {
    return (
      <div className="lv-p-pad">
        <div className="lv-p-center">
          <div className="lv-verdict no" style={{ background: "var(--bg-3)", color: "var(--ink-3)" }}>⏱</div>
          <div style={{ fontSize: 24, fontWeight: 800 }}>Too slow!</div>
          <div style={{ fontSize: 15, color: "var(--ink-3)" }}>No points this round — you'll catch the next one.</div>
          <div className="lv-rank-big" style={{ marginTop: 10 }}>You're <span className="em">{youRank}{ord(youRank)}</span></div>
        </div>
      </div>
    );
  }
  return (
    <div className="lv-p-pad">
      <div className="lv-p-center">
        <div className={`lv-verdict ${correct ? "ok" : "no"}`}>{correct ? "✓" : "✗"}</div>
        <div style={{ fontSize: 26, fontWeight: 800 }}>{correct ? "Correct!" : "Not this time"}</div>
        {correct ? (
          <>
            <div className="lv-points" style={{ color: "var(--ok)" }}>+{game.youGain}</div>
            <div className="lv-points-sub">{game.youSpeedBonus ? `includes +${game.youSpeedBonus} speed bonus` : "answered"}</div>
          </>
        ) : (
          <div className="lv-locked-card" style={{ justifyContent: "center", flexWrap: "wrap" }}>
            <span style={{ color: "var(--ink-3)" }}>Answer:</span>
            {!typed && <Shape i={q.correct} size={24} />}
            <span style={{ fontWeight: 700 }}>{typed ? q.answer : q.options[q.correct]}</span>
          </div>
        )}
        <div className="lv-rank-big" style={{ marginTop: 12 }}>You're <span className="em">{youRank}{ord(youRank)}</span> · {you.score.toLocaleString()} pts</div>
      </div>
    </div>
  );
}

function PlayerFinal({ game, you, youRank }) {
  plUseEffect(() => { haptic("celebrate"); }, []);
  const top = youRank <= 3;
  return (
    <div className="lv-p-pad">
      <div className="lv-p-center">
        <div className="lv-verdict ok" style={{ background: top ? "var(--accent)" : "var(--bg-3)", color: top ? "#fff" : "var(--ink)", fontSize: 40 }}>{youRank}{ord(youRank)}</div>
        <div style={{ fontSize: 26, fontWeight: 800 }}>{top ? "Podium finish!" : "Nice game!"}</div>
        <div className="lv-rank-big">{you.score.toLocaleString()} <span style={{ color: "var(--ink-3)", fontWeight: 600, fontSize: 18 }}>points</span></div>
        <div className="m-card is-accent" style={{ marginTop: 8, width: "100%" }}>
          <div className="m-card-eyebrow">Saved</div>
          <div style={{ fontSize: 15, fontWeight: 600, marginTop: 6 }}>This game counted toward your stats — {game.youCorrect}/{game.questionCount} correct added to your practice history.</div>
        </div>
      </div>
      <button className="m-cta" onClick={(e) => { tapFeedback("medium", e); game.reset(); }}><span>Back to practice</span><span className="arrow">→</span></button>
    </div>
  );
}

function ord(n) { return n === 1 ? "st" : n === 2 ? "nd" : n === 3 ? "rd" : "th"; }

Object.assign(window, { PlayerView });
