import { PageWrapper } from '@/components/shared/state/PageWrapper';
import { SponsorLeaguesTemplate } from '@/templates/SponsorLeaguesTemplate';
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 { AvailableLeaguesViewModel } from '@/lib/view-models/AvailableLeaguesViewModel';

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 apiClient = new SponsorsApiClient(baseUrl, errorReporter, logger);

  // Fetch data
  const leaguesData = await apiClient.getAvailableLeagues();
  
  // Process data with view model to calculate stats
  if (!leaguesData) {
    return <PageWrapper data={undefined} Template={SponsorLeaguesTemplate} />;
  }
  
  const viewModel = new AvailableLeaguesViewModel(leaguesData);
  
  // Calculate summary stats
  const stats = {
    total: viewModel.leagues.length,
    mainAvailable: viewModel.leagues.filter(l => l.mainSponsorSlot.available).length,
    secondaryAvailable: viewModel.leagues.reduce((sum, l) => sum + l.secondarySlots.available, 0),
    totalDrivers: viewModel.leagues.reduce((sum, l) => sum + l.drivers, 0),
    avgCpm: Math.round(
      viewModel.leagues.reduce((sum, l) => sum + l.cpm, 0) / viewModel.leagues.length
    ),
  };

  const processedData = {
    leagues: viewModel.leagues,
    stats,
  };
  
  return <PageWrapper data={processedData} Template={SponsorLeaguesTemplate} />;
}