import { PageWrapper } from '@/components/shared/state/PageWrapper';
import { SponsorLeaguesTemplate } from '@/templates/SponsorLeaguesTemplate';
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
import { SPONSOR_SERVICE_TOKEN } from '@/lib/di/tokens';
import { SponsorService } from '@/lib/services/sponsors/SponsorService';
import { AvailableLeaguesViewModel } from '@/lib/view-models/AvailableLeaguesViewModel';

export default async function Page() {
  const leaguesData = await PageDataFetcher.fetch<SponsorService, 'getAvailableLeagues'>(
    SPONSOR_SERVICE_TOKEN,
    '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} />;
}