import React, { useState, useEffect, useRef } from 'react';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Badge } from './ui/badge';
import { Card, CardContent } from './ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar';
import { 
  Search, 
  Filter, 
  ChevronDown, 
  Play, 
  Calendar, 
  Clock, 
  Users, 
  X,
  Mail,
  ArrowRight,
  ExternalLink,
  Loader2
} from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { navigateTo } from './Router';
import { ImageWithFallback } from './figma/ImageWithFallback';
import { BrandedTag } from './about/BrandedTag';
import { PrimaryCTAButton } from './PrimaryCTAButton';


// Mock data for webinars
const mockWebinars = {
  upcoming: [
    {
      id: 1,
      title: "Future-Ready Leadership: Navigating Digital Transformation",
      abstract: "Explore how modern leaders are adapting to digital disruption and driving organizational change through innovative leadership approaches.",
      speaker: {
        name: "Sarah Chen",
        title: "Chief Digital Officer",
        avatar: "https://images.unsplash.com/photo-1494790108755-2616b612b0e0?w=80&h=80&fit=crop&crop=face"
      },
      date: "2024-12-15",
      time: "14:00",
      duration: "60 min",
      status: "upcoming",
      theme: "Digital Leadership",
      registrationOpen: true,
      coverImage: "https://images.unsplash.com/photo-1542744094-24638eff58bb?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxidXNpbmVzcyUyMHN0cmF0ZWd5JTIwZGlnaXRhbCUyMHRyYW5zZm9ybWF0aW9ufGVufDF8fHx8MTc1NjExNDc5OXww&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral",
      attendees: 245
    },
    {
      id: 2,
      title: "Building Resilient Teams in Uncertain Times",
      abstract: "Learn proven strategies for developing team resilience and maintaining high performance during challenging periods.",
      speaker: {
        name: "Marcus Thompson",
        title: "Leadership Coach",
        avatar: "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=80&h=80&fit=crop&crop=face"
      },
      date: "2024-12-18",
      time: "15:30",
      duration: "45 min",
      status: "upcoming",
      theme: "Team Leadership",
      registrationOpen: true,
      coverImage: "https://images.unsplash.com/photo-1598015132635-131afe3ba07f?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxsZWFkZXJzaGlwJTIwdGVhbSUyMGNvbGxhYm9yYXRpb258ZW58MXx8fHwxNzU2MTE0Nzk0fDA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral",
      attendees: 189
    },
    {
      id: 3,
      title: "The Art of Strategic Decision Making",
      abstract: "Master the frameworks and methodologies that top executives use to make complex strategic decisions.",
      speaker: {
        name: "Dr. Rachel Park",
        title: "Strategy Consultant",
        avatar: "https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=80&h=80&fit=crop&crop=face"
      },
      date: "2024-12-20",
      time: "13:00",
      duration: "75 min",
      status: "upcoming",
      theme: "Strategic Leadership",
      registrationOpen: false,
      coverImage: "https://images.unsplash.com/photo-1742996111692-2d924f12a058?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxwcm9mZXNzaW9uYWwlMjBidXNpbmVzcyUyMG1lZXRpbmclMjBjb25mZXJlbmNlfGVufDF8fHx8MTc1NjExNDc4NXww&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral",
      attendees: 312
    }
  ],
  past: [
    {
      id: 4,
      title: "Emotional Intelligence in Leadership",
      abstract: "Discover how emotional intelligence drives effective leadership and creates positive organizational culture.",
      speaker: {
        name: "James Wilson",
        title: "Executive Coach",
        avatar: "/api/placeholder/40/40"
      },
      date: "2024-11-25",
      time: "14:00",
      duration: "60 min",
      status: "replay",
      theme: "Personal Leadership",
      coverImage: "https://images.unsplash.com/photo-1561993629-67302018480e?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxlbW90aW9uYWwlMjBpbnRlbGxpZ2VuY2UlMjBwcm9mZXNzaW9uYWwlMjBkZXZlbG9wbWVudHxlbnwxfHx8fDE3NTYxMTQ4NTJ8MA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral",
      views: 1245
    },
    {
      id: 5,
      title: "Innovation Leadership: Fostering Creative Culture",
      abstract: "Learn how to create an environment that encourages innovation and creative problem-solving.",
      speaker: {
        name: "Lisa Rodriguez",
        title: "Innovation Director",
        avatar: "/api/placeholder/40/40"
      },
      date: "2024-11-20",
      time: "16:00",
      duration: "50 min",
      status: "replay",
      theme: "Innovation Leadership",
      coverImage: "https://images.unsplash.com/photo-1744339699989-550c61f3ecb8?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxpbm5vdmF0aW9uJTIwY3JlYXRpdmUlMjB3b3JrcGxhY2V8ZW58MXx8fHwxNzU2MTE0ODU2fDA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral",
      views: 892
    },
    {
      id: 6,
      title: "Global Leadership: Managing Across Cultures",
      abstract: "Navigate the complexities of leading diverse, multicultural teams in a global business environment.",
      speaker: {
        name: "Ahmed Hassan",
        title: "Global Operations Manager",
        avatar: "/api/placeholder/40/40"
      },
      date: "2024-11-15",
      time: "10:00",
      duration: "65 min",
      status: "replay",
      theme: "Global Leadership",
      coverImage: "https://images.unsplash.com/photo-1650784854945-264d5b0b6b07?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxnbG9iYWwlMjBtdWx0aWN1bHR1cmFsJTIwYnVzaW5lc3MlMjB0ZWFtfGVufDF8fHx8MTc1NjExNDg2Mnww&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral",
      views: 1567
    }
  ]
};

