import { useState, useEffect } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ParkCard } from '@/components/parks/ParkCard';
import { RideCard } from '@/components/rides/RideCard';
import { RecentChangeCard } from './RecentChangeCard';
import { Badge } from '@/components/ui/badge';
import { Park, Ride } from '@/types/database';
import { supabase } from '@/integrations/supabase/client';
import { getErrorMessage } from '@/lib/errorHandler';
import { logger } from '@/lib/logger';
import { Clock } from 'lucide-react';

interface RecentChange {
  entityType: 'park' | 'ride' | 'company';
  entityId: string;
  entityName: string;
  entitySlug: string;
  parkSlug?: string;
  imageUrl: string | null;
  changeType: string;
  changedAt: string;
  changedByUsername?: string | null;
  changedByAvatar?: string | null;
  changeReason: string | null;
}

export function ContentTabs() {
  const [trendingParks, setTrendingParks] = useState<Park[]>([]);
  const [trendingRides, setTrendingRides] = useState<Ride[]>([]);
  const [recentParks, setRecentParks] = useState<Park[]>([]);
  const [recentRides, setRecentRides] = useState<Ride[]>([]);
  const [recentChanges, setRecentChanges] = useState<RecentChange[]>([]);
  const [recentlyOpened, setRecentlyOpened] = useState<Array<(Park | Ride) & { entityType: 'park' | 'ride' }>>([]);
  const [highestRatedParks, setHighestRatedParks] = useState<Park[]>([]);
  const [highestRatedRides, setHighestRatedRides] = useState<Ride[]>([]);
  const [openingSoon, setOpeningSoon] = useState<Array<(Park | Ride) & { entityType: 'park' | 'ride' }>>([]);
  const [closingSoon, setClosingSoon] = useState<Array<(Park | Ride) & { entityType: 'park' | 'ride' }>>([]);
  const [recentlyClosed, setRecentlyClosed] = useState<Array<(Park | Ride) & { entityType: 'park' | 'ride' }>>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchContent();
  }, []);

  const fetchContent = async () => {
    try {
      // Trending Parks (by 30-day view count)
      const { data: trending } = await supabase
        .from('parks')
        .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
        .order('view_count_30d', { ascending: false })
        .limit(12);

      // Recently Added Parks
      const { data: recent } = await supabase
        .from('parks')
        .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
        .order('created_at', { ascending: false })
        .limit(12);

      // Trending Rides (by 30-day view count)
      const { data: trendingRidesData } = await supabase
        .from('rides')
        .select(`*, park:parks!inner(name, slug, location:locations(*))`)
        .order('view_count_30d', { ascending: false })
        .limit(12);

      // Recently Added Rides
      const { data: recentRidesData } = await supabase
        .from('rides')
        .select(`*, park:parks!inner(name, slug, location:locations(*))`)
        .order('created_at', { ascending: false })
        .limit(12);

      // Fetch recent park versions
      const { data: parkVersions } = await supabase
        .from('park_versions')
        .select(`
          version_id,
          park_id,
          name,
          slug,
          change_type,
          created_at,
          created_by,
          change_reason,
          card_image_url,
          profiles:profiles!park_versions_created_by_fkey(username, avatar_url)
        `)
        .eq('is_current', true)
        .order('created_at', { ascending: false })
        .limit(12);

      // Fetch recent ride versions with park slug for proper routing
      const { data: rideVersions } = await supabase
        .from('ride_versions')
        .select(`
          version_id,
          ride_id,
          name,
          slug,
          change_type,
          created_at,
          created_by,
          change_reason,
          card_image_url,
          park_id,
          profiles:profiles!ride_versions_created_by_fkey(username, avatar_url)
        `)
        .eq('is_current', true)
        .order('created_at', { ascending: false })
        .limit(12);

      // Fetch park slugs for rides that have a park_id
      const rideParksMap = new Map<string, string>();
      if (rideVersions) {
        const parkIds = [...new Set(rideVersions.map(v => v.park_id).filter(Boolean))];
        if (parkIds.length > 0) {
          const { data: parks } = await supabase
            .from('parks')
            .select('id, slug')
            .in('id', parkIds);
          
          parks?.forEach(park => {
            rideParksMap.set(park.id, park.slug);
          });
        }
      }

      // Fetch recent company versions
      const { data: companyVersions } = await supabase
        .from('company_versions')
        .select(`
          version_id,
          company_id,
          name,
          slug,
          change_type,
          created_at,
          created_by,
          change_reason,
          card_image_url,
          profiles:profiles!company_versions_created_by_fkey(username, avatar_url)
        `)
        .eq('is_current', true)
        .order('created_at', { ascending: false })
        .limit(12);

      // Combine all changes into a unified structure
      const allChanges: RecentChange[] = [
        ...(parkVersions || []).map(v => ({
          entityType: 'park' as const,
          entityId: v.park_id,
          entityName: v.name,
          entitySlug: v.slug,
          imageUrl: v.card_image_url,
          changeType: v.change_type,
          changedAt: v.created_at,
          changedByUsername: v.profiles?.username,
          changedByAvatar: v.profiles?.avatar_url,
          changeReason: v.change_reason,
        })),
        ...(rideVersions || []).map(v => ({
          entityType: 'ride' as const,
          entityId: v.ride_id,
          entityName: v.name,
          entitySlug: v.slug,
          parkSlug: v.park_id ? rideParksMap.get(v.park_id) : undefined,
          imageUrl: v.card_image_url,
          changeType: v.change_type,
          changedAt: v.created_at,
          changedByUsername: v.profiles?.username,
          changedByAvatar: v.profiles?.avatar_url,
          changeReason: v.change_reason,
        })),
        ...(companyVersions || []).map(v => ({
          entityType: 'company' as const,
          entityId: v.company_id,
          entityName: v.name,
          entitySlug: v.slug,
          imageUrl: v.card_image_url,
          changeType: v.change_type,
          changedAt: v.created_at,
          changedByUsername: v.profiles?.username,
          changedByAvatar: v.profiles?.avatar_url,
          changeReason: v.change_reason,
        }))
      ]
        .sort((a, b) => new Date(b.changedAt).getTime() - new Date(a.changedAt).getTime())
        .slice(0, 24);

      // Fetch recently opened parks and rides
      const oneYearAgo = new Date();
      oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
      const dateThreshold = oneYearAgo.toISOString().split('T')[0];

      const { data: openedParks } = await supabase
        .from('parks')
        .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
        .not('opening_date', 'is', null)
        .gte('opening_date', dateThreshold)
        .order('opening_date', { ascending: false })
        .limit(20);

      const { data: openedRides } = await supabase
        .from('rides')
        .select(`*, park:parks!inner(name, slug, location:locations(*))`)
        .not('opening_date', 'is', null)
        .gte('opening_date', dateThreshold)
        .order('opening_date', { ascending: false })
        .limit(20);

      // Combine and sort by opening date
      const combinedOpened = [
        ...(openedParks || []).map(p => ({ ...p, entityType: 'park' as const })),
        ...(openedRides || []).map(r => ({ ...r, entityType: 'ride' as const }))
      ]
        .sort((a, b) => new Date(b.opening_date).getTime() - new Date(a.opening_date).getTime())
        .slice(0, 24);

      // Highest Rated Parks
      const { data: topRatedParks } = await supabase
        .from('parks')
        .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
        .gt('review_count', 0)
        .order('average_rating', { ascending: false })
        .order('review_count', { ascending: false })
        .limit(12);

      // Highest Rated Rides
      const { data: topRatedRides } = await supabase
        .from('rides')
        .select(`*, park:parks!inner(name, slug, location:locations(*))`)
        .gt('review_count', 0)
        .order('average_rating', { ascending: false })
        .order('review_count', { ascending: false })
        .limit(12);

      // Opening Soon (next 6 months)
      const sixMonthsFromNow = new Date();
      sixMonthsFromNow.setMonth(sixMonthsFromNow.getMonth() + 6);
      const futureThreshold = sixMonthsFromNow.toISOString().split('T')[0];

      const { data: parksSoon } = await supabase
        .from('parks')
        .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
        .not('opening_date', 'is', null)
        .gt('opening_date', new Date().toISOString().split('T')[0])
        .lte('opening_date', futureThreshold)
        .in('status', ['under_construction', 'planned'])
        .order('opening_date', { ascending: true })
        .limit(20);

      const { data: ridesSoon } = await supabase
        .from('rides')
        .select(`*, park:parks!inner(name, slug, location:locations(*))`)
        .not('opening_date', 'is', null)
        .gt('opening_date', new Date().toISOString().split('T')[0])
        .lte('opening_date', futureThreshold)
        .in('status', ['under_construction', 'planned'])
        .order('opening_date', { ascending: true })
        .limit(20);

      const combinedOpening = [
        ...(parksSoon || []).map(p => ({ ...p, entityType: 'park' as const })),
        ...(ridesSoon || []).map(r => ({ ...r, entityType: 'ride' as const }))
      ]
        .sort((a, b) => new Date(a.opening_date).getTime() - new Date(b.opening_date).getTime())
        .slice(0, 24);

      // Closing Soon (next 6 months)
      const { data: parksClosing } = await supabase
        .from('parks')
        .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
        .not('closing_date', 'is', null)
        .gt('closing_date', new Date().toISOString().split('T')[0])
        .lte('closing_date', futureThreshold)
        .eq('status', 'operating')
        .order('closing_date', { ascending: true })
        .limit(20);

      const { data: ridesClosing } = await supabase
        .from('rides')
        .select(`*, park:parks!inner(name, slug, location:locations(*))`)
        .not('closing_date', 'is', null)
        .gt('closing_date', new Date().toISOString().split('T')[0])
        .lte('closing_date', futureThreshold)
        .eq('status', 'operating')
        .order('closing_date', { ascending: true })
        .limit(20);

      const combinedClosing = [
        ...(parksClosing || []).map(p => ({ ...p, entityType: 'park' as const })),
        ...(ridesClosing || []).map(r => ({ ...r, entityType: 'ride' as const }))
      ]
        .sort((a, b) => new Date(a.closing_date).getTime() - new Date(b.closing_date).getTime())
        .slice(0, 24);

      // Recently Closed (closed in last year)
      const { data: parksClosed } = await supabase
        .from('parks')
        .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
        .not('closing_date', 'is', null)
        .lt('closing_date', new Date().toISOString().split('T')[0])
        .gte('closing_date', dateThreshold)
        .in('status', ['closed', 'permanently_closed'])
        .order('closing_date', { ascending: false })
        .limit(20);

      const { data: ridesClosed } = await supabase
        .from('rides')
        .select(`*, park:parks!inner(name, slug, location:locations(*))`)
        .not('closing_date', 'is', null)
        .lt('closing_date', new Date().toISOString().split('T')[0])
        .gte('closing_date', dateThreshold)
        .in('status', ['closed', 'removed', 'permanently_closed'])
        .order('closing_date', { ascending: false })
        .limit(20);

      const combinedClosed = [
        ...(parksClosed || []).map(p => ({ ...p, entityType: 'park' as const })),
        ...(ridesClosed || []).map(r => ({ ...r, entityType: 'ride' as const }))
      ]
        .sort((a, b) => new Date(b.closing_date).getTime() - new Date(a.closing_date).getTime())
        .slice(0, 24);

      setTrendingParks(trending || []);
      setRecentParks(recent || []);
      setTrendingRides(trendingRidesData || []);
      setRecentRides(recentRidesData || []);
      setRecentChanges(allChanges);
      setRecentlyOpened(combinedOpened);
      setHighestRatedParks(topRatedParks || []);
      setHighestRatedRides(topRatedRides || []);
      setOpeningSoon(combinedOpening);
      setClosingSoon(combinedClosing);
      setRecentlyClosed(combinedClosed);
    } catch (error: unknown) {
      logger.error('Failed to fetch content', { error: getErrorMessage(error) });
    } finally {
      setLoading(false);
    }
  };


  if (loading) {
    return (
      <section className="py-12">
        <div className="container mx-auto px-4">
          <div className="space-y-8">
            <div className="text-center space-y-3">
              <div className="h-8 bg-gradient-to-r from-primary/20 via-secondary/20 to-accent/20 rounded-lg w-64 mx-auto animate-pulse" />
              <div className="h-4 bg-muted/50 rounded w-96 mx-auto animate-pulse" style={{ animationDelay: '150ms' }} />
              <div className="mt-4 mx-auto w-24 h-1 bg-gradient-to-r from-transparent via-primary/30 to-transparent rounded-full animate-pulse" style={{ animationDelay: '300ms' }} />
            </div>
            
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4">
              {[...Array(12)].map((_, i) => (
                <div 
                  key={i} 
                  className="h-72 bg-gradient-to-br from-card via-card to-card/80 rounded-lg border border-border/50 animate-pulse relative overflow-hidden"
                  style={{ animationDelay: `${i * 50}ms` }}
                >
                  <div className="absolute inset-0 bg-gradient-to-r from-transparent via-primary/10 to-transparent animate-shimmer" />
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="py-8">
      <div className="container mx-auto px-4">
        <Tabs defaultValue="trending-parks" className="w-full">
          <div className="text-center mb-8">
            <TabsList className="flex flex-wrap justify-center gap-2 p-3 bg-muted/30 rounded-lg max-w-5xl mx-auto">
              <TabsTrigger value="trending-parks" className="px-4 py-2.5 text-sm font-medium rounded-full data-[state=active]:bg-primary data-[state=active]:text-primary-foreground hover:bg-muted/50 transition-colors text-center md:w-[calc(25%-0.375rem)]">
                Trending Parks
              </TabsTrigger>
              <TabsTrigger value="trending-rides" className="px-4 py-2.5 text-sm font-medium rounded-full data-[state=active]:bg-primary data-[state=active]:text-primary-foreground hover:bg-muted/50 transition-colors text-center md:w-[calc(25%-0.375rem)]">
                Trending Rides
              </TabsTrigger>
              <TabsTrigger value="recent-parks" className="px-4 py-2.5 text-sm font-medium rounded-full data-[state=active]:bg-primary data-[state=active]:text-primary-foreground hover:bg-muted/50 transition-colors text-center md:w-[calc(25%-0.375rem)]">
                New Parks
              </TabsTrigger>
              <TabsTrigger value="recent-rides" className="px-4 py-2.5 text-sm font-medium rounded-full data-[state=active]:bg-primary data-[state=active]:text-primary-foreground hover:bg-muted/50 transition-colors text-center md:w-[calc(25%-0.375rem)]">
                New Rides
              </TabsTrigger>
              <TabsTrigger value="recent-changes" className="px-4 py-2.5 text-sm font-medium rounded-full data-[state=active]:bg-primary data-[state=active]:text-primary-foreground hover:bg-muted/50 transition-colors text-center md:w-[calc(25%-0.375rem)]">
                Recent Changes
              </TabsTrigger>
              <TabsTrigger value="highest-rated-parks" className="px-4 py-2.5 text-sm font-medium rounded-full data-[state=active]:bg-primary data-[state=active]:text-primary-foreground hover:bg-muted/50 transition-colors text-center md:w-[calc(25%-0.375rem)]">
                Top Parks
              </TabsTrigger>
              <TabsTrigger value="highest-rated-rides" className="px-4 py-2.5 text-sm font-medium rounded-full data-[state=active]:bg-primary data-[state=active]:text-primary-foreground hover:bg-muted/50 transition-colors text-center md:w-[calc(25%-0.375rem)]">
                Top Rides
              </TabsTrigger>
              <TabsTrigger value="opening-soon" className="px-4 py-2.5 text-sm font-medium rounded-full data-[state=active]:bg-primary data-[state=active]:text-primary-foreground hover:bg-muted/50 transition-colors text-center md:w-[calc(25%-0.375rem)]">
                Opening Soon
              </TabsTrigger>
              <TabsTrigger value="recently-opened" className="px-4 py-2.5 text-sm font-medium rounded-full data-[state=active]:bg-primary data-[state=active]:text-primary-foreground hover:bg-muted/50 transition-colors text-center md:w-[calc(25%-0.375rem)]">
                Recently Opened
              </TabsTrigger>
              <TabsTrigger value="closing-soon" className="px-4 py-2.5 text-sm font-medium rounded-full data-[state=active]:bg-primary data-[state=active]:text-primary-foreground hover:bg-muted/50 transition-colors text-center md:w-[calc(25%-0.375rem)]">
                Closing Soon
              </TabsTrigger>
              <TabsTrigger value="recently-closed" className="px-4 py-2.5 text-sm font-medium rounded-full data-[state=active]:bg-primary data-[state=active]:text-primary-foreground hover:bg-muted/50 transition-colors text-center md:w-[calc(25%-0.375rem)]">
                Recently Closed
              </TabsTrigger>
            </TabsList>
          </div>

      <TabsContent value="trending-parks" className="mt-8">
        <div className="text-center mb-6">
          <h2 className="text-2xl md:text-3xl font-bold mb-2 bg-gradient-to-r from-primary via-secondary to-accent bg-clip-text text-transparent drop-shadow-[0_0_12px_rgba(139,92,246,0.3)]">Trending Parks</h2>
          <p className="text-muted-foreground text-sm md:text-base animate-fade-in">Most viewed parks in the last 30 days</p>
          <div className="mt-4 mx-auto w-24 h-1 bg-gradient-to-r from-transparent via-primary to-transparent rounded-full opacity-60"></div>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
          {trendingParks.map((park) => (
            <ParkCard key={park.id} park={park} />
          ))}
        </div>
      </TabsContent>

      <TabsContent value="trending-rides" className="mt-8">
        <div className="text-center mb-6">
          <h2 className="text-2xl md:text-3xl font-bold mb-2 bg-gradient-to-r from-primary via-secondary to-accent bg-clip-text text-transparent drop-shadow-[0_0_12px_rgba(139,92,246,0.3)]">Trending Rides</h2>
          <p className="text-muted-foreground text-sm md:text-base animate-fade-in">Most viewed rides in the last 30 days</p>
          <div className="mt-4 mx-auto w-24 h-1 bg-gradient-to-r from-transparent via-primary to-transparent rounded-full opacity-60"></div>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
          {trendingRides.map((ride) => (
            <RideCard key={ride.id} ride={ride} />
          ))}
        </div>
      </TabsContent>

      <TabsContent value="recent-parks" className="mt-8">
        <div className="text-center mb-6">
          <h2 className="text-2xl md:text-3xl font-bold mb-2 bg-gradient-to-r from-primary via-secondary to-accent bg-clip-text text-transparent drop-shadow-[0_0_12px_rgba(139,92,246,0.3)]">Recently Added Parks</h2>
          <p className="text-muted-foreground text-sm md:text-base animate-fade-in">Latest parks added to our database</p>
          <div className="mt-4 mx-auto w-24 h-1 bg-gradient-to-r from-transparent via-primary to-transparent rounded-full opacity-60"></div>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
          {recentParks.map((park) => (
            <ParkCard key={park.id} park={park} />
          ))}
        </div>
      </TabsContent>

      <TabsContent value="recent-rides" className="mt-8">
        <div className="text-center mb-6">
          <h2 className="text-2xl md:text-3xl font-bold mb-2 bg-gradient-to-r from-primary via-secondary to-accent bg-clip-text text-transparent drop-shadow-[0_0_12px_rgba(139,92,246,0.3)]">Recently Added Rides</h2>
          <p className="text-muted-foreground text-sm md:text-base animate-fade-in">Latest attractions added to our database</p>
          <div className="mt-4 mx-auto w-24 h-1 bg-gradient-to-r from-transparent via-primary to-transparent rounded-full opacity-60"></div>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
          {recentRides.map((ride) => (
            <RideCard key={ride.id} ride={ride} />
          ))}
        </div>
      </TabsContent>

      <TabsContent value="recent-changes" className="mt-8">
        <div className="text-center mb-6">
          <h2 className="text-2xl md:text-3xl font-bold mb-2 bg-gradient-to-r from-primary via-secondary to-accent bg-clip-text text-transparent drop-shadow-[0_0_12px_rgba(139,92,246,0.3)]">Recent Changes</h2>
          <p className="text-muted-foreground text-sm md:text-base animate-fade-in">Latest updates across all entities</p>
          <div className="mt-4 mx-auto w-24 h-1 bg-gradient-to-r from-transparent via-primary to-transparent rounded-full opacity-60"></div>
        </div>
        {recentChanges.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4">
            {recentChanges.map((change) => (
              <RecentChangeCard
                key={`${change.entityType}-${change.entityId}-${change.changedAt}`}
                entityType={change.entityType}
                entityId={change.entityId}
                entityName={change.entityName}
                entitySlug={change.entitySlug}
                parkSlug={change.parkSlug}
                imageUrl={change.imageUrl}
                changeType={change.changeType}
                changedAt={change.changedAt}
                changedByUsername={change.changedByUsername}
                changedByAvatar={change.changedByAvatar}
                changeReason={change.changeReason}
              />
            ))}
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center py-16 px-4">
            <div className="relative mb-6">
              <div className="absolute inset-0 rounded-full bg-primary/20 blur-2xl animate-pulse" />
              <div className="relative w-20 h-20 rounded-full bg-gradient-to-br from-card via-card to-card/80 flex items-center justify-center border-2 border-primary/20 shadow-xl">
                <Clock className="w-10 h-10 text-muted-foreground" />
              </div>
            </div>
            <h3 className="text-xl font-semibold mb-2 text-foreground">No Recent Changes</h3>
            <p className="text-muted-foreground text-center max-w-md text-sm">
              There are no recent entity changes to display yet. Check back soon for the latest updates to parks, rides, and companies!
            </p>
            <div className="mt-6 w-32 h-0.5 bg-gradient-to-r from-transparent via-primary/40 to-transparent rounded-full" />
          </div>
        )}
      </TabsContent>

      <TabsContent value="recently-opened" className="mt-8">
        <div className="text-center mb-6">
          <h2 className="text-2xl md:text-3xl font-bold mb-2 bg-gradient-to-r from-primary via-secondary to-accent bg-clip-text text-transparent drop-shadow-[0_0_12px_rgba(139,92,246,0.3)]">Recently Opened</h2>
          <p className="text-muted-foreground text-sm md:text-base animate-fade-in">Parks and rides that opened in the last year</p>
          <div className="mt-4 mx-auto w-24 h-1 bg-gradient-to-r from-transparent via-primary to-transparent rounded-full opacity-60"></div>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
          {recentlyOpened.map((entity: any) => (
            entity.entityType === 'park' ? (
              <div key={entity.id} className="relative">
                <ParkCard park={entity} />
                <Badge className="absolute top-2 right-2 bg-green-500/90 text-white backdrop-blur-sm">
                  {new Date(entity.opening_date).getFullYear()}
                </Badge>
              </div>
            ) : (
              <div key={entity.id} className="relative">
                <RideCard ride={entity} />
                <Badge className="absolute top-2 right-2 bg-green-500/90 text-white backdrop-blur-sm">
                  {new Date(entity.opening_date).getFullYear()}
                </Badge>
              </div>
            )
          ))}
        </div>
      </TabsContent>

      <TabsContent value="highest-rated-parks" className="mt-8">
        <div className="text-center mb-6">
          <h2 className="text-2xl md:text-3xl font-bold mb-2 bg-gradient-to-r from-primary via-secondary to-accent bg-clip-text text-transparent drop-shadow-[0_0_12px_rgba(139,92,246,0.3)]">Highest Rated Parks</h2>
          <p className="text-muted-foreground text-sm md:text-base animate-fade-in">Top-rated theme parks based on visitor reviews</p>
          <div className="mt-4 mx-auto w-24 h-1 bg-gradient-to-r from-transparent via-primary to-transparent rounded-full opacity-60"></div>
        </div>
        {highestRatedParks.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
            {highestRatedParks.map((park) => (
              <ParkCard key={park.id} park={park} />
            ))}
          </div>
        ) : (
          <div className="text-center py-12 text-muted-foreground">
            No rated parks available yet. Be the first to leave a review!
          </div>
        )}
      </TabsContent>

      <TabsContent value="highest-rated-rides" className="mt-8">
        <div className="text-center mb-6">
          <h2 className="text-2xl md:text-3xl font-bold mb-2 bg-gradient-to-r from-primary via-secondary to-accent bg-clip-text text-transparent drop-shadow-[0_0_12px_rgba(139,92,246,0.3)]">Highest Rated Rides</h2>
          <p className="text-muted-foreground text-sm md:text-base animate-fade-in">Top-rated attractions based on rider reviews</p>
          <div className="mt-4 mx-auto w-24 h-1 bg-gradient-to-r from-transparent via-primary to-transparent rounded-full opacity-60"></div>
        </div>
        {highestRatedRides.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
            {highestRatedRides.map((ride) => (
              <RideCard key={ride.id} ride={ride} />
            ))}
          </div>
        ) : (
          <div className="text-center py-12 text-muted-foreground">
            No rated rides available yet. Be the first to leave a review!
          </div>
        )}
      </TabsContent>

      <TabsContent value="opening-soon" className="mt-8">
        <div className="text-center mb-6">
          <h2 className="text-2xl md:text-3xl font-bold mb-2 bg-gradient-to-r from-primary via-secondary to-accent bg-clip-text text-transparent drop-shadow-[0_0_12px_rgba(139,92,246,0.3)]">Opening Soon</h2>
          <p className="text-muted-foreground text-sm md:text-base animate-fade-in">Parks and rides opening in the next 6 months</p>
          <div className="mt-4 mx-auto w-24 h-1 bg-gradient-to-r from-transparent via-primary to-transparent rounded-full opacity-60"></div>
        </div>
        {openingSoon.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
            {openingSoon.map((entity: any) => (
              entity.entityType === 'park' ? (
                <div key={entity.id} className="relative">
                  <ParkCard park={entity} />
                  <Badge className="absolute top-2 right-2 bg-blue-500/90 text-white backdrop-blur-sm">
                    {new Date(entity.opening_date).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}
                  </Badge>
                </div>
              ) : (
                <div key={entity.id} className="relative">
                  <RideCard ride={entity} />
                  <Badge className="absolute top-2 right-2 bg-blue-500/90 text-white backdrop-blur-sm">
                    {new Date(entity.opening_date).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}
                  </Badge>
                </div>
              )
            ))}
          </div>
        ) : (
          <div className="text-center py-12 text-muted-foreground">
            No parks or rides scheduled to open in the next 6 months.
          </div>
        )}
      </TabsContent>

      <TabsContent value="closing-soon" className="mt-8">
        <div className="text-center mb-6">
          <h2 className="text-2xl md:text-3xl font-bold mb-2 bg-gradient-to-r from-primary via-secondary to-accent bg-clip-text text-transparent drop-shadow-[0_0_12px_rgba(139,92,246,0.3)]">Closing Soon</h2>
          <p className="text-muted-foreground text-sm md:text-base animate-fade-in">Last chance: Parks and rides closing in the next 6 months</p>
          <div className="mt-4 mx-auto w-24 h-1 bg-gradient-to-r from-transparent via-primary to-transparent rounded-full opacity-60"></div>
        </div>
        {closingSoon.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
            {closingSoon.map((entity: any) => (
              entity.entityType === 'park' ? (
                <div key={entity.id} className="relative">
                  <ParkCard park={entity} />
                  <Badge className="absolute top-2 right-2 bg-red-500/90 text-white backdrop-blur-sm">
                    Closes {new Date(entity.closing_date).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}
                  </Badge>
                </div>
              ) : (
                <div key={entity.id} className="relative">
                  <RideCard ride={entity} />
                  <Badge className="absolute top-2 right-2 bg-red-500/90 text-white backdrop-blur-sm">
                    Closes {new Date(entity.closing_date).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}
                  </Badge>
                </div>
              )
            ))}
          </div>
        ) : (
          <div className="text-center py-12 text-muted-foreground">
            No parks or rides scheduled to close in the next 6 months.
          </div>
        )}
      </TabsContent>

      <TabsContent value="recently-closed" className="mt-8">
        <div className="text-center mb-6">
          <h2 className="text-2xl md:text-3xl font-bold mb-2 bg-gradient-to-r from-primary via-secondary to-accent bg-clip-text text-transparent drop-shadow-[0_0_12px_rgba(139,92,246,0.3)]">Recently Closed</h2>
          <p className="text-muted-foreground text-sm md:text-base animate-fade-in">Parks and rides that closed in the last year</p>
          <div className="mt-4 mx-auto w-24 h-1 bg-gradient-to-r from-transparent via-primary to-transparent rounded-full opacity-60"></div>
        </div>
        {recentlyClosed.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
            {recentlyClosed.map((entity: any) => (
              entity.entityType === 'park' ? (
                <div key={entity.id} className="relative">
                  <ParkCard park={entity} />
                  <Badge className="absolute top-2 right-2 bg-gray-500/90 text-white backdrop-blur-sm">
                    Closed {new Date(entity.closing_date).getFullYear()}
                  </Badge>
                </div>
              ) : (
                <div key={entity.id} className="relative">
                  <RideCard ride={entity} />
                  <Badge className="absolute top-2 right-2 bg-gray-500/90 text-white backdrop-blur-sm">
                    Closed {new Date(entity.closing_date).getFullYear()}
                  </Badge>
                </div>
              )
            ))}
          </div>
        ) : (
          <div className="text-center py-12 text-muted-foreground">
            No parks or rides closed in the last year.
          </div>
        )}
      </TabsContent>
        </Tabs>
      </div>
    </section>
  );
}