import React, { useState, useEffect, useRef } from 'react';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Textarea } from './ui/textarea';
import { Badge } from './ui/badge';
import { Card, CardContent } from './ui/card';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from './ui/accordion';
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar';
import { 
  Calendar, 
  Clock, 
  Users, 
  Play, 
  Download, 
  ArrowRight,
  ExternalLink,
  Share2,
  Copy,
  CheckCircle,
  AlertCircle,
  Video,
  Loader2,
  MapPin,
  Globe,
  User,
  Mail,
  Phone,
  Building2,
  ChevronLeft,
  ChevronRight,
  PlayCircle,
  PauseCircle,
  Volume2,
  VolumeX,
  Maximize,
  Minimize,
  X,
  Star,
  ShoppingCart
} 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';
import { toast } from 'sonner@2.0.3';
import { getWebinarBySlug, sharedWebinarsData, type WebinarData } from '../data/webinarsData';

interface WebinarDetailProps {
  params: { slug: string };
}

export default function WebinarDetail({ params }: WebinarDetailProps) {
  // Get webinar data from shared data source
  const [webinar, setWebinar] = useState<WebinarData | null>(null);
  const [timeLeft, setTimeLeft] = useState({ days: 0, hours: 0, minutes: 0, seconds: 0 });
  const [isRegistered, setIsRegistered] = useState(false);
  const [showRegistrationForm, setShowRegistrationForm] = useState(false);
  const [registrationData, setRegistrationData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    company: '',
    jobTitle: '',
    goals: ''
  });
  const [isSubmittingRegistration, setIsSubmittingRegistration] = useState(false);
  const [showShareMenu, setShowShareMenu] = useState(false);
  const [relatedCarouselIndex, setRelatedCarouselIndex] = useState(0);
  const [isVideoPlaying, setIsVideoPlaying] = useState(false);
  const [isMuted, setIsMuted] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);
  const shareMenuRef = useRef<HTMLDivElement>(null);

  // Load webinar data on component mount
  useEffect(() => {
    const webinarData = getWebinarBySlug(params.slug);
    if (webinarData) {
      setWebinar(webinarData);
    } else {
      // Fallback: redirect to webinars page if webinar not found
      navigateTo('/webinars');
    }
  }, [params.slug]);

  // Countdown timer
  useEffect(() => {
    if (!webinar || webinar.status !== 'upcoming') return;

    const targetDate = new Date(`${webinar.date}T${webinar.time}:00`);
    
    const updateCountdown = () => {
      const now = new Date().getTime();
      const distance = targetDate.getTime() - now;

      if (distance > 0) {
        setTimeLeft({
          days: Math.floor(distance / (1000 * 60 * 60 * 24)),
          hours: Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
          minutes: Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)),
          seconds: Math.floor((distance % (1000 * 60)) / 1000)
        });
      }
    };

    updateCountdown();
    const interval = setInterval(updateCountdown, 1000);

    return () => clearInterval(interval);
  }, [webinar?.date, webinar?.time, webinar?.status]);

  // Close share menu when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (shareMenuRef.current && !shareMenuRef.current.contains(event.target as Node)) {
        setShowShareMenu(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Handle registration form submission
  const handleRegistrationSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmittingRegistration(true);

    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 2000));

    setIsSubmittingRegistration(false);
    setIsRegistered(true);
    setShowRegistrationForm(false);
    toast.success('Registration successful! Check your email for confirmation details.');
  };

  // Handle share actions
  const handleShare = (platform: string) => {
    const url = window.location.href;
    const title = webinar?.title || '';
    
    switch (platform) {
      case 'linkedin':
        window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`, '_blank');
        break;
      case 'twitter':
        window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(title)}&url=${encodeURIComponent(url)}`, '_blank');
        break;
      case 'copy':
        navigator.clipboard.writeText(url);
        toast.success('Link copied to clipboard!');
        break;
    }
    setShowShareMenu(false);
  };

  // Get CTA button text and action based on webinar status
  const getCTAProps = () => {
    if (!webinar) return { text: 'Loading...', onClick: () => {}, disabled: true };

    const now = new Date();
    const webinarDate = new Date(`${webinar.date}T${webinar.time}:00`);
    const tenMinutesBefore = new Date(webinarDate.getTime() - 10 * 60 * 1000);

    switch (webinar.status) {
      case 'upcoming':
        return {
          text: webinar.registrationOpen ? 'Register Free' : 'Registration Closed',
          onClick: () => webinar.registrationOpen ? setShowRegistrationForm(true) : null,
          disabled: !webinar.registrationOpen
        };
      case 'live':
        if (now >= tenMinutesBefore) {
          return {
            text: 'Launch in Zoom',
            onClick: () => window.open(webinar.zoomUrl, '_blank'),
            disabled: false
          };
        } else {
          return {
            text: 'Join Available Soon',
            onClick: () => toast.info('Join button will be active 10 minutes before start time'),
            disabled: true
          };
        }
      case 'recorded':
        if (webinar.recordingReady) {
          return {
            text: 'Watch Replay',
            onClick: () => {
              const replaySection = document.getElementById('replay-player');
              replaySection?.scrollIntoView({ behavior: 'smooth' });
            },
            disabled: false
          };
        } else {
          return {
            text: 'Recording Processing',
            onClick: () => toast.info('Recording will be available soon'),
            disabled: true
          };
        }
      default:
        return {
          text: 'Learn More',
          onClick: () => {},
          disabled: false
        };
    }
  };

  // Handle related programmes carousel navigation
  const handleRelatedCarouselNav = (direction: 'prev' | 'next') => {
    if (!webinar) return;
    
    const maxIndex = Math.max(0, webinar.relatedProgrammes.length - 3);
    if (direction === 'prev') {
      setRelatedCarouselIndex(Math.max(0, relatedCarouselIndex - 1));
    } else {
      setRelatedCarouselIndex(Math.min(maxIndex, relatedCarouselIndex + 1));
    }
  };

  // Video player controls
  const togglePlayPause = () => {
    if (videoRef.current) {
      if (isVideoPlaying) {
        videoRef.current.pause();
      } else {
        videoRef.current.play();
      }
      setIsVideoPlaying(!isVideoPlaying);
    }
  };

  const toggleMute = () => {
    if (videoRef.current) {
      videoRef.current.muted = !isMuted;
      setIsMuted(!isMuted);
    }
  };

  const toggleFullscreen = () => {
    if (videoRef.current) {
      if (!isFullscreen) {
        videoRef.current.requestFullscreen();
      } else {
        document.exitFullscreen();
      }
      setIsFullscreen(!isFullscreen);
    }
  };

  // Show loading state while webinar data is loading
  if (!webinar) {
    return (
      <div className="min-h-screen flex items-center justify-center" style={{ backgroundColor: '#FFFFFF' }}>
        <div className="text-center">
          <Loader2 className="w-8 h-8 animate-spin mx-auto mb-4" />
          <p className="text-body text-gray-600">Loading webinar details...</p>
        </div>
      </div>
    );
  }

  const ctaProps = getCTAProps();

  return (
    <div className="min-h-screen" style={{ backgroundColor: '#FFFFFF' }}>
      {/* Countdown Hero */}
      <section className="relative min-h-[600px] lg:min-h-[700px] overflow-hidden">
        {/* Background Image */}
        <div className="absolute inset-0">
          <ImageWithFallback
            src={webinar.thumbnail}
            alt={webinar.title}
            className="w-full h-full object-cover"
          />
          <div className="absolute inset-0 bg-gradient-to-r from-black/80 via-black/60 to-black/40" />
        </div>

        {/* Hero Content */}
        <div className="relative z-10 h-full min-h-[600px] lg:min-h-[700px] flex items-center">
          <div className="section-margin-x w-full">
            <div className="max-w-4xl">
              <BrandedTag text={webinar.theme} variant="white" />
              
              <h1 className="text-h1-white mb-6">
                {webinar.title}
              </h1>
              
              <p className="text-body-lg-white mb-8 max-w-2xl">
                {webinar.description}
              </p>

              {/* Countdown Timer for Upcoming Webinars */}
              {webinar.status === 'upcoming' && (
                <div className="mb-8">
                  <div className="grid grid-cols-4 gap-4 max-w-md mb-4">
                    {[
                      { label: 'Days', value: timeLeft.days },
                      { label: 'Hours', value: timeLeft.hours },
                      { label: 'Minutes', value: timeLeft.minutes },
                      { label: 'Seconds', value: timeLeft.seconds }
                    ].map((unit, index) => (
                      <div key={index} className="text-center">
                        <div className="bg-white/10 backdrop-blur-sm rounded-lg p-3 mb-2">
                          <div className="text-h2-white font-mono">
                            {unit.value.toString().padStart(2, '0')}
                          </div>
                        </div>
                        <div className="text-small-white">{unit.label}</div>
                      </div>
                    ))}
                  </div>
                  <div className="text-small-white opacity-80">
                    Starts {new Date(`${webinar.date}T${webinar.time}:00`).toLocaleDateString('en-US', { 
                      weekday: 'long', 
                      year: 'numeric', 
                      month: 'long', 
                      day: 'numeric' 
                    })} at {webinar.time} {webinar.timezone}
                  </div>
                </div>
              )}

              {/* Live Status */}
              {webinar.status === 'live' && (
                <div className="mb-8">
                  <div className="flex items-center gap-3 mb-4">
                    <div className="flex items-center gap-2 bg-red-600 text-white px-3 py-1 rounded-full">
                      <div className="w-2 h-2 bg-white rounded-full animate-pulse" />
                      <span className="text-small font-medium">LIVE NOW</span>
                    </div>
                    <div className="text-small-white">
                      {webinar.attendees} people watching
                    </div>
                  </div>
                  <div className="text-body-lg-white">
                    Session in progress • Ends at {webinar.endTime} {webinar.timezone}
                  </div>
                </div>
              )}

              {/* Recorded Status */}
              {webinar.status === 'recorded' && (
                <div className="mb-8">
                  <div className="flex items-center gap-3 mb-2">
                    <Badge className="bg-green-600 text-white">COMPLETED</Badge>
                    {webinar.recordingReady && (
                      <Badge className="bg-blue-600 text-white">REPLAY AVAILABLE</Badge>
                    )}
                  </div>
                  <div className="text-body-lg-white">
                    Session held on {new Date(`${webinar.date}T${webinar.time}:00`).toLocaleDateString('en-US', { 
                      month: 'long', 
                      day: 'numeric', 
                      year: 'numeric' 
                    })}
                  </div>
                </div>
              )}

              {/* Primary CTA */}
              <div className="flex flex-col sm:flex-row gap-4">
                <PrimaryCTAButton
                  text={ctaProps.text}
                  onClick={ctaProps.onClick}
                  className={`cta-text-white ${ctaProps.disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
                />
                
                {/* Secondary CTA - Add to Calendar for upcoming */}
                {webinar.status === 'upcoming' && isRegistered && (
                  <Button
                    variant="outline"
                    className="h-12 border-2 border-white/30 text-white hover:bg-white/10 transition-all duration-200"
                    style={{ borderRadius: '10px' }}
                  >
                    <Calendar className="w-4 h-4 mr-2" />
                    Add to Calendar
                  </Button>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Meta Bar */}
      <section className="py-6 border-b border-gray-200">
        <div className="section-margin-x">
          <div className="flex flex-wrap items-center gap-6">
            {/* Host Info */}
            <div className="flex items-center gap-3">
              <Avatar className="w-12 h-12">
                <AvatarImage src={webinar.host.avatar} alt={webinar.host.name} />
                <AvatarFallback>{webinar.host.name.split(' ').map(n => n[0]).join('')}</AvatarFallback>
              </Avatar>
              <div>
                <div className="text-body font-medium">{webinar.host.name}</div>
                <div className="text-small text-muted">{webinar.host.title}</div>
              </div>
            </div>

            {/* Theme Tags */}
            <div className="flex flex-wrap gap-2">
              {webinar.tags.map((tag, index) => (
                <Badge key={index} variant="secondary" className="bg-[#F8C301] bg-opacity-10 text-[#04045B]">
                  {tag}
                </Badge>
              ))}
            </div>

            {/* Duration Badge */}
            <div className="flex items-center gap-2 text-muted">
              <Clock className="w-4 h-4" />
              <span className="text-small">{webinar.duration}</span>
            </div>

            {/* Attendee Count */}
            <div className="flex items-center gap-2 text-muted">
              <Users className="w-4 h-4" />
              <span className="text-small">
                {webinar.attendees} {webinar.status === 'live' ? 'watching' : 'registered'}
              </span>
            </div>
          </div>
        </div>
      </section>

      {/* Main Content */}
      <div className="section-margin-x py-16">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-16">
          {/* Main Content Column */}
          <div className="lg:col-span-2 space-y-16">
            {/* Abstract / What You'll Learn */}
            <section>
              <h2 className="text-h2 mb-6">About This Session</h2>
              <div className="space-y-6">
                <p className="text-body-lg text-muted leading-relaxed">
                  {webinar.abstract}
                </p>
                
                <div>
                  <h3 className="text-h3 mb-4">What You'll Learn</h3>
                  <ul className="space-y-3">
                    {webinar.keyTakeaways.map((takeaway, index) => (
                      <li key={index} className="flex items-start gap-3">
                        <CheckCircle className="w-5 h-5 text-[#04045B] mt-0.5 flex-shrink-0" />
                        <span className="text-body">{takeaway}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            </section>

            {/* Agenda Timeline */}
            <section>
              <h2 className="text-h2 mb-6">Session Agenda</h2>
              <div className="space-y-6">
                {webinar.agenda.map((item, index) => (
                  <div key={index} className="flex gap-6">
                    <div className="flex flex-col items-center">
                      <div className="w-4 h-4 bg-[#04045B] rounded-full" />
                      {index < webinar.agenda.length - 1 && (
                        <div className="w-0.5 h-16 bg-gray-200 mt-2" />
                      )}
                    </div>
                    <div className="flex-1 pb-8">
                      <div className="flex flex-col sm:flex-row sm:items-center gap-2 mb-2">
                        <Badge variant="outline" className="w-fit text-[#04045B] border-[#04045B]">
                          {item.time}
                        </Badge>
                        <h3 className="text-h4">{item.title}</h3>
                      </div>
                      <p className="text-body text-muted">{item.description}</p>
                    </div>
                  </div>
                ))}
              </div>
            </section>

            {/* Host & Panelists */}
            <section>
              <h2 className="text-h2 mb-6">Your Hosts & Speakers</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                {/* Main Host */}
                <Card className="overflow-hidden">
                  <CardContent className="p-6">
                    <div className="flex items-start gap-4 mb-4">
                      <Avatar className="w-16 h-16">
                        <AvatarImage src={webinar.host.avatar} alt={webinar.host.name} />
                        <AvatarFallback>{webinar.host.name.split(' ').map(n => n[0]).join('')}</AvatarFallback>
                      </Avatar>
                      <div className="flex-1">
                        <div className="flex items-start justify-between mb-2">
                          <div>
                            <h3 className="text-h4 mb-1">{webinar.host.name}</h3>
                            <p className="text-small text-[#04045B] font-medium">HOST</p>
                          </div>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => window.open(webinar.host.linkedin, '_blank')}
                            className="text-[#04045B] hover:bg-[#04045B] hover:text-white"
                          >
                            <ExternalLink className="w-4 h-4" />
                          </Button>
                        </div>
                        <p className="text-small text-muted mb-1">{webinar.host.title}</p>
                        <p className="text-small text-muted">{webinar.host.company}</p>
                      </div>
                    </div>
                    <p className="text-small text-muted leading-relaxed">{webinar.host.bio}</p>
                  </CardContent>
                </Card>

                {/* Panelists */}
                {webinar.panelists.map((panelist) => (
                  <Card key={panelist.id} className="overflow-hidden">
                    <CardContent className="p-6">
                      <div className="flex items-start gap-4 mb-4">
                        <Avatar className="w-16 h-16">
                          <AvatarImage src={panelist.avatar} alt={panelist.name} />
                          <AvatarFallback>{panelist.name.split(' ').map(n => n[0]).join('')}</AvatarFallback>
                        </Avatar>
                        <div className="flex-1">
                          <div className="flex items-start justify-between mb-2">
                            <div>
                              <h3 className="text-h4 mb-1">{panelist.name}</h3>
                              <p className="text-small text-[#F8C301] font-medium">SPEAKER</p>
                            </div>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => window.open(panelist.linkedin, '_blank')}
                              className="text-[#04045B] hover:bg-[#04045B] hover:text-white"
                            >
                              <ExternalLink className="w-4 h-4" />
                            </Button>
                          </div>
                          <p className="text-small text-muted mb-1">{panelist.title}</p>
                          <p className="text-small text-muted">{panelist.company}</p>
                        </div>
                      </div>
                      <p className="text-small text-muted leading-relaxed">{panelist.bio}</p>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </section>

            {/* Recording Player for Recorded Webinars */}
            {webinar.status === 'recorded' && webinar.recordingReady && (
              <section id="replay-player">
                <h2 className="text-h2 mb-6">Watch Recording</h2>
                <Card className="overflow-hidden">
                  <div className="aspect-video bg-black relative">
                    <video
                      ref={videoRef}
                      className="w-full h-full"
                      poster={webinar.thumbnail}
                      controls
                    >
                      <source src={webinar.recordingUrl} type="video/mp4" />
                      Your browser does not support the video tag.
                    </video>
                  </div>
                </Card>
              </section>
            )}

            {/* FAQ Section */}
            {webinar.faqs.length > 0 && (
              <section>
                <h2 className="text-h2 mb-6">Frequently Asked Questions</h2>
                <Accordion type="single" collapsible className="w-full">
                  {webinar.faqs.map((faq, index) => (
                    <AccordionItem key={index} value={`item-${index}`}>
                      <AccordionTrigger className="text-left">
                        {faq.question}
                      </AccordionTrigger>
                      <AccordionContent className="text-muted">
                        {faq.answer}
                      </AccordionContent>
                    </AccordionItem>
                  ))}
                </Accordion>
              </section>
            )}
          </div>

          {/* Sidebar */}
          <div className="lg:col-span-1">
            <div className="sticky top-8 space-y-8">
              {/* Registration Card or Session Info */}
              <Card>
                <CardContent className="p-6">
                  <div className="text-center mb-6">
                    <div className="text-h3 mb-2">{webinar.price}</div>
                    <div className="text-small text-muted">
                      {webinar.maxAttendees - parseInt(webinar.attendees.replace(/\D/g, '')) || 0} spots remaining
                    </div>
                  </div>

                  <div className="space-y-4 mb-6">
                    <div className="flex items-center gap-3">
                      <Calendar className="w-5 h-5 text-[#04045B]" />
                      <div>
                        <div className="text-body font-medium">
                          {new Date(`${webinar.date}T${webinar.time}:00`).toLocaleDateString('en-US', { 
                            weekday: 'long', 
                            year: 'numeric', 
                            month: 'long', 
                            day: 'numeric' 
                          })}
                        </div>
                        <div className="text-small text-muted">{webinar.time} {webinar.timezone}</div>
                      </div>
                    </div>

                    <div className="flex items-center gap-3">
                      <Clock className="w-5 h-5 text-[#04045B]" />
                      <div className="text-body">{webinar.duration}</div>
                    </div>

                    <div className="flex items-center gap-3">
                      <Globe className="w-5 h-5 text-[#04045B]" />
                      <div className="text-body">{webinar.format}</div>
                    </div>

                    <div className="flex items-center gap-3">
                      <Users className="w-5 h-5 text-[#04045B]" />
                      <div className="text-body">{webinar.attendees} registered</div>
                    </div>
                  </div>

                  <PrimaryCTAButton
                    text={ctaProps.text}
                    onClick={ctaProps.onClick}
                    className={`w-full cta-text-black ${ctaProps.disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
                  />

                  {/* Share Options */}
                  <div className="relative mt-4" ref={shareMenuRef}>
                    <Button
                      variant="outline"
                      onClick={() => setShowShareMenu(!showShareMenu)}
                      className="w-full"
                    >
                      <Share2 className="w-4 h-4 mr-2" />
                      Share This Webinar
                    </Button>

                    {showShareMenu && (
                      <div className="absolute top-full left-0 right-0 mt-2 bg-white border border-gray-200 rounded-lg shadow-lg z-10">
                        <div className="p-2">
                          <button
                            onClick={() => handleShare('linkedin')}
                            className="w-full px-3 py-2 text-left hover:bg-gray-50 rounded"
                          >
                            Share on LinkedIn
                          </button>
                          <button
                            onClick={() => handleShare('twitter')}
                            className="w-full px-3 py-2 text-left hover:bg-gray-50 rounded"
                          >
                            Share on Twitter
                          </button>
                          <button
                            onClick={() => handleShare('copy')}
                            className="w-full px-3 py-2 text-left hover:bg-gray-50 rounded"
                          >
                            <Copy className="w-4 h-4 inline mr-2" />
                            Copy Link
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>

              {/* Related Programmes */}
              {webinar.relatedProgrammes.length > 0 && (
                <Card>
                  <CardContent className="p-6">
                    <h3 className="text-h4 mb-4">Related Programmes</h3>
                    <div className="space-y-4">
                      {webinar.relatedProgrammes.slice(relatedCarouselIndex, relatedCarouselIndex + 2).map((programme) => {
                        // Calculate save percentage
                        const originalPrice = parseFloat(programme.originalPrice.replace('₹', '').replace(/,/g, ''));
                        const currentPrice = parseFloat(programme.price.replace('₹', '').replace(/,/g, ''));
                        const savePercentage = Math.round(((originalPrice - currentPrice) / originalPrice) * 100);
                        
                        return (
                          <div
                            key={programme.id}
                            className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden hover:shadow-xl transition-all duration-300 cursor-pointer group flex flex-col"
                            onClick={() => navigateTo(`/course/${programme.slug}`)}
                          >
                            {/* Programme Image with Badges */}
                            <div className="relative aspect-[16/9] overflow-hidden flex-shrink-0">
                              <ImageWithFallback
                                src={programme.image}
                                alt={programme.title}
                                className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                              />
                              {/* Category Badge - Yellow */}
                              <div className="absolute top-4 left-4">
                                <Badge 
                                  className="px-3 py-1 font-medium"
                                  style={{
                                    backgroundColor: 'rgba(248, 195, 1, 0.95)',
                                    color: 'var(--color-black)',
                                    fontSize: 'var(--font-small)',
                                    fontFamily: 'var(--font-family-base)',
                                    backdropFilter: 'blur(4px)',
                                    border: 'none'
                                  }}
                                >
                                  {programme.category}
                                </Badge>
                              </div>
                              {/* Level Badge - White */}
                              <div className="absolute top-4 right-4">
                                <Badge 
                                  variant="outline"
                                  className="px-3 py-1 font-medium bg-white/90 backdrop-blur-sm"
                                  style={{
                                    fontSize: 'var(--font-small)',
                                    fontFamily: 'var(--font-family-base)',
                                    borderColor: 'var(--color-primary)',
                                    color: 'var(--color-primary)'
                                  }}
                                >
                                  {programme.level}
                                </Badge>
                              </div>
                            </div>
                            
                            {/* Card Content */}
                            <div className="p-5 flex flex-col flex-1">
                              {/* Programme Title */}
                              <h3 
                                className="mb-3 group-hover:text-blue-600 transition-colors leading-snug"
                                style={{
                                  fontSize: 'var(--font-h4)',
                                  fontWeight: 'var(--font-weight-h4)',
                                  lineHeight: '1.3',
                                  color: 'var(--color-black)',
                                  fontFamily: 'var(--font-family-base)'
                                }}
                              >
                                {programme.title}
                              </h3>
                              
                              {/* Programme Description */}
                              <p 
                                className="mb-5 line-clamp-2 leading-relaxed"
                                style={{
                                  fontSize: 'var(--font-body)',
                                  lineHeight: '1.5',
                                  color: 'var(--color-gray-muted)',
                                  fontFamily: 'var(--font-family-base)',
                                  display: '-webkit-box',
                                  WebkitLineClamp: 2,
                                  WebkitBoxOrient: 'vertical',
                                  overflow: 'hidden',
                                  textOverflow: 'ellipsis'
                                }}
                              >
                                {programme.description}
                              </p>
                              
                              {/* Programme Meta Information */}
                              <div className="flex items-center justify-between mb-5 pt-3 border-t border-gray-100">
                                <div className="flex items-center gap-5">
                                  <div className="flex items-center gap-2">
                                    <Clock className="w-4 h-4 text-gray-400" />
                                    <span style={{ 
                                      fontSize: 'var(--font-small)', 
                                      fontFamily: 'var(--font-family-base)',
                                      color: 'var(--color-gray-muted)',
                                      fontWeight: '500'
                                    }}>
                                      {programme.duration}
                                    </span>
                                  </div>
                                  <div className="flex items-center gap-2">
                                    <Users className="w-4 h-4 text-gray-400" />
                                    <span style={{ 
                                      fontSize: 'var(--font-small)', 
                                      fontFamily: 'var(--font-family-base)',
                                      color: 'var(--color-gray-muted)',
                                      fontWeight: '500'
                                    }}>
                                      {programme.participants}
                                    </span>
                                  </div>
                                </div>
                                
                                <div className="flex items-center gap-1">
                                  <Star className="w-4 h-4 fill-current text-yellow-400" />
                                  <span 
                                    className="font-semibold"
                                    style={{
                                      fontSize: 'var(--font-small)',
                                      fontFamily: 'var(--font-family-base)',
                                      color: 'var(--color-black)'
                                    }}
                                  >
                                    {programme.rating}
                                  </span>
                                </div>
                              </div>

                              {/* Pricing Section */}
                              <div className="mb-5">
                                <div className="flex items-center justify-between">
                                  <div className="flex items-baseline gap-3">
                                    <span 
                                      className="font-bold"
                                      style={{
                                        fontSize: '1.75rem',
                                        fontFamily: 'var(--font-family-base)',
                                        color: '#04045B'
                                      }}
                                    >
                                      {programme.price}
                                    </span>
                                    <span 
                                      className="line-through"
                                      style={{
                                        fontSize: 'var(--font-body)',
                                        fontFamily: 'var(--font-family-base)',
                                        color: 'var(--color-gray-muted)'
                                      }}
                                    >
                                      {programme.originalPrice}
                                    </span>
                                  </div>
                                  <div className="text-right">
                                    <span 
                                      className="text-green-600 font-semibold text-sm"
                                      style={{
                                        fontFamily: 'var(--font-family-base)'
                                      }}
                                    >
                                      Save {savePercentage}%
                                    </span>
                                  </div>
                                </div>
                              </div>
                              
                              {/* Action Buttons - Horizontal Layout */}
                              <div className="flex flex-row gap-2 mt-auto">
                                {/* Add to Cart Button - Outline Blue */}
                                <Button
                                  variant="outline"
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    // Add to cart functionality would go here
                                  }}
                                  className="flex-1 flex items-center justify-center gap-2 h-11 rounded-lg transition-all duration-200 font-medium"
                                  style={{
                                    borderColor: '#04045B',
                                    color: '#04045B',
                                    backgroundColor: 'transparent',
                                    fontSize: 'var(--font-body)',
                                    fontFamily: 'var(--font-family-base)',
                                    fontWeight: '500',
                                    borderWidth: '2px'
                                  }}
                                  onMouseEnter={(e) => {
                                    e.currentTarget.style.backgroundColor = '#04045B';
                                    e.currentTarget.style.color = 'white';
                                  }}
                                  onMouseLeave={(e) => {
                                    e.currentTarget.style.backgroundColor = 'transparent';
                                    e.currentTarget.style.color = '#04045B';
                                  }}
                                >
                                  <ShoppingCart className="w-4 h-4" />
                                  Add to Cart
                                </Button>
                                
                                {/* Learn More Button - Solid Blue */}
                                <Button
                                  className="flex-1 flex items-center justify-center gap-2 h-11 rounded-lg transition-all duration-200 font-medium"
                                  style={{
                                    backgroundColor: '#04045B',
                                    color: 'white',
                                    fontSize: 'var(--font-body)',
                                    fontFamily: 'var(--font-family-base)',
                                    fontWeight: '500',
                                    border: 'none'
                                  }}
                                  onMouseEnter={(e) => {
                                    e.currentTarget.style.backgroundColor = '#030359';
                                  }}
                                  onMouseLeave={(e) => {
                                    e.currentTarget.style.backgroundColor = '#04045B';
                                  }}
                                >
                                  Learn More
                                  <ArrowRight className="w-4 h-4" />
                                </Button>
                              </div>
                            </div>
                          </div>
                        );
                      })}
                    </div>

                    {webinar.relatedProgrammes.length > 2 && (
                      <div className="flex gap-2 mt-4">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleRelatedCarouselNav('prev')}
                          disabled={relatedCarouselIndex === 0}
                        >
                          <ChevronLeft className="w-4 h-4" />
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleRelatedCarouselNav('next')}
                          disabled={relatedCarouselIndex >= webinar.relatedProgrammes.length - 2}
                        >
                          <ChevronRight className="w-4 h-4" />
                        </Button>
                      </div>
                    )}
                  </CardContent>
                </Card>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Registration Modal */}
      <AnimatePresence>
        {showRegistrationForm && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4"
            onClick={(e) => {
              if (e.target === e.currentTarget) {
                setShowRegistrationForm(false);
              }
            }}
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              className="bg-white rounded-lg shadow-xl max-w-md w-full max-h-[90vh] overflow-y-auto"
            >
              <div className="p-6">
                <div className="flex items-center justify-between mb-6">
                  <h3 className="text-h4">Register for Webinar</h3>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setShowRegistrationForm(false)}
                  >
                    <X className="w-4 h-4" />
                  </Button>
                </div>

                <form onSubmit={handleRegistrationSubmit} className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label htmlFor="firstName">First Name *</Label>
                      <Input
                        id="firstName"
                        value={registrationData.firstName}
                        onChange={(e) => setRegistrationData({ ...registrationData, firstName: e.target.value })}
                        required
                      />
                    </div>
                    <div>
                      <Label htmlFor="lastName">Last Name *</Label>
                      <Input
                        id="lastName"
                        value={registrationData.lastName}
                        onChange={(e) => setRegistrationData({ ...registrationData, lastName: e.target.value })}
                        required
                      />
                    </div>
                  </div>

                  <div>
                    <Label htmlFor="email">Email Address *</Label>
                    <Input
                      id="email"
                      type="email"
                      value={registrationData.email}
                      onChange={(e) => setRegistrationData({ ...registrationData, email: e.target.value })}
                      required
                    />
                  </div>

                  <div>
                    <Label htmlFor="company">Company</Label>
                    <Input
                      id="company"
                      value={registrationData.company}
                      onChange={(e) => setRegistrationData({ ...registrationData, company: e.target.value })}
                    />
                  </div>

                  <div>
                    <Label htmlFor="jobTitle">Job Title</Label>
                    <Input
                      id="jobTitle"
                      value={registrationData.jobTitle}
                      onChange={(e) => setRegistrationData({ ...registrationData, jobTitle: e.target.value })}
                    />
                  </div>

                  <div>
                    <Label htmlFor="goals">What do you hope to achieve from this webinar?</Label>
                    <Textarea
                      id="goals"
                      value={registrationData.goals}
                      onChange={(e) => setRegistrationData({ ...registrationData, goals: e.target.value })}
                      rows={3}
                    />
                  </div>

                  <div className="flex gap-3 pt-4">
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => setShowRegistrationForm(false)}
                      className="flex-1"
                    >
                      Cancel
                    </Button>
                    <Button
                      type="submit"
                      disabled={isSubmittingRegistration}
                      className="flex-1"
                      style={{ backgroundColor: 'var(--color-primary)' }}
                    >
                      {isSubmittingRegistration ? (
                        <>
                          <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                          Registering...
                        </>
                      ) : (
                        'Register Free'
                      )}
                    </Button>
                  </div>
                </form>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}