import NavigationWrapper from "@/components/NavigationWrapper";
import EventsPageSection from "@/components/EventsPageSection";
import { prisma } from "@/lib/prisma";
import { getBackgroundImage } from "@/lib/preferences";
import { auth } from "@/lib/auth";
import { calculateEventStatus } from "@/lib/eventStatus";

export default async function EventsPage() {
  const events = await prisma.event.findMany({
    orderBy: {
      date: "desc",
    },
  });

  // Sérialiser les dates pour le client
  const serializedEvents = events.map((event) => ({
    ...event,
    date: event.date.toISOString(),
    createdAt: event.createdAt.toISOString(),
    updatedAt: event.updatedAt.toISOString(),
  }));

  const backgroundImage = await getBackgroundImage("events", "/got-2.jpg");

  // Récupérer les inscriptions côté serveur pour éviter le clignotement
  const session = await auth();
  const initialRegistrations: Record<string, boolean> = {};

  if (session?.user?.id) {
    // Récupérer toutes les inscriptions (passées et à venir) pour permettre le feedback
    const allRegistrations = await prisma.eventRegistration.findMany({
      where: {
        userId: session.user.id,
      },
      select: {
        eventId: true,
      },
    });

    allRegistrations.forEach((reg) => {
      initialRegistrations[reg.eventId] = true;
    });
  }

  return (
    <main className="min-h-screen bg-black relative">
      <NavigationWrapper />
      <EventsPageSection
        events={serializedEvents}
        backgroundImage={backgroundImage}
        initialRegistrations={initialRegistrations}
      />
    </main>
  );
}
