import flagLookup from "../../../../domain/flagLookup";
import styles from "./ScoreBoard.module.css";

// since everyone wants to use giant names...
const nameLineWidthGuess = 25;

export const PlayerScoreTile = ({ name, guesses, totalScore, winner }) => (
  <div className={styles.tile}>
    <div className={styles.header}>
      <span
        className={`${styles.name} ${
          name.length > nameLineWidthGuess ? styles.longname : ""
        }`}
      >
        {name}
      </span>
      <span className={styles.total}>
        {winner && "🏆"} {totalScore}
      </span>
    </div>
    <div className={styles.scores}>
      {Object.entries(guesses)
        .map(([k, v]) => [parseInt(k, 10), v])
        // eslint-disable-next-line no-nested-ternary
        .sort(([k1], [k2]) => (k1 < k2 ? -1 : k1 > k2 ? 1 : 0))
        .map(([num, { score, country }]) =>
          score !== undefined ? (
            <div className={styles.round} key={num}>
              <span className={styles.score}>
                Round {num}: {score ?? 0}
              </span>
              <span className={styles.flag}>{flagLookup(country)}</span>
            </div>
          ) : null
        )}
    </div>
  </div>
);

const ScoreBoard = ({ players }) => (
  <div className={styles.scoreboard}>
    {players
      .filter(({ currentRound }) => currentRound === null)
      .sort(({ totalScore: p1 }, { totalScore: p2 }) =>
        // eslint-disable-next-line no-nested-ternary
        p1 > p2 ? -1 : p1 < p2 ? 1 : 0
      )
      .map(({ name, guesses, totalScore, winner }, i) => (
        <PlayerScoreTile
          key={name}
          // TODO gracefully handle ties...
          winner={i === 0}
          {...{ name, guesses, totalScore, winner }}
        />
      ))}
  </div>
);

export default ScoreBoard;
