import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { LeaderboardView } from "./leaderboard-view";
import { AgoraLogo } from "@/components/agora-logo";

export default async function LeaderboardPage() {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    redirect("/login");
  }

  const { data: profiles, error } = await supabase
    .from("profiles")
    .select("id, pseudo, avatar_url, points, previous_rank, role")
    .order("points", { ascending: false });

  const isJudge = profiles?.find((p) => p.id === user.id)?.role === "judge";

  return (
    <div className="mx-auto w-full max-w-2xl px-4 py-8">
      <div className="mb-6 flex flex-col items-center text-center">
        <AgoraLogo className="h-32 w-32 sm:h-40 sm:w-40" />
        <p className="mt-2 font-serif text-sm text-marble/60 italic">Le classement des Citoyens</p>
      </div>

      {error && (
        <p role="alert" className="text-sm text-oxblood">
          Impossible de charger le classement pour le moment.
        </p>
      )}

      {!error && <LeaderboardView initialProfiles={profiles ?? []} isJudge={isJudge} />}
    </div>
  );
}
