import { PageWrapper } from '@/components/shared/state/PageWrapper';
import { SponsorLeaguesPageClient } from '@/client-wrapper/SponsorLeaguesPageClient';
import { SponsorsApiClient } from '@/lib/api/sponsors/SponsorsApiClient';
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { getWebsiteServerEnv } from '@/lib/config/env';

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

  // Create API client
  const apiClient = new SponsorsApiClient(baseUrl, errorReporter, logger);

  // Fetch data
  const leaguesData = await apiClient.getAvailableLeagues();
  
  // Process data - move business logic to template
  if (!leaguesData) {
    return <PageWrapper data={undefined} Template={SponsorLeaguesPageClient} />;
  }
  
  // Calculate summary stats (business logic moved from view model)
  const stats = {
    total: leaguesData.length,
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    mainAvailable: leaguesData.filter((l: any) => l.mainSponsorSlot.available).length,
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    secondaryAvailable: leaguesData.reduce((sum: number, l: any) => sum + l.secondarySlots.available, 0),
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    totalDrivers: leaguesData.reduce((sum: number, l: any) => sum + l.drivers, 0),
    avgCpm: Math.round(
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      leaguesData.reduce((sum: number, l: any) => sum + l.cpm, 0) / leaguesData.length
    ),
  };

  const processedData = {
    leagues: leaguesData,
    stats,
  };
  
  return <PageWrapper data={processedData} Template={SponsorLeaguesPageClient} />;
}