// =====================================================================
// 生態系ウォーズ — トーナメント ブラケット表示コンポーネント
// (presentational only; logic lives in tournament-app.jsx)
// =====================================================================

const TN_ROUND_META = (totalRounds) => (r) => {
  const fromEnd = totalRounds - 1 - r;
  if (fromEnd === 0) return { name: '決勝', en: 'FINAL' };
  if (fromEnd === 1) return { name: '準決勝', en: 'SEMI FINAL' };
  if (fromEnd === 2) return { name: '準々決勝', en: 'QUARTER FINAL' };
  return { name: `${r + 1}回戦`, en: `ROUND ${r + 1}` };
};

function TnChip({ part, match, teamsById, onPick, recentWin }) {
  // part: { kind:'team'|'bye'|'tbd', teamId }
  const { kind, teamId } = part;
  const team = kind === 'team' ? teamsById[teamId] : null;
  const isWin = match.winner != null && kind === 'team' && match.winner === teamId;
  const isLose = match.winner != null && kind === 'team' && match.winner !== teamId;
  const clickable = kind === 'team' && match.bothKnown && !match.hasBye;

  let cls = 'tn-chip';
  if (kind === 'tbd') cls += ' is-tbd';
  else if (kind === 'bye') cls += ' is-bye';
  else if (isWin) cls += ' is-win';
  else if (isLose) cls += ' is-lose';
  if (recentWin && recentWin.matchId === match.id && recentWin.teamId === teamId) cls += ' just-won';

  const label = kind === 'bye' ? '— 不戦勝（シード） —'
    : kind === 'tbd' ? '勝者を待っています'
    : team.name;

  return (
    <button
      className={cls}
      onClick={clickable ? () => onPick(match.id, teamId) : undefined}
      disabled={!clickable}
      type="button"
    >
      <span className="tn-chip-swatch" style={team ? { background: team.color } : undefined}></span>
      <span className="tn-chip-name">{label}</span>
      <span className="tn-chip-mark">{isWin ? '✓' : ''}</span>
    </button>
  );
}

function TnMatch({ match, teamsById, onPick, recentWin, label }) {
  const cls = 'tn-match' + (match.winner != null && !match.hasBye ? ' is-decided' : '');
  return (
    <div className={cls}>
      <div className="tn-match-no">{label}</div>
      <TnChip part={match.a} match={match} teamsById={teamsById} onPick={onPick} recentWin={recentWin} />
      <TnChip part={match.b} match={match} teamsById={teamsById} onPick={onPick} recentWin={recentWin} />
    </div>
  );
}

function TnBracket({ rounds, teamsById, onPick, recentWin, champion, colWidth, gap }) {
  const totalRounds = rounds.length;
  const meta = TN_ROUND_META(totalRounds);
  const styleVars = { '--col-w': colWidth + 'px', '--gap': gap + 'px' };

  return (
    <div className="tn-bracket-wrap">
      <div className="tn-bracket" style={styleVars}>
        {rounds.map((matches, r) => {
          const m = meta(r);
          const roundCls = 'tn-round'
            + (r < totalRounds - 1 ? ' has-next' : '')
            + (r > 0 ? ' has-prev' : '');
          return (
            <div className={roundCls} key={r}>
              <div className="tn-round-head">
                <div className="tn-round-name">{m.name}</div>
                <div className="tn-round-en">{m.en}</div>
              </div>
              <div className="tn-round-col">
                {matches.map((match, i) => (
                  <div className="tn-slot" key={match.id}>
                    <TnMatch
                      match={match}
                      teamsById={teamsById}
                      onPick={onPick}
                      recentWin={recentWin}
                      label={`${m.en} ・ M${i + 1}`}
                    />
                  </div>
                ))}
              </div>
            </div>
          );
        })}

        {/* champion column */}
        <div className="tn-champ-col">
          <div className="tn-round-head">
            <div className="tn-round-name">優勝</div>
            <div className="tn-round-en">CHAMPION</div>
          </div>
          <div className="tn-champ-box">
            <img
              className={'tn-champ-shield' + (champion ? '' : ' is-empty')}
              src="assets/shield-emblem.png" alt="シールドエンブレム" />
            <div className="tn-champ-label">◤ CHAMPION TEAM</div>
            {champion
              ? <div className="tn-champ-name" style={{ color: '#FFC21A' }}>{champion.name}</div>
              : <div className="tn-champ-name is-tbd">決勝の勝者がここに</div>}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { TnChip, TnMatch, TnBracket, TN_ROUND_META });
