import { RacesTemplate } from '@/templates/RacesTemplate';
import { RacesApiClient } from '@/lib/api/races/RacesApiClient';
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';

export default async function Page() {
  // Manual wiring: create dependencies
  const baseUrl = getWebsiteApiBaseUrl();
  const logger = new ConsoleLogger();
  const errorReporter = new EnhancedErrorReporter(logger, {
    showUserNotifications: true,
    logToConsole: true,
    reportToExternal: process.env.NODE_ENV === 'production',
  });

  // Create API client
  const racesApiClient = new RacesApiClient(baseUrl, errorReporter, logger);

  // Fetch data
  const data = await racesApiClient.getPageData();
  
  // Transform races
  const transformRace = (race: any) => ({
    id: race.id,
    track: race.track,
    car: race.car,
    scheduledAt: race.scheduledAt,
    status: race.status as 'scheduled' | 'running' | 'completed' | 'cancelled',
    sessionType: 'race',
    leagueId: race.leagueId,
    leagueName: race.leagueName,
    strengthOfField: race.strengthOfField ?? undefined,
    isUpcoming: race.status === 'scheduled',
    isLive: race.status === 'running',
    isPast: race.status === 'completed',
  });

  const races = data.races.map(transformRace);
  const scheduledRaces = races.filter(r => r.isUpcoming);
  const runningRaces = races.filter(r => r.isLive);
  const completedRaces = races.filter(r => r.isPast);
  const totalCount = races.length;
  
  return <RacesTemplate
    races={races}
    totalCount={totalCount}
    scheduledRaces={scheduledRaces}
    runningRaces={runningRaces}
    completedRaces={completedRaces}
    isLoading={false}
    statusFilter="all"
    setStatusFilter={() => {}}
    leagueFilter="all"
    setLeagueFilter={() => {}}
    timeFilter="upcoming"
    setTimeFilter={() => {}}
    onRaceClick={() => {}}
    onLeagueClick={() => {}}
    onRegister={() => {}}
    onWithdraw={() => {}}
    onCancel={() => {}}
    showFilterModal={false}
    setShowFilterModal={() => {}}
    currentDriverId={undefined}
    userMemberships={[]}
  />;
}