const themes = [
  "All Themes",
  "Digital Leadership",
  "Team Leadership", 
  "Strategic Leadership",
  "Personal Leadership",
  "Innovation Leadership",
  "Global Leadership"
];

const speakers = [
  "All Speakers",
  "Sarah Chen",
  "Marcus Thompson", 
  "Dr. Rachel Park",
  "James Wilson",
  "Lisa Rodriguez",
  "Ahmed Hassan"
];

export function WebinarsListing() {
  const [activeTab, setActiveTab] = useState('upcoming');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedTheme, setSelectedTheme] = useState('All Themes');
  const [selectedSpeaker, setSelectedSpeaker] = useState('All Speakers');
  const [filtersOpen, setFiltersOpen] = useState(false);
  const [emailInput, setEmailInput] = useState('');
  const [isSubscribing, setIsSubscribing] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [page, setPage] = useState(1);
  const searchTimeout = useRef(null);

  // Handle URL hash changes for deep linking
  useEffect(() => {
    const hash = window.location.hash.replace('#', '');
    if (hash === 'upcoming' || hash === 'past') {
      setActiveTab(hash);
    }
  }, []);

  // Update URL hash when tab changes
  const handleTabChange = (value) => {
    setActiveTab(value);
    window.history.pushState(null, null, `/webinars#${value}`);
    
    // Announce to screen readers
    const announcement = `Switched to ${value} webinars. Showing ${getFilteredWebinars(value).length} results.`;
    const liveRegion = document.createElement('div');
    liveRegion.setAttribute('aria-live', 'polite');
    liveRegion.setAttribute('aria-atomic', 'true');
    liveRegion.className = 'sr-only';
    liveRegion.textContent = announcement;
    document.body.appendChild(liveRegion);
    setTimeout(() => document.body.removeChild(liveRegion), 1000);
  };

  // Debounced search
  useEffect(() => {
    if (searchTimeout.current) {
      clearTimeout(searchTimeout.current);
    }
    searchTimeout.current = setTimeout(() => {
      // Search logic would trigger here
    }, 300);
    
    return () => {
      if (searchTimeout.current) {
        clearTimeout(searchTimeout.current);
      }
    };
  }, [searchQuery]);

  // Filter webinars based on current filters
  const getFilteredWebinars = (tab = activeTab) => {
    let webinars = mockWebinars[tab] || [];
    
    if (searchQuery) {
      webinars = webinars.filter(webinar => 
        webinar.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        webinar.abstract.toLowerCase().includes(searchQuery.toLowerCase()) ||
        webinar.speaker.name.toLowerCase().includes(searchQuery.toLowerCase())
      );
    }
    
    if (selectedTheme !== 'All Themes') {
      webinars = webinars.filter(webinar => webinar.theme === selectedTheme);
    }
    
    if (selectedSpeaker !== 'All Speakers') {
      webinars = webinars.filter(webinar => webinar.speaker.name === selectedSpeaker);
    }
    
    return webinars;
  };

  // Handle newsletter subscription
  const handleSubscribe = async (e) => {
    e.preventDefault();
    if (!emailInput || isSubscribing) return;
    
    setIsSubscribing(true);
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 1500));
    setIsSubscribing(false);
    setEmailInput('');
    alert('Successfully subscribed to webinar reminders!');
  };

  // Handle load more for past webinars
  const handleLoadMore = async () => {
    setLoadingMore(true);
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 1000));
    setPage(prev => prev + 1);
    setLoadingMore(false);
  };

  // Clear all filters
  const clearFilters = () => {
    setSearchQuery('');
    setSelectedTheme('All Themes');
    setSelectedSpeaker('All Speakers');
  };

  const hasActiveFilters = searchQuery || selectedTheme !== 'All Themes' || selectedSpeaker !== 'All Speakers';
  const filteredWebinars = getFilteredWebinars();

  return (
    <div className="min-h-screen" style={{ backgroundColor: '#FFFFFF' }}>
      {/* Hero Banner */}
      <section className="relative py-20 overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-r from-[#04045B] via-[#04045B] to-[#030359]" />
        <div className="absolute inset-0 bg-[url('https://images.unsplash.com/photo-1580863651276-3a1669b2e65a?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHx3ZWJpbmFyJTIwaGVybyUyMGJhY2tncm91bmQlMjBwcmVzZW50YXRpb258ZW58MXx8fHwxNzU2MTE0ODA0fDA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral')] bg-cover bg-center opacity-10" />
        
        <div className="relative z-10 section-margin-x">
          <div className="max-w-4xl">
            <BrandedTag text="LEARN & GROW" variant="white" />
            <h1 className="text-h1-white mb-6">
              Expert-Led Webinars for <br />
              Leadership Excellence
            </h1>
            <p className="text-body-lg-white mb-8 max-w-2xl">
              Join industry experts and thought leaders as they share cutting-edge insights, 
              proven strategies, and practical tools to elevate your leadership journey.
            </p>
            
            {/* Hero Stats */}
            <div className="grid grid-cols-3 gap-8 max-w-lg">
              <div className="text-center">
                <div className="text-h2-white">50+</div>
                <div className="text-small-white">Expert Sessions</div>
              </div>
              <div className="text-center">
                <div className="text-h2-white">12K+</div>
                <div className="text-small-white">Global Attendees</div>
              </div>
              <div className="text-center">
                <div className="text-h2-white">95%</div>
                <div className="text-small-white">Satisfaction Rate</div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Main Content */}
      <section className="py-16 section-margin-x">
        {/* Tab Switcher */}
        <Tabs value={activeTab} onValueChange={handleTabChange} className="w-full">
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between mb-8">
            <TabsList className="grid w-full lg:w-auto grid-cols-2 mb-4 lg:mb-0">
              <TabsTrigger 
                value="upcoming" 
                className="data-[state=active]:bg-[#04045B] data-[state=active]:text-white"
              >
                Upcoming Webinars
              </TabsTrigger>
              <TabsTrigger 
                value="past"
                className="data-[state=active]:bg-[#04045B] data-[state=active]:text-white"
              >
                Past Webinars
              </TabsTrigger>
            </TabsList>

            {/* Results Count */}
            <div className="text-small text-muted">
              Showing {filteredWebinars.length} result{filteredWebinars.length !== 1 ? 's' : ''}
            </div>
          </div>

          {/* Filter & Search Bar */}
          <Card className="mb-8">
            <CardContent className="p-6">
              {/* Mobile Filter Toggle */}
              <div className="lg:hidden mb-4">
                <Button
                  variant="outline"
                  onClick={() => setFiltersOpen(!filtersOpen)}
                  className="w-full justify-between"
                >
                  <div className="flex items-center gap-2">
                    <Filter className="w-4 h-4" />
                    Filters & Search
                  </div>
                  <ChevronDown className={`w-4 h-4 transition-transform ${filtersOpen ? 'rotate-180' : ''}`} />
                </Button>
              </div>

              {/* Filter Content */}
              <div className={`space-y-4 lg:space-y-0 lg:grid lg:grid-cols-12 lg:gap-4 lg:items-end ${!filtersOpen ? 'hidden lg:grid' : ''}`}>
                {/* Search Input */}
                <div className="lg:col-span-4">
                  <label className="block text-small font-medium mb-2">Search Webinars</label>
                  <div className="relative">
                    <Input
                      type="text"
                      placeholder="Search by title, speaker, or topic..."
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      className="pl-10"
                    />
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted" />
                  </div>
                </div>

                {/* Theme Filter */}
                <div className="lg:col-span-3">
                  <label className="block text-small font-medium mb-2">Theme</label>
                  <select
                    value={selectedTheme}
                    onChange={(e) => setSelectedTheme(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#04045B] focus:border-transparent"
                  >
                    {themes.map(theme => (
                      <option key={theme} value={theme}>{theme}</option>
                    ))}
                  </select>
                </div>

                {/* Speaker Filter */}
                <div className="lg:col-span-3">
                  <label className="block text-small font-medium mb-2">Speaker</label>
                  <select
                    value={selectedSpeaker}
                    onChange={(e) => setSelectedSpeaker(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#04045B] focus:border-transparent"
                  >
                    {speakers.map(speaker => (
                      <option key={speaker} value={speaker}>{speaker}</option>
                    ))}
                  </select>
                </div>

                {/* Clear Filters */}
                <div className="lg:col-span-2">
                  {hasActiveFilters && (
                    <Button
                      variant="outline"
                      onClick={clearFilters}
                      className="w-full"
                    >
                      <X className="w-4 h-4 mr-2" />
                      Clear
                    </Button>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Tab Content */}
          <TabsContent value="upcoming" className="mt-0">
            <WebinarGrid webinars={filteredWebinars} type="upcoming" />
          </TabsContent>

          <TabsContent value="past" className="mt-0">
            <WebinarGrid webinars={filteredWebinars} type="past" />
            
            {/* Load More Button for Past Webinars */}
            {filteredWebinars.length > 0 && (
              <div className="text-center mt-8">
                <Button
                  onClick={handleLoadMore}
                  disabled={loadingMore}
                  className="bg-[#04045B] hover:bg-[#030359] text-white"
                >
                  {loadingMore ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      Loading More...
                    </>
                  ) : (
                    'Load More Webinars'
                  )}
                </Button>
              </div>
            )}
          </TabsContent>
        </Tabs>

        {/* Empty State */}
        {filteredWebinars.length === 0 && (
          <EmptyState 
            type={activeTab} 
            hasFilters={hasActiveFilters}
            onClearFilters={clearFilters}
            onSwitchTab={() => handleTabChange(activeTab === 'upcoming' ? 'past' : 'upcoming')}
          />
        )}
      </section>

      {/* Newsletter CTA Panel */}
      <section className="py-16 bg-gray-50">
        <div className="section-margin-x">
          <div className="max-w-4xl mx-auto text-center">
            <div className="mb-8">
              <h2 className="text-h2 mb-4">Never Miss a Session</h2>
              <p className="text-body-lg text-muted max-w-2xl mx-auto">
                Get notified about upcoming webinars, exclusive leadership insights, and 
                early access to replay content. Join our community of 12,000+ leaders.
              </p>
            </div>

            <form onSubmit={handleSubscribe} className="max-w-md mx-auto">
              <div className="flex gap-3">
                <div className="flex-1">
                  <Input
                    type="email"
                    placeholder="Enter your email address"
                    value={emailInput}
                    onChange={(e) => setEmailInput(e.target.value)}
                    required
                    className="h-12"
                  />
                </div>
                <Button
                  type="submit"
                  disabled={isSubscribing || !emailInput}
                  className="bg-[#04045B] hover:bg-[#030359] text-white h-12 px-6"
                >
                  {isSubscribing ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <>
                      <Mail className="w-4 h-4 mr-2" />
                      Subscribe
                    </>
                  )}
                </Button>
              </div>
              <p className="text-small text-muted mt-3">
                No spam, unsubscribe at any time. We respect your privacy.
              </p>
            </form>
          </div>
        </div>
      </section>
    </div>
  );
}

// Webinar Grid Component
function WebinarGrid({ webinars, type }) {
  if (webinars.length === 0) return null;

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
      {webinars.map((webinar, index) => (
        <WebinarCard key={webinar.id} webinar={webinar} type={type} index={index} />
      ))}
    </div>
  );
}

