"use client";

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

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"),
  );
}

function liveTeamIdsFor(group: GroupId, matches: Match[]): Set<string> {
  const ids = new Set<string>();
  for (const m of matches) {
    if (m.group !== group) continue;
    if (m.status === "LIVE" || m.status === "IN_PLAY" || m.status === "PAUSED") {
      if (m.homeTeamId) ids.add(m.homeTeamId);
      if (m.awayTeamId) ids.add(m.awayTeamId);
    }
  }
  return ids;
}

export default function Groups({
  tables, teams, matches, onOpenGroup,
}: {
  tables: GroupTable[]; teams: Team[]; matches: Match[];
  onOpenGroup: (g: GroupId) => void;
}) {
  return (
    <div className="group-grid">
      {tables.map((t) => {
        const live = liveMatchFor(t.group, matches);
        const liveIds = liveTeamIdsFor(t.group, matches);
        const groupMatches = matches.filter((m) => m.group === t.group);
        const groupComplete = groupMatches.length > 0 && groupMatches.every((m) => m.status === "FINISHED");
        return (
          <div className="group-card" key={t.group}>
            <button
              className="group-head group-head-btn"
              onClick={() => onOpenGroup(t.group)}
              title={`Spiele der Gruppe ${t.group} ansehen`}
            >
              <span className={`group-name${groupComplete ? " group-complete" : ""}`}>Gruppe {t.group}</span>
              <span className="group-tag">
                {live ? "● LIVE" : "Spiele ansehen →"}
              </span>
            </button>
            <table className="standings">
              <thead>
                <tr>
                  <th className="team">Mannschaft</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" : "";
                  const isLive = liveIds.has(r.teamId);
                  return (
                    <tr key={r.teamId} className={isLive ? "row-live" : ""}>
                      <td className="team">
                        <span className={`rankdot ${cls}`}>{r.rank}</span>
                        <Flag team={team} size={20} />
                        <span className="team-name">{team?.localisedName ?? team?.name ?? r.teamId}</span>
                        {isLive && <span className="row-live-dot" title="läuft gerade" />}
                      </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>
  );
}
