'use client';

import React, { useState, useMemo } from 'react';
import { SponsorLeaguesTemplate, type SortOption, type TierFilter, type AvailabilityFilter } from '@/templates/SponsorLeaguesTemplate';
import { ClientWrapperProps } from '@/lib/contracts/components/ComponentContracts';
import { ViewData } from '@/lib/contracts/view-data/ViewData';

export function SponsorLeaguesPageClient({ viewData }: ClientWrapperProps<ViewData>) {
  const [searchQuery, setSearchQuery] = useState('');
  const [tierFilter] = useState<TierFilter>('all');
  const [availabilityFilter] = useState<AvailabilityFilter>('all');
  const [sortBy] = useState<SortOption>('rating');

  const filteredLeagues = useMemo(() => {
    const d = viewData as any;
    if (!d?.leagues) return [];
    return d.leagues
      .filter((league: any) => {
        if (searchQuery && !league.name.toLowerCase().includes(searchQuery.toLowerCase())) {
          return false;
        }
        if (tierFilter !== 'all' && league.tier !== tierFilter) {
          return false;
        }
        if (availabilityFilter === 'main' && !league.mainSponsorSlot.available) {
          return false;
        }
        if (availabilityFilter === 'secondary' && league.secondarySlots.available === 0) {
          return false;
        }
        return true;
      })
      .sort((a: any, b: any) => {
        switch (sortBy) {
          case 'rating': return b.rating - a.rating;
          case 'drivers': return b.drivers - a.drivers;
          case 'price': return a.mainSponsorSlot.price - b.mainSponsorSlot.price;
          case 'views': return b.avgViewsPerRace - a.avgViewsPerRace;
          default: return 0;
        }
      });
  }, [viewData, searchQuery, tierFilter, availabilityFilter, sortBy]);

  return (
    <SponsorLeaguesTemplate
      viewData={viewData as any}
      filteredLeagues={filteredLeagues}
      searchQuery={searchQuery}
      setSearchQuery={setSearchQuery}
    />
  );
}
