/* screens-tischfussball.jsx — Tischfußball: best of 3, first to 9 goals, team-aware. */
const { useState: useStateTFB, useEffect: useEffectTFB } = React;

/* Compute team arrays from players (players 1-2 → team A, 3-4 → team B) */
function getTeams(players) {
  const n = players.length;
  const split = n <= 2 ? 1 : 2;
  return [players.slice(0, split), players.slice(split)];
}
function teamName(team) { return team.map((p) => p.name).filter(Boolean).join(" & ") || "Team"; }

function TischfussballGame({ sess, account, nav, onChange, lang, setLang }) {
  const [showRules, setShowRules] = useStateTFB(false);
  const [showHistory, setShowHistory] = useStateTFB(false);
  const teams = getTeams(sess.players);

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

  function addGoal(teamIdx) {
    patch((n) => {
      n.current.scores[teamIdx]++;
      n.current.lastGoal = teamIdx;
      if (n.current.scores[teamIdx] >= 9) {
        n.matches.push({ scores: [...n.current.scores], winner: teamIdx });
        n.wins[teamIdx]++;
        if (n.wins[teamIdx] >= 2) {
          n.status = "finished";
          n.winner = teamIdx;
        } else {
          n.current = { scores: [0, 0], lastGoal: null };
          n.round = n.matches.length + 1;
        }
      }
    });
  }

  function undoGoal() {
    patch((n) => {
      if (n.current.lastGoal === null || n.current.lastGoal === undefined) return;
      const p = n.current.lastGoal;
      if (n.current.scores[p] > 0) n.current.scores[p]--;
      n.current.lastGoal = null;
    });
  }

  const [sa, sb] = sess.current.scores;
  const matchNum = sess.matches.length + 1;
  const finished = sess.status === "finished";
  const winnerName = finished ? teamName(teams[sess.winner]) : "";

  return (
    <div className="app">
      <AppHeader account={account} nav={nav} onSignOut={() => {}} crumb={t("game.tfb.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>
          {!finished && <span className="round-pill">{t("tfb.match", { n: matchNum })}</span>}
          <span className="round-pill">{t("tfb.bestof")}</span>
          <span style={{ flex: 1 }}></span>
          <button className="btn sm" onClick={() => setShowRules(true)}><Icon name="book" size={15} />{t("game.rules")}</button>
          <button className="btn sm" onClick={() => setShowHistory(true)}><Icon name="book" size={15} />{t("tfb.history")}</button>
          {finished && <span className="tag live" style={{ fontSize: 14, padding: "8px 14px" }}>🏆 {winnerName}</span>}
        </div>

        {/* series progress */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 24, marginBottom: 8 }}>
          <WinPips wins={sess.wins[0]} total={2} />
          <span className="muted" style={{ fontSize: 14, fontFamily: "var(--font-display)", fontWeight: 600, whiteSpace: "nowrap" }}>
            {sess.wins[0]} : {sess.wins[1]}
          </span>
          <WinPips wins={sess.wins[1]} total={2} flip />
        </div>

        {/* match over banner */}
        {!finished && (sa >= 9 || sb >= 9) && (
          <div style={{ background: "var(--accent-50)", border: "1.5px solid var(--accent-100)", borderRadius: "var(--r-lg)", padding: "14px 20px", display: "flex", alignItems: "center", gap: 12, margin: "4px 0 10px" }}>
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15, color: "var(--accent)" }}>
              🎉 {t("tfb.matchwin", { name: sa >= 9 ? teamName(teams[0]) : teamName(teams[1]), n: matchNum - 1 })}
            </span>
          </div>
        )}

        {/* game board */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr auto 1fr", gap: 12, flex: 1, margin: "8px 0" }}>
          <TeamPanel teamPlayers={teams[0]} score={sa} teamIdx={0} onGoal={addGoal}
            disabled={finished || sa >= 9 || sb >= 9} active={sa > sb} />
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 28, color: "var(--faint)" }}>:</div>
          </div>
          <TeamPanel teamPlayers={teams[1]} score={sb} teamIdx={1} onGoal={addGoal}
            disabled={finished || sa >= 9 || sb >= 9} active={sb > sa} />
        </div>

        {/* action bar */}
        <div className="action-bar">
          <div className="wrap inner">
            <span className="turn-label muted" style={{ fontSize: 14 }}>
              {finished ? t("tfb.serieswin", { name: winnerName }) : t("tfb.match", { n: matchNum })}
            </span>
            <span style={{ flex: 1 }}></span>
            <button className="btn sm ghost" disabled={sess.current.lastGoal === null || sess.current.lastGoal === undefined} onClick={undoGoal}>
              <Icon name="back" size={15} />{t("tfb.undo")}
            </button>
            {finished && <button className="btn primary" onClick={() => nav("#/")}><Icon name="flag" size={15} />{t("tfb.done")}</button>}
          </div>
        </div>
      </main>

      {showHistory && <TFBHistory sess={sess} teams={teams} onClose={() => setShowHistory(false)} />}
      {showRules && <GameRulesModal gameId="tfb" lang={lang} onClose={() => setShowRules(false)} />}
    </div>
  );
}

