import NavigationWrapper from "@/components/navigation/NavigationWrapper";
import EventsPageSection from "@/components/events/EventsPageSection";
import { eventService } from "@/services/events/event.service";
import { eventRegistrationService } from "@/services/events/event-registration.service";
import { getBackgroundImage } from "@/lib/preferences";
import { auth } from "@/lib/auth";

export const dynamic = "force-dynamic";

export default async function EventsPage() {
  // Paralléliser les appels indépendants
  const session = await auth();
  
  const [events, backgroundImage, allRegistrations] = await Promise.all([
    eventService.getAllEvents({
      orderBy: { date: "desc" },
    }),
    getBackgroundImage("events", "/got-2.jpg"),
    session?.user?.id
      ? eventRegistrationService.getUserRegistrations(session.user.id)
      : Promise.resolve([]),
  ]);

  // 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(),
  }));

  // Construire le map des inscriptions
  const initialRegistrations: Record<string, boolean> = {};
  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>
  );
}
