/* game-round.jsx — Generic round-based score tracker.
   Covers: Mäxchen, Can't Stop, Zombie Dice, Wizard, Hearts, Spades,
   UNO, Schafkopf, Doppelkopf, Skat, Phase 10, Cribbage,
   Catan (VP), Ticket to Ride, 7 Wonders, Wingspan, Scrabble.
   Exported: RoundGame
*/
const { useState: useRound, useEffect: useRoundFX, useRef: useRoundRef } = React;

/* ---------- helpers ---------- */
function roundTotals(rounds, n) {
  const tots = Array(n).fill(0);
  rounds.forEach((r) => r.scores.forEach((s, i) => { tots[i] += (typeof s === "number" ? s : 0); }));
  return tots;
}
function categoryTotals(cats, scores, n) {
  const tots = Array(n).fill(0);
  cats.forEach((_, ci) => scores[ci].forEach((s, pi) => { tots[pi] += (typeof s === "number" ? s : 0); }));
  return tots;
}
function leaderIdx(totals, highWins) {
  let best = highWins ? -Infinity : Infinity, idx = 0;
  totals.forEach((v, i) => { if (highWins ? v > best : v < best) { best = v; idx = i; } });
  return idx;
}

/* ============================================================
   Main RoundGame component
   ============================================================ */
