/* game-racket.jsx — Tennis & Table Tennis tracker. */
const { useState: useRacket, useEffect: useRacketFX } = React;

const TENNIS_PTS = [0, 15, 30, 40]; // display labels

function RacketGame({ sess, account, nav, onChange, lang, setLang }) {
  const [toast, setToast] = useRacket("");
  const [showRules, setShowRules] = useRacket(false);
  const [showResults, setShowResults] = useRacket(sess.status === "finished");
  useRacketFX(() => { if (!toast) return; const tm = setTimeout(() => setToast(""), 1700); return () => clearTimeout(tm); }, [toast]);
  useRacketFX(() => { if (sess.status === "finished") setShowResults(true); }, [sess.status]);

  const isTennis = sess.sport === "tennis";
  const a = sess.players[0].name;
  const b = sess.players[1].name;
  const gameId = sess.gameId || (isTennis ? "tennis" : "tischtennis");

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

  function addPoint(pi) {
    patch((s) => {
      if (s.status === "finished") return;
      const opponent = 1 - pi;
      if (isTennis) { scoreTennisPoint(s, pi, opponent); }
      else { scoreTTPoint(s, pi, opponent); }
    });
  }

  function scoreTennisPoint(s, pi, opp) {
    const g = s.currentGame;
    if (s.tiebreak) {
      g.pts[pi]++;
      if (g.pts[pi] >= 7 && g.pts[pi] - g.pts[opp] >= 2) { winTennisGame(s, pi); }
      return;
    }
    if (s.deuce) {
      if (s.advantage === pi)  { winTennisGame(s, pi); }
      else if (s.advantage === opp) { s.advantage = -1; } // back to deuce
      else { s.advantage = pi; }                           // from deuce → advantage
      return;
    }
    g.pts[pi]++;
    // Both at 40 (3) → deuce; scorer gets advantage immediately
    if (g.pts[pi] >= 4 && g.pts[opp] >= 3) { s.deuce = true; s.advantage = pi; return; }
    if (g.pts[pi] >= 4) { winTennisGame(s, pi); }
  }

  function winTennisGame(s, pi) {
    const opp = 1 - pi;
    s.currentSet.games[pi]++;
    s.currentGame = { pts: [0, 0] };
    s.deuce = false; s.advantage = -1; s.tiebreak = false;
    const [ga, gb] = s.currentSet.games;
    const maxG = Math.max(ga, gb), minG = Math.min(ga, gb);
    if (s.currentSet.tiebreak && maxG === 7) { winTennisSet(s, pi); return; }
    if (ga === 6 && gb === 6) { s.currentSet.tiebreak = true; s.currentGame.pts = [0, 0]; return; }
    if (maxG >= 6 && maxG - minG >= 2) { winTennisSet(s, pi); }
  }

  function winTennisSet(s, pi) {
    const opp = 1 - pi;
    s.sets.push({ games: [...s.currentSet.games] });
    s.setWins[pi]++;
    s.currentSet = { games: [0, 0], tiebreak: false };
    s.currentGame = { pts: [0, 0] };
    s.deuce = false; s.advantage = -1; s.tiebreak = false;
    if (s.setWins[pi] >= Math.ceil(s.bestOf / 2)) {
      s.status = "finished"; s.winner = pi;
    }
  }

  function scoreTTPoint(s, pi, opp) {
    s.currentGame.score[pi]++;
    const [sa, sb] = s.currentGame.score;
    const max = Math.max(sa, sb), min = Math.min(sa, sb);
    if (max >= s.target && max - min >= 2) {
      s.games.push({ score: [...s.currentGame.score] });
      s.gameWins[pi]++;
      s.currentGame = { score: [0, 0] };
      if (s.gameWins[pi] >= Math.ceil(s.bestOf / 2)) {
        s.status = "finished"; s.winner = pi;
      }
    }
  }

  // Display helpers
  function currentScoreLabel(pi) {
    if (isTennis) {
      if (sess.tiebreak) return sess.currentGame.pts[pi];
      if (sess.deuce) {
        if (sess.advantage === pi)  return t("racket.advantage");
        if (sess.advantage === -1)  return t("racket.deuce");
        return "40"; // opponent has advantage
      }
      return TENNIS_PTS[sess.currentGame.pts[pi]] ?? 0;
    }
    return sess.currentGame.score[pi];
  }

  const sets = isTennis ? sess.sets : sess.games;
  const setWins = isTennis ? sess.setWins : sess.gameWins;
  const setWord = isTennis ? t("racket.set") : t("racket.game");
  const bestOfN = sess.bestOf;
  const finished = sess.status === "finished";

  return (
    <div className="app">
      <AppHeader account={account} nav={nav} onSignOut={() => {}} crumb={t("game." + (sess.gameId || (isTennis ? "tennis" : "tischtennis")) + ".name")} lang={lang} setLang={setLang} />
      <main className="wrap" style={{ flex: 1, paddingBottom: 30, display: "flex", flexDirection: "column" }}>
        <div className="game-top">
          <button className="btn ghost sm" onClick={() => nav("#/")} style={{ paddingLeft: 6 }}><Icon name="back" size={16} />{t("nav.dashboard")}</button>
          <span className="round-pill">{t("racket.bestof", { n: bestOfN })} {setWord}s</span>
          {finished && <span className="tag live">🏆 {sess.players[sess.winner].name}</span>}
          <span style={{ flex: 1 }}></span>
          <button className="btn sm" onClick={() => setShowRules(true)}><Icon name="book" size={15}/>{t("game.rules")}</button>
        </div>

        {/* Set score history */}
        {sets.length > 0 && (
          <div style={{ display: "flex", gap: 8, marginBottom: 12, flexWrap: "wrap" }}>
            {sets.map((s, i) => (
              <div key={i} className="card" style={{ padding: "6px 14px", fontSize: 13, fontFamily: "var(--font-display)", fontWeight: 600 }}>
                {setWord} {i + 1}: {s.games ? s.games.join("–") : s.score.join("–")}
              </div>
            ))}
          </div>
        )}

        {/* Set win pips */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 24, marginBottom: 12 }}>
          <WinPips wins={setWins[0]} total={Math.ceil(bestOfN / 2)} />
          <span className="muted" style={{ fontFamily: "var(--font-display)", fontWeight: 600 }}>{setWins[0]} : {setWins[1]}</span>
          <WinPips wins={setWins[1]} total={Math.ceil(bestOfN / 2)} flip />
        </div>

        {/* Game score */}
        {!finished && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr auto 1fr", gap: 16, flex: 1, margin: "8px 0" }}>
            <RacketPanel name={a} pi={0} currentScore={currentScoreLabel(0)} setGames={isTennis ? sess.currentSet.games[0] : sess.currentGame.score[0]}
              onPoint={() => addPoint(0)} disabled={finished} isTennis={isTennis} active={isTennis ? (sess.currentGame.pts[0] > sess.currentGame.pts[1]) : (sess.currentGame.score[0] > sess.currentGame.score[1])} />
            <div style={{ display: "flex", alignItems: "center" }}>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 24, color: "var(--faint)" }}>:</div>
            </div>
            <RacketPanel name={b} pi={1} currentScore={currentScoreLabel(1)} setGames={isTennis ? sess.currentSet.games[1] : sess.currentGame.score[1]}
              onPoint={() => addPoint(1)} disabled={finished} isTennis={isTennis} active={isTennis ? (sess.currentGame.pts[1] > sess.currentGame.pts[0]) : (sess.currentGame.score[1] > sess.currentGame.score[0])} />
          </div>
        )}

        {/* Current set games (tennis) */}
        {isTennis && !finished && (
          <div style={{ textAlign: "center", marginTop: 8, fontSize: 14, color: "var(--muted)" }}>
            {t("racket.set")} {sets.length + 1}: <b style={{ color: "var(--ink)", fontFamily: "var(--font-display)" }}>{sess.currentSet.games[0]} – {sess.currentSet.games[1]}</b>
            {sess.currentSet.tiebreak && <span className="tag live" style={{ marginLeft: 8 }}>{t("racket.tiebreak")}</span>}
          </div>
        )}

        {showRules && <GameRulesModal gameId={sess.gameId || (isTennis?"tennis":"tischtennis")} lang={lang} onClose={()=>setShowRules(false)} />}

        {finished && (
          <div className="card" style={{ padding: 24, textAlign: "center", margin: "20px 0" }}>
            <div style={{ color: "var(--gold)" }}><Icon name="crown" size={32} /></div>
            <h3 style={{ marginTop: 8 }}>{t("racket.matchwin", { name: sess.players[sess.winner].name })}</h3>
            <button className="btn primary" style={{ marginTop: 16 }} onClick={() => nav("#/new/" + (isTennis ? "tennis" : "tischtennis"))}>{t("res.newgame")}</button>
          </div>
        )}
      </main>
    </div>
  );
}

function RacketPanel({ name, pi, currentScore, setGames, onPoint, disabled, isTennis, active }) {
  return (
    <div className={"card tfb-side" + (active ? " tfb-active" : "")}
      style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 12, padding: "20px 10px" }}>
      <Avatar name={name} idx={pi} />
      {/* current point score */}
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 48, lineHeight: 1, letterSpacing: "-0.04em", color: active ? "var(--accent)" : "var(--ink)", minWidth: 80, textAlign: "center" }}>
        {currentScore}
      </div>
      {isTennis && (
        <div style={{ fontSize: 13, color: "var(--muted)", fontFamily: "var(--font-display)" }}>
          {t("racket.set")} {setGames}
        </div>
      )}
      <div style={{ fontWeight: 700, fontSize: 14 }}>{name}</div>
      <button className="btn primary lg block" style={{ fontSize: 16 }} disabled={disabled} onClick={onPoint}>
        +1 {t("racket.point")}
      </button>
    </div>
  );
}

Object.assign(window, { RacketGame, RacketPanel });