function TeamPanel({ teamPlayers, score, teamIdx, onGoal, disabled, active }) {
  const name = teamName(teamPlayers);
  const won = score >= 9;
  const barH = Math.min(score / 9, 1) * 100;

  return (
    <div className={"card tfb-side" + (active ? " tfb-active" : "")} style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 12, padding: "22px 12px", minHeight: 280, position: "relative" }}>
      {won && <div style={{ position: "absolute", top: 10, right: 10 }}><span className="tag live">🏆</span></div>}

      {/* player avatars */}
      <div style={{ display: "flex", gap: -4 }}>
        {teamPlayers.map((p, i) => <Avatar key={i} name={p.name} idx={teamIdx === 0 ? i : i + 2} size={teamPlayers.length > 1 ? "sm" : ""} />)}
      </div>

      {/* score */}
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: won ? 56 : 48, letterSpacing: "-0.04em", lineHeight: 1, color: active ? "var(--accent)" : "var(--ink)", transition: "color .3s" }}>
        {score}
      </div>

      {/* progress bar */}
      <div style={{ width: 7, borderRadius: 4, alignSelf: "stretch", background: "var(--bg-2)", overflow: "hidden", minHeight: 60, position: "relative" }}>
        <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: barH + "%", background: active ? "var(--accent)" : "var(--line-2)", transition: "height .3s ease, background .3s" }}></div>
      </div>

      {/* team name */}
      <div style={{ fontWeight: 700, fontSize: 14, textAlign: "center", lineHeight: 1.3 }}>{name}</div>

      <button className="btn primary lg block" style={{ fontSize: 20, height: 58, borderRadius: "var(--r-lg)" }}
        disabled={disabled} onClick={() => onGoal(teamIdx)}>
        +1 {t("tfb.goal")}
      </button>
    </div>
  );
}

function WinPips({ wins, total, flip }) {
  const pips = Array.from({ length: total }, (_, i) => i < wins);
  if (flip) pips.reverse();
  return (
    <div style={{ display: "flex", gap: 6 }}>
      {pips.map((filled, i) => (
        <div key={i} style={{ width: 14, height: 14, borderRadius: "50%", background: filled ? "var(--accent)" : "var(--line-2)", transition: "background .3s" }}></div>
      ))}
    </div>
  );
}

function TFBHistory({ sess, teams, onClose }) {
  return (
    <div className="scrim" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
          <h3>{t("tfb.history")}</h3>
          <button className="iconbtn" style={{ marginLeft: "auto", width: 32, height: 32 }} onClick={onClose}><Icon name="x" size={16} /></button>
        </div>
        {sess.matches.length === 0 && <p className="muted" style={{ fontSize: 14 }}>—</p>}
        {sess.matches.map((m, i) => (
          <div className="results-row" key={i}>
            <span className="rank-badge">{i + 1}</span>
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, flex: 1 }}>{t("tfb.match", { n: i + 1 })}</span>
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 18 }}>{m.scores[0]} : {m.scores[1]}</span>
            <Avatar name={teamName(teams[m.winner])} idx={m.winner} size="sm" />
          </div>
        ))}
        {sess.status === "finished" && (
          <div style={{ marginTop: 14, padding: "12px 14px", background: "var(--accent-50)", borderRadius: "var(--r)", border: "1px solid var(--accent-100)" }}>
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, color: "var(--accent)" }}>
              🏆 {t("tfb.serieswin", { name: teamName(teams[sess.winner]) })}
            </span>
          </div>
        )}
        <button className="btn ghost block" style={{ marginTop: 14 }} onClick={onClose}>{t("res.close")}</button>
      </div>
    </div>
  );
}

Object.assign(window, { TischfussballGame, TeamPanel, WinPips, TFBHistory });