// Individual Webinar Card Component
function WebinarCard({ webinar, type, index }) {
  const [isHovered, setIsHovered] = useState(false);
  const [imageError, setImageError] = useState(false);

  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', { 
      month: 'short', 
      day: 'numeric',
      year: 'numeric'
    });
  };

  const getStatusBadge = () => {
    switch (webinar.status) {
      case 'live':
        return <Badge className="bg-red-500 text-white">LIVE</Badge>;
      case 'upcoming':
        return <Badge className="bg-[#04045B] text-white">Upcoming</Badge>;
      case 'replay':
        return <Badge className="bg-green-600 text-white">Replay</Badge>;
      default:
        return null;
    }
  };

  const handleCardClick = () => {
    // Navigate to webinar detail page
    navigateTo(`/webinar/${webinar.id}`);
  };

  const handleCTAClick = (e) => {
    e.stopPropagation();
    
    if (webinar.status === 'upcoming') {
      if (webinar.registrationOpen) {
        // Handle registration
        alert('Registration functionality would be implemented here');
      } else {
        // Show tooltip or message
        alert('Registration is closed for this webinar');
      }
    } else if (webinar.status === 'replay') {
      // Navigate to replay
      navigateTo(`/webinar/${webinar.id}`);
    }
  };

  return (
    <motion.article
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.5, delay: index * 0.1 }}
      className="group cursor-pointer"
      onClick={handleCardClick}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      role="article"
      tabIndex={0}
      onKeyDown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          handleCardClick();
        }
      }}
    >
      <Card className="overflow-hidden transition-all duration-300 hover:shadow-lg hover:-translate-y-1 focus-within:shadow-lg focus-within:-translate-y-1">
        <div className="relative">
          {/* Status Badge */}
          <div className="absolute top-3 left-3 z-10">
            {getStatusBadge()}
          </div>

          {/* Cover Image */}
          <div className="relative h-48 overflow-hidden">
            <ImageWithFallback
              src={webinar.coverImage}
              alt={webinar.title}
              className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
              onError={() => setImageError(true)}
            />
            {imageError && (
              <div className="absolute inset-0 bg-gray-200 flex items-center justify-center">
                <Play className="w-12 h-12 text-gray-400" />
              </div>
            )}
          </div>

          {/* Hover Overlay */}
          <AnimatePresence>
            {isHovered && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center"
              >
                <div className="text-center text-white p-4">
                  <Play className="w-12 h-12 mx-auto mb-2" />
                  <p className="text-small">{webinar.abstract}</p>
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>

        <CardContent className="p-6">
          {/* Theme Badge */}
          <Badge variant="secondary" className="mb-3 bg-[#F8C301] bg-opacity-10 text-[#04045B]">
            {webinar.theme}
          </Badge>

          {/* Title */}
          <h3 className="text-h4 mb-3 line-clamp-2 group-hover:text-[#04045B] transition-colors">
            {webinar.title}
          </h3>

          {/* Speaker */}
          <div className="flex items-center gap-3 mb-4">
            <Avatar className="w-10 h-10">
              <AvatarImage src={webinar.speaker.avatar} alt={webinar.speaker.name} />
              <AvatarFallback>{webinar.speaker.name.split(' ').map(n => n[0]).join('')}</AvatarFallback>
            </Avatar>
            <div>
              <div className="text-body font-medium">{webinar.speaker.name}</div>
              <div className="text-small text-muted">{webinar.speaker.title}</div>
            </div>
          </div>

          {/* Meta Information */}
          <div className="flex items-center gap-4 mb-4 text-small text-muted">
            <div className="flex items-center gap-1">
              <Calendar className="w-4 h-4" />
              {formatDate(webinar.date)}
            </div>
            <div className="flex items-center gap-1">
              <Clock className="w-4 h-4" />
              {webinar.duration}
            </div>
            {type === 'upcoming' && (
              <div className="flex items-center gap-1">
                <Users className="w-4 h-4" />
                {webinar.attendees} registered
              </div>
            )}
            {type === 'past' && (
              <div className="flex items-center gap-1">
                <Play className="w-4 h-4" />
                {webinar.views} views
              </div>
            )}
          </div>

          {/* CTA Button */}
          <Button
            onClick={handleCTAClick}
            disabled={webinar.status === 'upcoming' && !webinar.registrationOpen}
            className={`w-full ${
              webinar.status === 'upcoming' && !webinar.registrationOpen
                ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                : 'bg-[#04045B] hover:bg-[#030359] text-white'
            }`}
          >
            {webinar.status === 'upcoming' && webinar.registrationOpen && 'Register Now'}
            {webinar.status === 'upcoming' && !webinar.registrationOpen && 'Registration Closed'}
            {webinar.status === 'replay' && (
              <>
                Watch Replay
                <ExternalLink className="w-4 h-4 ml-2" />
              </>
            )}
          </Button>
        </CardContent>
      </Card>
    </motion.article>
  );
}

