"use client" import { useState, useEffect } from "react" import { use } from "react" import Link from "next/link" import Navigation from "@/components/Navigation" import TeamsSection from "@/components/TeamsSection" import { DeleteTournamentButton } from "@/components/DeleteTournamentButton" import { ScheduleGenerator } from "@/components/ScheduleGenerator" import MatchEditor from "@/components/MatchEditor" interface PageProps { params: Promise<{ id: string }> } export default function TournamentDetailPage({ params }: PageProps) { const resolvedParams = use(params) const tournamentId = resolvedParams.id const [activeTab, setActiveTab] = useState("overview") const [tournament, setTournament] = useState(null) const [matches, setMatches] = useState([]) const [participants, setParticipants] = useState([]) const [rounds, setRounds] = useState([]) const [allPlayers, setAllPlayers] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState("") // Load tournament data useEffect(() => { const loadTournament = async () => { try { setLoading(true) const response = await fetch(`/api/tournaments/${tournamentId}`) if (!response.ok) { throw new Error("Failed to load tournament") } const data = await response.json() // API returns { tournament: { ... } } or direct tournament object const tournamentData = data.tournament || data setTournament(tournamentData) } catch (err) { setError("Failed to load tournament") } finally { setLoading(false) } } loadTournament() }, [tournamentId]) // Load all related data when tournament loads useEffect(() => { if (!tournament) return const loadRelatedData = async () => { try { // Load participants const pResponse = await fetch(`/api/tournaments/${tournamentId}/participants`) if (pResponse.ok) { const pData = await pResponse.json() setParticipants(pData.participants || []) } // Load matches const mResponse = await fetch(`/api/tournaments/${tournamentId}/matches`) if (mResponse.ok) { const mData = await mResponse.json() setMatches(mData.matches || []) } // Load schedule/rounds const sResponse = await fetch(`/api/tournaments/${tournamentId}/schedule`) if (sResponse.ok) { const sData = await sResponse.json() setRounds(sData.rounds || []) } // Load all players for selection const playersResponse = await fetch("/api/players") if (playersResponse.ok) { const playersData = await playersResponse.json() setAllPlayers(playersData || []) } } catch (err) { console.error("Failed to load related data:", err) } } loadRelatedData() }, [tournamentId, tournament]) if (loading) { return (

Loading...

) } if (error || !tournament) { return (

{error || "Tournament not found"}

) } const hasSchedule = rounds.length > 0 const statusColors: Record = { pending: "bg-gray-100 text-gray-700", in_progress: "bg-yellow-100 text-yellow-800", completed: "bg-green-100 text-green-800", } // Tab content renderer const renderTabContent = () => { switch (activeTab) { case "overview": return ( <> {/* Participants Section */}

Participants ({participants.length})

{participants.length > 0 ? (
{participants.map((participant) => (
{participant.player.name}
))}
) : (

No participants registered yet.

)}
{/* Recent Matches Section */}

Recent Matches ({matches.length})

{matches.length > 0 ? (
{matches.slice(0, 10).map((match) => (

{match.playedAt ? new Date(match.playedAt).toLocaleDateString() : ''}

{match.player1P1?.name} + {match.player1P2?.name} vs{" "} {match.player2P1?.name} + {match.player2P2?.name}

match.team2Score ? 'text-green-600' : match.team1Score < match.team2Score ? 'text-red-600' : 'text-gray-600' }`}> {match.team1Score} - match.team1Score ? 'text-green-600' : match.team2Score < match.team1Score ? 'text-red-600' : 'text-gray-600' }`}> {match.team2Score}
))}
) : (

No matches recorded yet.

)}
) case "participants": return (

Add Participants

{/* Player Search */}
{/* Current Participants */}

Current Participants ({participants.length})

{participants.length > 0 ? (
{participants.map((participant) => (
{participant.player.name} Elo: {participant.player.currentElo}
))}
) : (

No participants registered yet.

)}
) case "matchups": return ( ({ id: p.player.id, name: p.player.name, currentElo: p.player.currentElo, }))} teamDurability={tournament.teamDurability || "permanent"} partnerRotation={tournament.partnerRotation || "none"} allowByes={tournament.allowByes ?? true} /> ) case "schedule": return ( <> {!hasSchedule && (

No Schedule Generated

)} {rounds.map((round) => (

Round {round.roundNumber}

{round.status.replace("_", " ")}
{round.bracketMatchups?.length === 0 ? (

No matchups in this round.

) : (
{round.bracketMatchups?.map((matchup: any) => { const team1Name = matchup.player1P1 && matchup.player1P2 ? `${matchup.player1P1.name} + ${matchup.player1P2.name}` : "TBD" const team2Name = matchup.player2P1 && matchup.player2P2 ? `${matchup.player2P1.name} + ${matchup.player2P2.name}` : "TBD" return (
{matchup.tableNumber && ( Table {matchup.tableNumber} )} {matchup.status.replace("_", " ")}

{team1Name} vs {team2Name}

{matchup.match ? (
matchup.match.team2Score ? 'text-green-600' : 'text-gray-900' }`}> {matchup.match.team1Score} - matchup.match.team1Score ? 'text-green-600' : 'text-gray-900' }`}> {matchup.match.team2Score}
) : ( )}
) })}
)}
))} {hasSchedule && (

Schedule Actions

)} ) case "results": return (

Enter Match Results

) default: return null } } return (
{/* Breadcrumb */} {/* Tournament Header */}

{tournament.name}

{tournament.format} - {tournament.status}

{tournament.eventDate && (

{new Date(tournament.eventDate).toLocaleDateString()}

)}
{/* Quick Stats */}

Participants

{participants.length}

Rounds

{rounds.length}

Matchups

{matches.length}

{/* Tabs */}
{/* Content */}
{renderTabContent()}
) }