function RoundGame({ sess, account, nav, onChange, lang, setLang }) {
  const cfg = sess.cfg || {};
  const mode = cfg.mode || "running"; // "running" | "vp" | "categories" | "phase"
  const n = sess.players.length;

  const [entryState, setEntryState] = useRound(null); // {type:"score"|"vp"|"cat", playerIdx, roundIdx, catIdx}
  const [endConfirm, setEndConfirm] = useRound(false);
  const [showResults, setShowResults] = useRound(sess.status === "finished");
  const [showRules, setShowRules] = useRound(false);
  const [toast, setToast] = useRound("");

  useRoundFX(() => { if (!toast) return; const tm = setTimeout(() => setToast(""), 1700); return () => clearTimeout(tm); }, [toast]);
  useRoundFX(() => { if (sess.status === "finished") setShowResults(true); }, [sess.status]);

  function patch(updater) {
    const next = JSON.parse(JSON.stringify(sess));
    updater(next);
    onChange(next);
  }

  /* -- running mode -- */
  function addRound() {
    patch((n) => {
      n.rounds.push({ scores: Array(n.players.length).fill(null) });
      n.currentRound = n.rounds.length;
    });
  }
  function setScore(roundIdx, playerIdx, val) {
    patch((s) => {
      s.rounds[roundIdx].scores[playerIdx] = val;
      // Auto-win when target reached (e.g. Catan at 10 VP)
      if (s.cfg?.winAt && s.cfg?.highWins !== false) {
        const tots = Array(s.players.length).fill(0);
        s.rounds.forEach(r => r.scores.forEach((sc, i) => { tots[i] += typeof sc === 'number' ? sc : 0; }));
        if (tots.some(v => v >= s.cfg.winAt)) {
          const wi = tots.indexOf(Math.max(...tots));
          s.status = 'finished'; s.winner = wi;
        }
      }
    });
  }

  /* -- VP mode -- */
  function setVP(playerIdx, val) {
    patch((s) => { s.currentVP[playerIdx] = val; });
  }

  /* -- categories mode -- */
  function setCatScore(catIdx, playerIdx, val) {
    patch((s) => { s.catScores[catIdx][playerIdx] = val; });
  }

  /* -- phase mode -- */
  function setPhase(playerIdx, val) {
    patch((s) => { s.phases[playerIdx] = Math.max(1, Math.min(10, val)); });
  }

  function endGame() {
    patch((s) => { s.status = "finished"; });
    setEndConfirm(false);
  }

  // Compute totals
  const totals = mode === "categories"
    ? categoryTotals(cfg.cats || [], sess.catScores || [], n)
    : mode === "vp" ? (sess.currentVP || Array(n).fill(0))
    : roundTotals(sess.rounds || [], n);
  const highWins = cfg.highWins !== false;
  const leader = totals.some((v) => v !== 0) ? leaderIdx(totals, highWins) : -1;

  const gameNameKey = "game." + sess.gameId + ".name";
  const roundCfg = CATALOG.byId(sess.gameId) || {};

  return (
    <div className="app">
      <AppHeader account={account} nav={nav} onSignOut={() => {}} crumb={t(gameNameKey)} lang={lang} setLang={setLang} />
      <main className="wrap" style={{ flex: 1, paddingBottom: 80 }}>
        <div className="game-top">
          <button className="btn ghost sm" onClick={() => nav("#/")} style={{ paddingLeft: 6 }}><Icon name="back" size={16} />{t("nav.dashboard")}</button>
          {mode !== "categories" && mode !== "vp" && (
            <span className="round-pill">{t("round.round", { n: sess.currentRound || 1 })}</span>
          )}
          <span className="round-pill">{highWins ? t("round.highwins") : t("round.lowwins")}</span>
          {cfg.winAt && <span className="round-pill">{t("round.target", { n: cfg.winAt })}</span>}
          <span style={{ flex: 1 }}></span>
          {sess.status === "active" && <button className="btn sm" onClick={() => setEndConfirm(true)}><Icon name="flag" size={15} />{t("round.endgame")}</button>}
          {sess.status === "finished" && <button className="btn sm primary" onClick={() => setShowResults(true)}><Icon name="crown" size={15} />{t("game.results")}</button>}
          {window.GAME_RULES?.[sess.gameId] && <button className="btn sm" onClick={() => setShowRules(true)}><Icon name="book" size={15} />{t("game.rules")}</button>}
        </div>

        {/* Player chips */}
        <div className="player-rail" style={{ marginBottom: 16 }}>
          {sess.players.map((p, i) => (
            <div key={i} className={"pchip" + (i === leader ? " lead" : "")}>
              <div className="ptop">
                <Avatar name={p.name} size="sm" idx={i} />
                <span className="pname">{p.name}</span>
                {i === leader && <span className="crown"><Icon name="crown" size={15} /></span>}
              </div>
              <div className="score">{totals[i]}</div>
            </div>
          ))}
        </div>

        {/* Main content by mode */}
        {mode === "categories" ? (
          <CategoriesTable sess={sess} cfg={cfg} n={n} totals={totals} onEdit={(ci, pi) => setEntryState({ type: "cat", catIdx: ci, playerIdx: pi })} disabled={sess.status === "finished"} />
        ) : mode === "vp" ? (
          <VPTable sess={sess} n={n} onEdit={(pi) => setEntryState({ type: "vp", playerIdx: pi })} disabled={sess.status === "finished"} />
        ) : mode === "phase" ? (
          <PhaseTable sess={sess} n={n} totals={totals} onEditScore={(ri, pi) => setEntryState({ type: "score", roundIdx: ri, playerIdx: pi })}
            onEditPhase={(pi) => setEntryState({ type: "phase", playerIdx: pi })} disabled={sess.status === "finished"} />
        ) : (
          <RunningTable sess={sess} n={n} totals={totals} onEdit={(ri, pi) => setEntryState({ type: "score", roundIdx: ri, playerIdx: pi })} disabled={sess.status === "finished"} />
        )}
      </main>

      {/* Action bar */}
      {sess.status === "active" && (
        <div className="action-bar">
          <div className="wrap inner">
            <span style={{ flex: 1 }}></span>
            {mode !== "vp" && mode !== "categories" && (
              <button className="btn" onClick={addRound}><Icon name="plus" size={16} />{t("round.addround")}</button>
            )}
            <button className="btn primary" onClick={() => setEndConfirm(true)}><Icon name="flag" size={15} />{t("round.endgame")}</button>
          </div>
        </div>
      )}

      {entryState && <RoundEntryModal state={entryState} sess={sess} cfg={cfg}
        onSave={(val) => {
          if (entryState.type === "score") setScore(entryState.roundIdx, entryState.playerIdx, val);
          else if (entryState.type === "vp") setVP(entryState.playerIdx, val);
          else if (entryState.type === "cat") setCatScore(entryState.catIdx, entryState.playerIdx, val);
          else if (entryState.type === "phase") setPhase(entryState.playerIdx, val);
          setEntryState(null);
        }}
        onClose={() => setEntryState(null)} />}

      {endConfirm && (
        <div className="scrim" onClick={() => setEndConfirm(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()}>
            <h3>{t("round.endsure")}</h3>
            <p className="muted" style={{ marginTop: 8, marginBottom: 20, fontSize: 14 }}>{t("round.highwins")}</p>
            <div style={{ display: "flex", gap: 10 }}>
              <button className="btn primary block" onClick={endGame}>{t("round.endgame")}</button>
              <button className="btn ghost block" onClick={() => setEndConfirm(false)}>{t("entry.cancel")}</button>
            </div>
          </div>
        </div>
      )}

      {showResults && <RoundResults sess={sess} totals={totals} highWins={highWins} onClose={() => setShowResults(false)} nav={nav} gameNameKey={gameNameKey} />}
      {showRules && <GameRulesModal gameId={sess.gameId} lang={lang} onClose={() => setShowRules(false)} />}
      <Toast msg={toast} />
    </div>
  );
}

/* ---------- Running Table ---------- */
function RunningTable({ sess, n, totals, onEdit, disabled }) {
  const rounds = sess.rounds || [];
  const signed = sess.cfg?.signed;
  return (
    <div className="sheet-wrap">
      <table className="sheet">
        <thead>
          <tr>
            <th className="cat-cell" style={{ textAlign: "left", background: "var(--surface-2)", minWidth: 80 }}>#</th>
            {sess.players.map((p, i) => <th key={i}><Avatar name={p.name} idx={i} size="sm" /></th>)}
          </tr>
        </thead>
        <tbody>
          {rounds.map((r, ri) => (
            <tr key={ri}>
              <td className="cat-cell" style={{ fontSize: 13, color: "var(--muted)" }}>{t("round.round", { n: ri + 1 })}</td>
              {r.scores.map((s, pi) => (
                <td key={pi} className={"scell" + (s === null ? " empty" : " filled") + (disabled ? " locked" : "")}
                  style={{ color: signed && s < 0 ? "var(--strike)" : undefined }}
                  onClick={() => !disabled && onEdit(ri, pi)}>
                  {s !== null ? s : ""}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
        <tfoot>
          <tr className="total-row">
            <td className="cat-cell">{t("round.total")}</td>
            {totals.map((v, i) => <td key={i} className="scell">{v}</td>)}
          </tr>
        </tfoot>
      </table>
    </div>
  );
}

/* ---------- VP Table ---------- */
function VPTable({ sess, n, onEdit, disabled }) {
  const vps = sess.currentVP || Array(n).fill(0);
  return (
    <div className="card" style={{ padding: 20 }}>
      <div className="eyebrow" style={{ marginBottom: 16 }}>{t("round.score")}</div>
      <div style={{ display: "flex", flex: 1, gap: 12 }}>
        {sess.players.map((p, i) => (
          <div key={i} className={"card" + (disabled ? "" : " game-card")} style={{ flex: 1, padding: "16px 12px", textAlign: "center", cursor: disabled ? "default" : "pointer" }} onClick={() => !disabled && onEdit(i)}>
            <Avatar name={p.name} idx={i} />
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 36, marginTop: 10 }}>{vps[i]}</div>
            <div style={{ fontSize: 13, marginTop: 4, color: "var(--muted)" }}>{p.name}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- Categories Table ---------- */
function CategoriesTable({ sess, cfg, n, totals, onEdit, disabled }) {
  const cats = cfg.cats || [];
  const scores = sess.catScores || [];
  return (
    <div className="sheet-wrap">
      <table className="sheet">
        <thead>
          <tr>
            <th className="cat-cell" style={{ textAlign: "left", background: "var(--surface-2)" }}>{t("round.cats")}</th>
            {sess.players.map((p, i) => <th key={i}><span style={{ fontSize: 13 }}>{p.name}</span></th>)}
          </tr>
        </thead>
        <tbody>
          {cats.map((cat, ci) => (
            <tr key={ci}>
              <td className="cat-cell"><span className="clabel">{cat}</span></td>
              {Array(n).fill(0).map((_, pi) => {
                const v = scores[ci] ? scores[ci][pi] : null;
                return <td key={pi} className={"scell" + (v === null ? " empty" : " filled") + (disabled ? " locked" : "")}
                  onClick={() => !disabled && onEdit(ci, pi)}>{v !== null ? v : ""}</td>;
              })}
            </tr>
          ))}
        </tbody>
        <tfoot>
          <tr className="total-row">
            <td className="cat-cell">{t("round.total")}</td>
            {totals.map((v, i) => <td key={i} className="scell">{v}</td>)}
          </tr>
        </tfoot>
      </table>
    </div>
  );
}

/* ---------- Phase Table (Phase 10) ---------- */
function PhaseTable({ sess, n, totals, onEditScore, onEditPhase, disabled }) {
  const rounds = sess.rounds || [];
  const phases = sess.phases || Array(n).fill(1);
  return (
    <div>
      {/* Phase progress */}
      <div className="card" style={{ padding: 16, marginBottom: 14, display: "flex", gap: 12, flexWrap: "wrap" }}>
        {sess.players.map((p, i) => (
          <div key={i} style={{ flex: 1, minWidth: 120, textAlign: "center", cursor: disabled ? "default" : "pointer" }} onClick={() => !disabled && onEditPhase(i)}>
            <div style={{ fontSize: 12, fontWeight: 600, color: "var(--muted)", marginBottom: 4 }}>{p.name}</div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20 }}>Phase {phases[i]}/10</div>
            <div style={{ height: 6, borderRadius: 3, background: "var(--line-2)", marginTop: 6 }}>
              <div style={{ width: ((phases[i] - 1) / 10 * 100) + "%", height: "100%", borderRadius: 3, background: "var(--accent)", transition: "width .3s" }}></div>
            </div>
          </div>
        ))}
      </div>
      <RunningTable sess={sess} n={n} totals={totals} onEdit={onEditScore} disabled={disabled} />
    </div>
  );
}

/* ---------- Entry Modal ---------- */
function RoundEntryModal({ state, sess, cfg, onSave, onClose }) {
  const [val, setVal]     = useRound("");
  const [total, setTotal] = useRound(0);

  const signed = cfg.signed;
  const isPhase = state.type === "phase";
  const isVP = state.type === "vp";
  const isUNO = cfg.unoMode === true;
  const player = sess.players[state.playerIdx] || {};
  const catName = state.type === "cat" && cfg.cats ? cfg.cats[state.catIdx] : "";

  function submit() {
    if (val.trim() === "") return;
    const n = Number(val);
    if (isNaN(n)) return;
    onSave(n);
  }

  // Phase: tap 1-10
  if (isPhase) {
    return (
      <div className="scrim" onClick={onClose}>
        <div className="modal" onClick={e => e.stopPropagation()}>
          <h3 style={{ marginBottom: 4 }}>{t("round.phase")}</h3>
          <p className="muted" style={{ fontSize: 14, marginBottom: 14 }}>{player.name}</p>
          <div className="entry-grid" style={{ gridTemplateColumns: "repeat(5,1fr)", margin:"0 0 14px" }}>
            {Array.from({length:10},(_,i)=>i+1).map(v => (
              <div key={v} className="entry-opt" style={{height:48}} onClick={() => onSave(v)}>
                <span className="pts" style={{fontSize:18}}>{v}</span>
              </div>
            ))}
          </div>
          <button className="btn ghost block" onClick={onClose}>{t("entry.cancel")}</button>
        </div>
      </div>
    );
  }

  // VP: tap 0-10 (absolute VP values)
  if (isVP) {
    return (
      <div className="scrim" onClick={onClose}>
        <div className="modal" onClick={e => e.stopPropagation()}>
          <h3 style={{ marginBottom: 4 }}>{t("round.score")}</h3>
          <p className="muted" style={{ fontSize: 14, marginBottom: 14 }}>{player.name}</p>
          <div className="entry-grid" style={{ gridTemplateColumns: "repeat(5,1fr)", margin:"0 0 14px" }}>
            {Array.from({length:11},(_,i)=>i).map(v => (
              <div key={v} className="entry-opt" style={{height:48}} onClick={() => onSave(v)}>
                <span className="pts" style={{fontSize:18}}>{v}</span>
              </div>
            ))}
          </div>
          <button className="btn ghost block" onClick={onClose}>{t("entry.cancel")}</button>
        </div>
      </div>
    );
  }

  // UNO: winner button + tap-to-add card values
  if (isUNO) {
    return (
      <div className="scrim" onClick={onClose}>
        <div className="modal wide" onClick={e => e.stopPropagation()}>
          <h3 style={{ marginBottom: 14 }}>{player.name}</h3>
          <button className="btn primary lg block" style={{ marginBottom: 18 }}
            onClick={() => onSave(0)}>🏆 {t("uno.winner")}</button>
          <div className="eyebrow" style={{ marginBottom: 8 }}>{t("uno.penalty")}</div>
          <div style={{ background:"var(--surface-2)", borderRadius:"var(--r)", padding:"10px 14px",
            fontFamily:"var(--font-display)", fontWeight:700, fontSize:28, textAlign:"right", marginBottom:10,
            border:"1px solid var(--line)", letterSpacing:"-0.02em" }}>{total} Pts</div>
          {/* Number cards: face value */}
          <div style={{ display:"grid", gridTemplateColumns:"repeat(5,1fr)", gap:7, marginBottom:8 }}>
            {[0,1,2,3,4,5,6,7,8,9].map(v => (
              <button key={v} className="btn" style={{ height:46, fontSize:17, fontWeight:700 }}
                onClick={() => setTotal(t2 => t2 + v)}>+{v}</button>
            ))}
          </div>
          {/* Action & Wild cards */}
          <div style={{ display:"flex", gap:8, marginBottom:14 }}>
            <button className="btn" style={{ flex:1, height:46, background:"var(--accent-50)", borderColor:"var(--accent-100)", fontWeight:700 }}
              onClick={() => setTotal(t2 => t2 + 20)}>+20 Action</button>
            <button className="btn" style={{ flex:1, height:46, background:"var(--accent-50)", borderColor:"var(--accent-100)", fontWeight:700 }}
              onClick={() => setTotal(t2 => t2 + 50)}>+50 Wild</button>
            <button className="btn sm ghost" onClick={() => setTotal(0)}>C</button>
          </div>
          <div style={{ display:"flex", gap:10 }}>
            <button className="btn primary block" onClick={() => onSave(total)} disabled={total === 0}>{t("entry.done")}</button>
            <button className="btn ghost block" onClick={onClose}>{t("entry.cancel")}</button>
          </div>
        </div>
      </div>
    );
  }

  // Games with quick options (Schnapsen: 1,2,3 / Catan: 1,2)
  const cfgQuick = cfg.quickOpts;

  return (
    <div className="scrim" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <h3 style={{ marginBottom: 4 }}>{catName || t("round.score")}</h3>
        <p className="muted" style={{ fontSize: 14, marginBottom: 12 }}>{t("round.enterprompt", { name: player.name || "" })}</p>

        {/* Quick options row */}
        {cfgQuick && (
          <div style={{display:"flex", gap:8, marginBottom:12, flexWrap:"wrap"}}>
            {cfgQuick.map(v => (
              <button key={v} className="btn primary" style={{flex:1,height:52,fontSize:18,fontWeight:700}}
                onClick={() => onSave(v)}>{v > 0 ? '+' : ''}{v}</button>
            ))}
            {signed && [-1,-2,-3].map(v => (
              <button key={v} className="btn" style={{flex:1,height:52,fontSize:18,fontWeight:700,color:"var(--strike)"}}
                onClick={() => onSave(v)}>{v}</button>
            ))}
          </div>
        )}

        {/* NumPad */}
        <NumPad value={val} onChange={setVal} allowNegative={!!signed} />
        <div style={{ display:"flex", gap:10, marginTop:10 }}>
          <button className="btn primary block" onClick={submit}>{t("entry.done")}</button>
          <button className="btn ghost block" onClick={onClose}>{t("entry.cancel")}</button>
        </div>
      </div>
    </div>
  );
}

/* ---------- Results ---------- */
function RoundResults({ sess, totals, highWins, onClose, nav, gameNameKey }) {
  const ranked = sess.players.map((p, i) => ({ name: p.name, total: totals[i], idx: i }))
    .sort((a, b) => highWins ? b.total - a.total : a.total - b.total);
  return (
    <div className="scrim" onClick={onClose}>
      <div className="modal wide" onClick={(e) => e.stopPropagation()}>
        <div style={{ textAlign: "center", marginBottom: 6 }}>
          <div style={{ color: "var(--gold)", display: "flex", justifyContent: "center" }}><Icon name="crown" size={34} /></div>
          <h3 style={{ fontSize: 24, marginTop: 8 }}>{t("res.over")}</h3>
          <p className="muted" style={{ fontSize: 14 }}>{t("res.wins", { name: ranked[0].name, n: ranked[0].total })}</p>
        </div>
        <div style={{ margin: "18px 0" }}>
          {ranked.map((r, pos) => (
            <div className="results-row" key={r.idx}>
              <span className={"rank-badge" + (pos === 0 ? " gold" : "")}>{pos + 1}</span>
              <Avatar name={r.name} idx={r.idx} />
              <span style={{ fontWeight: 700, flex: 1 }}>{r.name}</span>
              <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 22 }}>{r.total}</span>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn primary block" onClick={() => nav("#/")}>{t("res.newgame")}</button>
          <button className="btn ghost block" onClick={onClose}>{t("res.close")}</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RoundGame, RoundResults });