// Empty State Component
function EmptyState({ type, hasFilters, onClearFilters, onSwitchTab }) {
  const isUpcoming = type === 'upcoming';
  
  return (
    <div className="text-center py-16">
      <div className="max-w-md mx-auto">
        <div className="w-20 h-20 mx-auto mb-6 bg-gray-100 rounded-full flex items-center justify-center">
          <Calendar className="w-10 h-10 text-gray-400" />
        </div>
        
        <h3 className="text-h3 mb-4">
          {hasFilters ? 'No Results Found' : 
           isUpcoming ? 'No Upcoming Webinars' : 'No Past Webinars'}
        </h3>
        
        <p className="text-body text-muted mb-6">
          {hasFilters ? 
            'Try adjusting your search criteria or clear filters to see more results.' :
            isUpcoming ? 
              'We\'re planning exciting sessions. Check back soon or explore our past webinars.' :
              'Our webinar archive is growing. Check out our upcoming sessions.'
          }
        </p>
        
        <div className="flex flex-col sm:flex-row gap-3 justify-center">
          {hasFilters && (
            <Button onClick={onClearFilters} variant="outline">
              Clear Filters
            </Button>
          )}
          
          <Button onClick={onSwitchTab} className="bg-[#04045B] hover:bg-[#030359] text-white">
            {isUpcoming ? 'View Past Webinars' : 'View Upcoming Webinars'}
            <ArrowRight className="w-4 h-4 ml-2" />
          </Button>
        </div>
      </div>
    </div>
  );
}

export default WebinarsListing;