import Link from "next/link";
import { notFound } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { CompetitionSidebar } from "@/components/layout/Sidebar";
import { YaltopiaFooter } from "@/components/layout/YaltopiaFooter";

export default async function CompetitionLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ leagueId: string; competitionId: string }>;
}) {
  const { leagueId, competitionId } = await params;
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  const { data: competition } = await supabase
    .from("competitions")
    .select("*, leagues(name)")
    .eq("id", competitionId)
    .single();

  if (!competition) notFound();

  let showMyTeam = false;
  if (user) {
    const { data: compTeams } = await supabase
      .from("teams")
      .select("id")
      .eq("competition_id", competitionId);
    const ids = compTeams?.map((t) => t.id) ?? [];
    if (ids.length > 0) {
      const { count } = await supabase
        .from("team_members")
        .select("id", { count: "exact", head: true })
        .eq("user_id", user.id)
        .eq("role", "manager")
        .in("team_id", ids);
      showMyTeam = (count ?? 0) > 0;
    }
  }

  return (
    <div className="flex min-h-screen flex-col">
      <div className="flex flex-1">
        <aside className="flex w-56 flex-col border-r border-white/10 bg-black/20">
          <div className="border-b border-white/10 p-4">
            <Link
              href={`/leagues/${leagueId}`}
              className="text-xs text-cyan-400 hover:underline"
            >
              ← {(competition.leagues as { name: string })?.name}
            </Link>
            <h2 className="mt-1 font-semibold">{competition.name}</h2>
            <p className="text-xs capitalize text-[var(--color-muted)]">
              {competition.tournament_mode} · {competition.status}
            </p>
          </div>
          <CompetitionSidebar
            leagueId={leagueId}
            competitionId={competitionId}
            showMyTeam={showMyTeam}
          />
        </aside>
        <div className="flex flex-1 flex-col">
          <main className="flex-1 p-6">{children}</main>
          <YaltopiaFooter />
        </div>
      </div>
    </div>
  );
}
