// 3rd-place rankings across all 12 groups, with knockout qualification markers.
const { useMemo: useMemoTP } = React;

function ThirdPlaceTeamCell({ name }) {
  const url = window.TEAMS_DATA?.flagUrl(name);
  return (
    <span className="tpt-team-cell">
      {url && <img src={url} alt={name} className="team-flag" onError={e => { e.target.style.display = 'none'; }} />}
      {name}
    </span>
  );
}

function formatCardValue(row, key) {
  if (!row.cardsAvailable) return '—';
  const value = row[key];
  if (!row.cardsComplete) return `${value}*`;
  return value;
}

function ThirdPlaceView({ standings, thirdRanks, simulateGroupStage, simulationConfig, clearPreds }) {
  const rows = thirdRanks || [];
  const allGroupsPlayed = useMemoTP(
    () => window.TEAMS_DATA.GROUP_LETTERS.every(g => standings?.[g]?.allPlayed),
    [standings]
  );
  const qualifying = new Set(rows.slice(0, 8).map(r => r.name));

  return (
    <div className="third-place-view">
      {simulateGroupStage && (
        <div className="tpv-toolbar">
          <button className="run-sim-btn" onClick={() => simulateGroupStage(simulationConfig)}>
            Sim Group Stage
          </button>
          {clearPreds && <button className="clear-btn" onClick={() => clearPreds()}>Clear</button>}
        </div>
      )}
      <div className="tpv-header">
        <div>
          <div className="tpv-kicker">Group Stage Ranking</div>
          <h2>3rd Place Teams</h2>
          <p className="tpv-copy">
            The top eight third-placed teams advance to the round of 32.
            {!allGroupsPlayed && ' This table is provisional until every group is complete.'}
          </p>
        </div>
        <div className={`tpv-status ${allGroupsPlayed ? 'is-final' : ''}`}>
          {allGroupsPlayed ? 'Final ranking' : 'Live ranking'}
        </div>
      </div>

      <div className="tpv-rules">
        <strong>Qualification order:</strong> points, goal difference, goals scored, team conduct score, then FIFA Men&apos;s World Ranking.
        <span> Group placement itself uses the 2026 head-to-head tiebreak sequence inside each group.</span>
      </div>

      <div className="tpv-table-wrap">
        <table className="tpv-table">
          <thead>
            <tr>
              <th>#</th>
              <th>Group</th>
              <th className="team">Team</th>
              <th>Pts</th>
              <th>GF</th>
              <th>GA</th>
              <th>GD</th>
              <th title="Yellow cards, where local report data is available">YC</th>
              <th title="Red cards, where local report data is available">RC</th>
              <th>Knockout</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((row, idx) => {
              const isIn = qualifying.has(row.name);
              return (
                <tr key={`${row.group}-${row.name}`} className={isIn ? 'is-qualifying' : 'is-eliminated'}>
                  <td className="rank">{idx + 1}</td>
                  <td>{row.group}</td>
                  <td className="team">
                    <ThirdPlaceTeamCell name={row.name} />
                  </td>
                  <td>{row.Pts}</td>
                  <td>{row.GF}</td>
                  <td>{row.GA}</td>
                  <td className={row.GD > 0 ? 'pos' : row.GD < 0 ? 'neg' : ''}>
                    {row.GD > 0 ? '+' : ''}{row.GD}
                  </td>
                  <td>{formatCardValue(row, 'YC')}</td>
                  <td>{formatCardValue(row, 'RC')}</td>
                  <td>
                    <span className={`tpv-badge ${isIn ? 'in' : 'out'}`}>
                      {isIn ? 'Top 8' : 'Out'}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <p className="tpv-footnote">
        * Card totals are shown when local match-report data exists for that team&apos;s completed group matches.
      </p>
    </div>
  );
}

window.ThirdPlaceView = ThirdPlaceView;
