"use client";

import { GroupTable, Match, Team } from "@/lib/types";

function teamById(teams: Team[], id: string) {
  return teams.find((t) => t.id === id);
}

function liveMatchFor(group: string, matches: Match[]) {
  return matches.find(
    (m) => m.group === group && (m.status === "LIVE" || m.status === "IN_PLAY" || m.status === "PAUSED"),
  );
}

export default function Groups({
  tables, teams, matches,
}: { tables: GroupTable[]; teams: Team[]; matches: Match[] }) {
  return (
    <div className="group-grid">
      {tables.map((t) => {
        const live = liveMatchFor(t.group, matches);
        return (
          <div className="group-card" key={t.group}>
            <div className="group-head">
              <span className="group-name">Gruppe {t.group}</span>
              <span className="group-tag">
                {live ? "● LIVE" : `${t.rows.reduce((a, r) => a + r.played, 0)} Spiele`}
              </span>
            </div>
            <table className="standings">
              <thead>
                <tr>
                  <th className="team">Team</th>
                  <th>Sp</th><th>S</th><th>U</th><th>N</th>
                  <th>Tore</th><th>±</th><th>Pkt</th>
                </tr>
              </thead>
              <tbody>
                {t.rows.map((r) => {
                  const team = teamById(teams, r.teamId);
                  const cls = r.rank <= 2 ? `q${r.rank}` : r.rank === 3 ? "q3" : "";
                  return (
                    <tr key={r.teamId}>
                      <td className="team">
                        <span className={`rankdot ${cls}`}>{r.rank}</span>
                        <span className="team-name">{team?.name ?? r.teamId}</span>
                        {team?.code && <span className="team-code">{team.code}</span>}
                      </td>
                      <td>{r.played}</td>
                      <td>{r.won}</td>
                      <td>{r.drawn}</td>
                      <td>{r.lost}</td>
                      <td>{r.goalsFor}:{r.goalsAgainst}</td>
                      <td>{r.goalDiff > 0 ? `+${r.goalDiff}` : r.goalDiff}</td>
                      <td className="pts">{r.points}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        );
      })}
    </div>
  );
}
