import { COLOR_GLYPHS, COLOR_HEX, EXPEDITION_NAMES_KO } from "../game/cards";
import { scoreBreakdown } from "../game/scoring";
import type { GameState } from "../game/types";

function signed(value: number): string {
  return value > 0 ? `+${value}` : String(value);
}

function scoreClass(value: number): string {
  return value < 0 ? "is-negative" : value > 0 ? "is-positive" : "";
}

/** Per-expedition breakdown of one round's board: cards (with the wager multiplier)
 *  and score, for both players. */
function ColorTable({ state }: { state: GameState }) {
  const you = scoreBreakdown(state, 0);
  const rival = scoreBreakdown(state, 1);
  return (
    <table className="result-table">
      <thead>
        <tr>
          <th scope="col">원정</th>
          <th scope="col" colSpan={2}>나</th>
          <th scope="col" colSpan={2}>상대</th>
        </tr>
        <tr className="result-table__subhead">
          <th scope="col" />
          <th scope="col">카드</th>
          <th scope="col">점수</th>
          <th scope="col">카드</th>
          <th scope="col">점수</th>
        </tr>
      </thead>
      <tbody>
        {EXPEDITION_NAMES_KO.map((name, color) => {
          const mine = you.colors[color];
          const theirs = rival.colors[color];
          const cards = (c: { cards: number; handshakes: number }) =>
            c.cards ? `${c.cards}${c.handshakes ? ` ·×${c.handshakes + 1}` : ""}` : "—";
          return (
            <tr key={name}>
              <th scope="row" style={{ "--lane-color": COLOR_HEX[color] } as React.CSSProperties}>
                <i>{COLOR_GLYPHS[color]}</i>{name}
              </th>
              <td className="result-table__detail">{cards(mine)}</td>
              <td className={scoreClass(mine.score)}>{mine.cards ? signed(mine.score) : "—"}</td>
              <td className="result-table__detail">{cards(theirs)}</td>
              <td className={scoreClass(theirs.score)}>{theirs.cards ? signed(theirs.score) : "—"}</td>
            </tr>
          );
        })}
      </tbody>
      <tfoot>
        <tr>
          <th scope="row">합계</th>
          <td className="result-table__detail" />
          <td>{signed(you.total)}</td>
          <td className="result-table__detail" />
          <td>{signed(rival.total)}</td>
        </tr>
      </tfoot>
    </table>
  );
}

/** The pause between rounds: the finished round's per-colour scores and where the
 *  match stands, held until the player chooses to deal the next round. */
export function RoundOverlay({
  state,
  roundIdx,
  totalRounds,
  matchTotals,
  onContinue,
}: {
  state: GameState;
  roundIdx: number;
  totalRounds: number;
  matchTotals: [number, number];
  onContinue: () => void;
}) {
  return (
    <div className="result-overlay">
      <section className="result-card" aria-label={`${roundIdx + 1}라운드 결과`}>
        <header className="result-card__head">
          <p>{roundIdx + 1}라운드 종료</p>
          <strong>{matchTotals[0]} <i>:</i> {matchTotals[1]}</strong>
          <small className="result-card__banked">누적 점수 · 나 {matchTotals[0]} · 상대 {matchTotals[1]}</small>
        </header>
        <ColorTable state={state} />
        <footer className="result-card__foot">
          <button type="button" className="is-primary" onClick={onContinue}>
            {roundIdx + 1 >= totalRounds - 1 ? "마지막 라운드로" : `${roundIdx + 2}라운드 시작`}
          </button>
        </footer>
      </section>
    </div>
  );
}

/** The end of the game: the outcome, the final round's per-colour breakdown, and --
 *  for a match -- a single table summarising all three rounds. */
export function ResultCard({
  state,
  outcome,
  roundHistory,
  totalRounds,
  onPlayAgain,
}: {
  state: GameState;
  outcome: string;
  /** Each finished round's [you, rival] total, including this last one. */
  roundHistory: [number, number][];
  totalRounds: number;
  onPlayAgain: () => void;
}) {
  const isMatch = totalRounds > 1;
  const totals = roundHistory.reduce(
    (acc, [you, rival]) => [acc[0] + you, acc[1] + rival] as [number, number],
    [0, 0] as [number, number],
  );

  return (
    <div className="result-overlay">
      <section className="result-card" aria-label="최종 결과">
        <header className="result-card__head">
          <p>{isMatch ? `${totalRounds}라운드 매치 종료` : "게임 종료"}</p>
          <h1>{outcome}</h1>
          <strong>{totals[0]} <i>:</i> {totals[1]}</strong>
        </header>

        {isMatch ? (
          <table className="result-table result-table--rounds">
            <thead>
              <tr>
                <th scope="col">라운드</th>
                <th scope="col">나</th>
                <th scope="col">상대</th>
              </tr>
            </thead>
            <tbody>
              {roundHistory.map(([you, rival], round) => (
                <tr key={round}>
                  <th scope="row">{round + 1}라운드</th>
                  <td className={scoreClass(you)}>{signed(you)}</td>
                  <td className={scoreClass(rival)}>{signed(rival)}</td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr className="result-table__match">
                <th scope="row">합계</th>
                <td>{signed(totals[0])}</td>
                <td>{signed(totals[1])}</td>
              </tr>
            </tfoot>
          </table>
        ) : (
          <ColorTable state={state} />
        )}

        <footer className="result-card__foot">
          <button type="button" className="is-primary" onClick={onPlayAgain}>다시 하기</button>
        </footer>
      </section>
    </div>
  );
}
