import { createFileRoute } from "@tanstack/react-router";
import { tournamentQueries, useCurrentTournament } from "@/features/tournaments/queries";
import UpcomingTournament from "@/features/tournaments/components/upcoming-tournament";
import { ensureServerQueryData } from "@/lib/tanstack-query/utils/ensure";
import StartedTournament from "@/features/tournaments/components/started-tournament";
import { Suspense } from "react";
import UpcomingTournamentSkeleton from "@/features/tournaments/components/upcoming-tournament/skeleton";

export const Route = createFileRoute("/_authed/")({
  component: () => <Suspense fallback={<UpcomingTournamentSkeleton />}>
    <Home />
  </Suspense>,
  beforeLoad: async ({ context }) => {
    const queryClient = context.queryClient;
    const tournament = await ensureServerQueryData(queryClient, tournamentQueries.current())

    return { tournament }
  },
  loader: ({ context }) => ({
    withPadding: false,
    header: {
      title: context.tournament.name || "FLXN"
    }
  }),
  pendingComponent: () => <UpcomingTournamentSkeleton />
});

function Home() {
  const { data: tournament } = useCurrentTournament();
  if (!tournament.matches || tournament.matches.length === 0) {
    return <UpcomingTournament tournament={tournament} />;
  }

  return <StartedTournament tournament={tournament} />
}
