import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { toPng } from 'html-to-image';
import type { Event } from '../../types';
import { useAuth } from '../../context/AuthContext';
import { API_BASE_URL } from '../../lib/config';
import { CLUBS } from './constants';

interface EventCardProps {
  event: Event;
  isBooked: boolean;
  onToggle: (customDetails?: any) => void;
  onTrackStatus?: (event: Event) => void;
  currentUserName?: string;
  userRole?: string;
  registration?: any;
}

const Portal: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  return createPortal(children, document.body);
};

const EventCard: React.FC<EventCardProps> = ({ event, isBooked, onToggle, onTrackStatus, currentUserName = 'Student', userRole, registration }) => {
  const [showConfirm, setShowConfirm] = useState(false);
  const clubInfo = useMemo(() => CLUBS.find(c => c.name === event.club), [event.club]);
  const [showCancelConfirm, setShowCancelConfirm] = useState(false);
  const [showTicket, setShowTicket] = useState(false);
  const [showSummary, setShowSummary] = useState(false);
  const [userDept, setUserDept] = useState<string>('');
  const [userYear, setUserYear] = useState<string>('');
  const [userSection, setUserSection] = useState<string>('');
  const [now, setNow] = useState(new Date());
  const [isDownloading, setIsDownloading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const ticketRef = useRef<HTMLDivElement>(null);
  const [persistedTicket, setPersistedTicket] = useState<{id: string, qr: string} | null>(null);

  // Form states for registration details
  const [formName, setFormName] = useState('');
  const [formDept, setFormDept] = useState('');
  const [formSection, setFormSection] = useState('');
  const [formRegNo, setFormRegNo] = useState('');
  const [formPhone, setFormPhone] = useState('');
  const [formEmail, setFormEmail] = useState('');
  
  // Additional states for external students
  const [formClass, setFormClass] = useState('');
  const [formYear, setFormYear] = useState('');
  const [formCollegeName, setFormCollegeName] = useState('');
  const [formCollegeLocation, setFormCollegeLocation] = useState('');

  const { user } = useAuth();
  const [batches, setBatches] = useState<any[]>([]);

  useEffect(() => {
    const fetchBatches = async () => {
      try {
        const res = await fetch(`${API_BASE_URL}/api/batches`);
        if (res.ok) {
          const data = await res.json();
          setBatches(data);
        }
      } catch (err) {
        console.error(err);
      }
    };
    fetchBatches();
  }, []);

  const studentBatchName = useMemo(() => {
    const userDeptVal = registration?.dept || userDept || (user?.department || '');
    const userYearVal = registration?.year || userYear || (user?.year || '');
    const userSecVal = registration?.section || userSection || (user?.section || '');

    if (!userDeptVal || !userYearVal || !userSecVal) return null;

    const classStr = `${userYearVal} - ${userSecVal}`;
    const match = batches.find(b => b.department === userDeptVal && b.classes?.includes(classStr));
    return match ? match.name : null;
  }, [batches, registration, userDept, userYear, userSection, user]);

  useEffect(() => {
    if (showConfirm && user) {
      setFormName(user.fullName || '');
      setFormDept(user.department || '');
      setFormSection(user.section || 'A');
      setFormRegNo(user.regNo || '');
      setFormPhone(user.phone || '');
      setFormEmail(user.email || '');

      setFormClass(user.department || ''); // Often class relates to dept or branch for externals
      setFormYear(user.year || '');
      setFormCollegeName(user.collegeName || '');
      setFormCollegeLocation('');
    }
  }, [showConfirm, user]);

  const isExternal = user?.department === 'Others' || user?.regNo?.startsWith('EXT-') || (user?.collegeName && user?.collegeName.toLowerCase() !== 'rit');

  useEffect(() => {
    if (showTicket && registration?.id) {
      const initializeTicket = async () => {
        // 1. Check if already persisted
        if (registration.ticket_id && registration.ticket_qrcode) {
          setPersistedTicket({ id: registration.ticket_id, qr: registration.ticket_qrcode });
          return;
        }

        // 2. Otherwise generate and save
        try {
          const newId = `RIT-EVT-${Math.random().toString(36).substring(2, 6).toUpperCase()}-${registration.id.substring(0, 4).toUpperCase()}`;
          const newQr = `${window.location.origin}/?verify=${registration.id}`;
          
          const res = await fetch(`${API_BASE_URL}/api/registrations/${registration.id}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              ticket_id: newId,
              ticket_qrcode: newQr
            })
          });

          if (res.ok) {
            setPersistedTicket({ id: newId, qr: newQr });
          }
        } catch (err) {
          console.error("Ticket initialization failed:", err);
        }
      };
      initializeTicket();
    }
  }, [showTicket, registration?.id]);

  useEffect(() => {
    const timer = setInterval(() => setNow(new Date()), 1000);
    if (user) {
      setUserDept(user.department || '');
      setUserYear(user.year || '');
      setUserSection(user.section || '');
    }
    return () => clearInterval(timer);
  }, [user]);

  const admissionStatus = useMemo(() => {
    if (event.status === 'Completed') return 'EVENT_ENDED';

    if (event.registrationDeadline) {
      const deadline = new Date(event.registrationDeadline);
      if (now > deadline) return 'DEADLINE_PASSED';
    }

    if (event.maxParticipants && (event.currentParticipants || 0) >= event.maxParticipants) {
      return 'TOTAL_FULL';
    }

    if (!event.openToAll && user && user.role === 'STUDENT') {
      const normalize = (s: string) => (s || '').trim().replace(/[^a-zA-Z0-9]/g, '').toLowerCase();

      const userDept = normalize(user.department);
      const eventDept = normalize(event.domain || event.department);

      if (userDept === 'others' || !eventDept || userDept !== eventDept) {
        return 'DEPT_RESTRICTED';
      }

      const userYear = normalize(user.year);
      if (event.academicYears && event.academicYears.length > 0) {
        const yearMatches = event.academicYears.map((y: string) => normalize(y)).includes(userYear);
        if (!yearMatches) {
          return 'YEAR_RESTRICTED';
        }
      }

      const userSec = normalize(user.section);
      if (event.targetedSections && event.targetedSections.length > 0) {
        const sectionMatches = event.targetedSections.map((s: string) => normalize(s)).includes(userSec);
        if (!sectionMatches) {
          return 'SECTION_RESTRICTED';
        }
      }
    }

    return 'OPEN';
  }, [event, now, user]);

  const timeLeft = useMemo(() => {
    const targetDate = new Date(event.date).getTime();
    const distance = targetDate - now.getTime();
    if (isNaN(targetDate) || distance <= 0) return { d: '00', h: '00', m: '00', s: '00' };
    return {
      d: Math.floor(distance / (1000 * 60 * 60 * 24)).toString().padStart(2, '0'),
      h: Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString().padStart(2, '0'),
      m: Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0'),
      s: Math.floor((distance % (1000 * 60)) / 1000).toString().padStart(2, '0')
    };
  }, [event.date, now]);

  const handleDownload = async () => {
    if (!ticketRef.current) return;
    setIsDownloading(true);
    try {
      const dataUrl = await toPng(ticketRef.current, { cacheBust: true, quality: 2, backgroundColor: '#1e293b' });
      const jsPDFModule = await import('jspdf');
      const jsPDFClass = (jsPDFModule.jsPDF || jsPDFModule.default || jsPDFModule) as any;
      
      const width = ticketRef.current.offsetWidth || 380;
      const height = ticketRef.current.offsetHeight || 580;
      
      const pdf = new jsPDFClass({
        orientation: 'portrait',
        unit: 'px',
        format: [width, height]
      });
      
      pdf.addImage(dataUrl, 'PNG', 0, 0, width, height);
      pdf.save(`Pass_${event.title.replace(/\s+/g, '_')}.pdf`);
    } catch (err) {
      console.error("Capture failed:", err);
    } finally {
      setIsDownloading(false);
    }
  };

  const verificationLink = `${window.location.origin}/?verify=local_${event.id}`;

  return (
    <div className="bg-white rounded-[40px] overflow-hidden shadow-xl shadow-gray-900/5 transition-all duration-500 hover:-translate-y-2 flex flex-col h-full group border border-gray-200">
      <div className="h-64 relative overflow-hidden">
        <img src={event.image} alt={event.title} className="w-full h-full object-cover transition-transform duration-1000 group-hover:scale-110" />
        <div className="absolute top-6 left-6 flex flex-col gap-3">
          <div className="bg-white px-5 py-2 rounded-2xl text-[10px] font-black uppercase tracking-widest text-[#f97316] shadow-xl border border-gray-200">{event.category}</div>
          {event.registrationDeadline && (
            <div className={`px-5 py-2 rounded-2xl text-[9px] font-black uppercase tracking-widest text-white shadow-xl flex items-center gap-2 ${admissionStatus === 'DEADLINE_PASSED' ? 'bg-[#1A202C]' : 'bg-rose-600 animate-pulse'}`}>
              <i className="fas fa-clock"></i>
              {admissionStatus === 'DEADLINE_PASSED' ? 'Closed' : `Ends ${new Date(event.registrationDeadline).toLocaleDateString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}`}
            </div>
          )}
        </div>
        {event.domain && (
          <div className="absolute top-6 right-6 z-10">
            <div className="bg-white/90 backdrop-blur-md px-4 py-2 rounded-2xl text-[9px] font-black uppercase tracking-widest text-[#1A202C] shadow-xl border border-white/20">
              <i className="fas fa-building mr-1.5 text-[#f97316]"></i>
              {event.domain}
            </div>
          </div>
        )}
      </div>
      
      <div className="p-10 flex flex-col flex-1">
        <div className="flex justify-between items-start mb-6">
          <div className="flex-1">
            {clubInfo && (
              <div className="flex items-center gap-2 mb-2">
                <img 
                  src={clubInfo.image} 
                  alt={clubInfo.name} 
                  className="w-12 h-12 rounded-full object-cover border border-gray-100 shadow-sm"
                  referrerPolicy="no-referrer"
                />
                <span className="text-[10px] font-black text-[#f97316] uppercase tracking-widest">{clubInfo.name}</span>
              </div>
            )}
            <h3 className="text-3xl font-black text-[#1A202C] line-clamp-2 uppercase tracking-tight group-hover:text-[#f97316] transition-colors">{event.title}</h3>
          </div>
          <div className={`px-4 py-1.5 rounded-full text-[9px] font-black uppercase tracking-widest border ${event.pricingType === 'PAID' ? 'bg-rose-50 border-rose-100 text-rose-600' : 'bg-emerald-50 border-emerald-100 text-emerald-600'}`}>{event.pricingType}</div>
        </div>

        <div className="space-y-3 mb-8 text-gray-400 font-bold text-xs uppercase tracking-widest">
          <div className="flex items-center gap-4">
            <i className="far fa-calendar-alt w-4 text-[#f97316]"></i>
            <span>{event.date}{event.schedule?.[0]?.start_time ? ` • ${event.schedule[0].start_time}` : ''}</span>
          </div>
          {event.durationDays && event.durationDays > 1 && (
            <div className="flex items-center gap-4">
              <i className="fas fa-hourglass-half w-4 text-[#f97316]"></i>
              <span>Duration: {event.durationDays} Days</span>
            </div>
          )}
          <div className="flex items-center justify-between w-full">
            <div className="flex items-center gap-4">
              <i className="fas fa-location-dot w-4 text-[#f97316]"></i>
              <span>{event.location}</span>
            </div>
            {event.event_summary && (
              <button 
                onClick={() => setShowSummary(true)}
                className="w-7 h-7 flex items-center justify-center rounded-xl bg-slate-50 border border-slate-200 text-slate-400 hover:bg-[#f97316] hover:text-white hover:border-[#f97316] transition-all shadow-sm group"
                title="View summary"
              >
                 <i className="fas fa-info text-[10px] group-hover:scale-110 transition-transform"></i>
              </button>
            )}
          </div>
        </div>


        <div className="mb-8 p-6 bg-gray-50 rounded-3xl border border-gray-200">
           <div className="flex justify-between items-center">
              <span className="text-[10px] font-black text-gray-400 uppercase tracking-widest">Global Seats</span>
              <span className="text-xs font-black text-[#1A202C]">{event.currentParticipants || 0} / {event.maxParticipants || '∞'}</span>
           </div>
        </div>

        <div className="flex justify-between items-center mb-10 text-center">
           {[ {l: 'D', v: timeLeft.d}, {l: 'H', v: timeLeft.h}, {l: 'M', v: timeLeft.m}, {l: 'S', v: timeLeft.s} ].map((t, i) => (
             <div key={i} className="flex-1">
               <span className={`block text-2xl font-black leading-none ${i === 3 ? 'text-[#f97316]' : 'text-[#1A202C]'}`}>{t.v}</span>
               <span className="text-[9px] font-black text-gray-400 uppercase tracking-widest">{t.l}</span>
             </div>
           ))}
        </div>

        <div className="mt-auto">
          {userRole === 'ADMIN' || userRole === 'COORDINATOR' ? (
            <button disabled className="w-full py-5 rounded-[2rem] bg-slate-100 border border-slate-200 text-slate-400 font-black uppercase tracking-[0.3em] text-xs cursor-not-allowed">
              View Only ({userRole === 'ADMIN' ? 'Admin' : 'Coordinator'})
            </button>
          ) : isBooked ? (
            <div className="flex flex-col gap-4">
              <button onClick={() => onTrackStatus?.(event)} className="w-full py-5 rounded-[2rem] bg-[#f97316] text-white font-black uppercase tracking-[0.3em] text-xs shadow-xl shadow-orange-100 flex items-center justify-center gap-3 active:scale-[0.98] transition-all">
                Track Progress <i className="fas fa-arrow-right"></i>
              </button>
              {event.status !== 'Completed' && (
                <button onClick={() => setShowTicket(true)} className="w-full py-5 rounded-[2rem] bg-[#1A202C] text-white font-black uppercase tracking-[0.3em] text-xs hover:bg-black transition-all active:scale-[0.98] shadow-xl shadow-gray-200 flex items-center justify-center gap-3">
                  View Ticket <i className="fas fa-ticket"></i>
                </button>
              )}
              {event.status !== 'Event Ongoing' && event.status !== 'Completed' && (
                <button onClick={() => setShowCancelConfirm(true)} className="w-full py-4 text-rose-500 font-black uppercase tracking-widest text-[9px] hover:bg-rose-50 rounded-2xl transition-all flex items-center justify-center gap-2 mt-2">
                  <i className="fas fa-times-circle"></i> Cancel Registration
                </button>
              )}
            </div>
          ) : admissionStatus === 'OPEN' ? (
            <button onClick={() => setShowConfirm(true)} className="w-full py-5 rounded-[2rem] bg-[#1A202C] text-white font-black uppercase tracking-[0.3em] text-xs hover:bg-black transition-all active:scale-95 shadow-xl shadow-gray-200">
              Get Tickets
            </button>
          ) : (
            <button disabled className="w-full py-5 rounded-[2rem] bg-rose-50 border border-rose-100 text-rose-400 font-black uppercase tracking-[0.3em] text-xs cursor-not-allowed">
              {admissionStatus === 'EVENT_ENDED' 
                ? 'EVENT ENDED' 
                : admissionStatus === 'DEADLINE_PASSED' 
                  ? 'Deadline Over' 
                  : admissionStatus === 'DEPT_RESTRICTED'
                    ? 'DEPT RESTRICTED'
                    : admissionStatus === 'YEAR_RESTRICTED'
                      ? 'YEAR RESTRICTED'
                      : admissionStatus === 'SECTION_RESTRICTED'
                        ? 'SEC RESTRICTED'
                        : 'Event Full'}
            </button>
          )}
        </div>
      </div>

      {showConfirm && (
        <Portal>
          <div className="fixed inset-0 z-[10000] flex items-center justify-center p-6 bg-slate-900/60 backdrop-blur-sm">
            <div className="bg-white rounded-[3rem] w-full max-w-lg p-8 shadow-2xl animate-in zoom-in-95 flex flex-col max-h-[90vh]">
              <div className="overflow-y-auto flex-1 pr-2 custom-scrollbar space-y-6">
                <div className={`w-16 h-16 ${event.isTeamEvent ? 'bg-orange-50 text-orange-500' : 'bg-blue-50 text-blue-500'} rounded-full flex items-center justify-center text-2xl mx-auto mb-2`}>
                  <i className={`fas ${event.isTeamEvent ? 'fa-users' : 'fa-ticket'}`}></i>
                </div>
                <h3 className="text-xl font-black text-[#1A202C] uppercase text-center mb-1">
                  {event.isTeamEvent ? 'Team Registration' : 'Confirm Pass?'}
                </h3>
                
                {event.isTeamEvent && (
                  <div className="bg-orange-50 border border-orange-100 rounded-2xl p-4 text-left">
                    <p className="text-[9px] font-black text-orange-600 uppercase tracking-widest mb-1 flex items-center gap-1.5">
                       <i className="fas fa-exclamation-triangle"></i> Important Notice
                    </p>
                    <p className="text-xs text-orange-800 font-bold leading-normal">
                      This is a <span className="underline">team-based event</span>. You must create or join a team in the registrations section after registering.
                    </p>
                  </div>
                )}

                {/* Paid Event Links Box */}
                {event.paymentLink && (
                  <div className="bg-indigo-50 border border-brand-indigo/10 rounded-2xl p-4 text-left">
                    <span className="block text-[8px] font-black text-brand-indigo uppercase tracking-widest mb-2 flex items-center gap-1">
                      <i className="fas fa-link"></i> Required Payment & Form Link
                    </span>
                    <a 
                      href={event.paymentLink} 
                      target="_blank" 
                      rel="noopener noreferrer" 
                      className="text-xs font-black text-blue-600 hover:underline flex items-center gap-1.5 break-all"
                    >
                      {event.paymentLink} <i className="fas fa-external-link-alt text-[9px]"></i>
                    </a>
                  </div>
                )}

                {/* Registration Details Form */}
                <div className="space-y-4 text-left">
                  <span className="block text-[9px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100 pb-1">Review Registration Details</span>
                  
                  {isExternal ? (
                    <>
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                          <label className="block text-[8px] font-black text-slate-400 uppercase tracking-wider mb-1">Name</label>
                          <input 
                            type="text" 
                            value={formName} 
                            onChange={e => setFormName(e.target.value)} 
                            className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-bold outline-none focus:ring-2 focus:ring-brand-indigo/20 text-slate-800"
                            required
                          />
                        </div>
                        <div>
                          <label className="block text-[8px] font-black text-slate-400 uppercase tracking-wider mb-1">College Email ID</label>
                          <input 
                            type="email" 
                            value={formEmail} 
                            onChange={e => setFormEmail(e.target.value)} 
                            className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-bold outline-none focus:ring-2 focus:ring-brand-indigo/20 text-slate-800"
                            required
                          />
                        </div>
                      </div>

                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <label className="block text-[8px] font-black text-slate-400 uppercase tracking-wider mb-1">Class</label>
                          <input 
                            type="text" 
                            value={formClass} 
                            onChange={e => setFormClass(e.target.value)} 
                            className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-bold outline-none focus:ring-2 focus:ring-brand-indigo/20 text-slate-800"
                            required
                          />
                        </div>
                        <div>
                          <label className="block text-[8px] font-black text-slate-400 uppercase tracking-wider mb-1">Year</label>
                          <input 
                            type="text" 
                            value={formYear} 
                            onChange={e => setFormYear(e.target.value)} 
                            className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-bold outline-none focus:ring-2 focus:ring-brand-indigo/20 text-slate-800"
                            required
                          />
                        </div>
                      </div>

                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                          <label className="block text-[8px] font-black text-slate-400 uppercase tracking-wider mb-1">College Name</label>
                          <input 
                            type="text" 
                            value={formCollegeName} 
                            onChange={e => setFormCollegeName(e.target.value)} 
                            className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-bold outline-none focus:ring-2 focus:ring-brand-indigo/20 text-slate-800"
                            required
                          />
                        </div>
                        <div>
                          <label className="block text-[8px] font-black text-slate-400 uppercase tracking-wider mb-1">College Location</label>
                          <input 
                            type="text" 
                            value={formCollegeLocation} 
                            onChange={e => setFormCollegeLocation(e.target.value)} 
                            className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-bold outline-none focus:ring-2 focus:ring-brand-indigo/20 text-slate-800"
                            required
                          />
                        </div>
                      </div>

                      <div>
                        <label className="block text-[8px] font-black text-slate-400 uppercase tracking-wider mb-1">Phone Number</label>
                        <input 
                          type="text" 
                          value={formPhone} 
                          onChange={e => setFormPhone(e.target.value)} 
                          className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-bold outline-none focus:ring-2 focus:ring-brand-indigo/20 text-slate-800"
                          required
                        />
                      </div>
                    </>
                  ) : (
                    <>
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                          <label className="block text-[8px] font-black text-slate-400 uppercase tracking-wider mb-1">Name</label>
                          <input 
                            type="text" 
                            value={formName} 
                            onChange={e => setFormName(e.target.value)} 
                            className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-bold outline-none focus:ring-2 focus:ring-brand-indigo/20 text-slate-800"
                            required
                          />
                        </div>
                        <div>
                          <label className="block text-[8px] font-black text-slate-400 uppercase tracking-wider mb-1">College Email ID</label>
                          <input 
                            type="email" 
                            value={formEmail} 
                            onChange={e => setFormEmail(e.target.value)} 
                            className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-bold outline-none focus:ring-2 focus:ring-brand-indigo/20 text-slate-800"
                            required
                          />
                        </div>
                      </div>

                      <div className="grid grid-cols-3 gap-4">
                        <div>
                          <label className="block text-[8px] font-black text-slate-400 uppercase tracking-wider mb-1">Dept</label>
                          <input 
                            type="text" 
                            value={formDept} 
                            onChange={e => setFormDept(e.target.value)} 
                            className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-bold outline-none focus:ring-2 focus:ring-brand-indigo/20 text-slate-800"
                            required
                          />
                        </div>
                        <div>
                          <label className="block text-[8px] font-black text-slate-400 uppercase tracking-wider mb-1">Section</label>
                          <input 
                            type="text" 
                            value={formSection} 
                            onChange={e => setFormSection(e.target.value)} 
                            className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-bold outline-none focus:ring-2 focus:ring-brand-indigo/20 text-slate-800"
                            required
                          />
                        </div>
                        <div>
                          <label className="block text-[8px] font-black text-slate-400 uppercase tracking-wider mb-1">Roll / Reg No</label>
                          <input 
                            type="text" 
                            value={formRegNo} 
                            onChange={e => setFormRegNo(e.target.value)} 
                            className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-bold outline-none focus:ring-2 focus:ring-brand-indigo/20 text-slate-800"
                            required
                          />
                        </div>
                      </div>

                      <div>
                        <label className="block text-[8px] font-black text-slate-400 uppercase tracking-wider mb-1">Phone Number</label>
                        <input 
                          type="text" 
                          value={formPhone} 
                          onChange={e => setFormPhone(e.target.value)} 
                          className="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-bold outline-none focus:ring-2 focus:ring-brand-indigo/20 text-slate-800"
                          required
                        />
                      </div>
                    </>
                  )}
                </div>
              </div>

              <div className="flex gap-4 border-t border-slate-100 pt-4 mt-6 shrink-0">
                <button onClick={() => setShowConfirm(false)} className="flex-1 py-3.5 bg-gray-100 text-gray-500 rounded-2xl font-black uppercase tracking-widest text-[10px] hover:bg-gray-200 transition-all">Cancel</button>
                <button 
                  onClick={() => { 
                    onToggle({
                      userName: formName,
                      email: formEmail,
                      dept: isExternal ? 'Others' : formDept,
                      section: isExternal ? 'N/A' : formSection,
                      regNo: isExternal ? (user?.regNo || 'EXT-UNKNOWN') : formRegNo,
                      phone: formPhone,
                      class: isExternal ? formClass : undefined,
                      year: isExternal ? formYear : undefined,
                      collegeName: isExternal ? formCollegeName : undefined,
                      collegeLocation: isExternal ? formCollegeLocation : undefined,
                      isExternal
                    }); 
                    setShowConfirm(false); 
                  }} 
                  className={`flex-1 py-3.5 ${event.isTeamEvent ? 'bg-orange-500 shadow-orange-200' : 'bg-[#1A202C] shadow-gray-200'} text-white rounded-2xl font-black uppercase tracking-widest text-[10px] shadow-lg active:scale-95 transition-all`}
                >
                  Confirm
                </button>
              </div>
            </div>
          </div>
        </Portal>
      )}

      {showCancelConfirm && (
        <Portal>
          <div className="fixed inset-0 z-[10000] flex items-center justify-center p-6 bg-slate-900/60 backdrop-blur-sm">
            <div className="bg-white rounded-[3rem] w-full max-w-sm p-12 text-center shadow-2xl animate-in zoom-in-95">
              <div className="w-20 h-20 bg-rose-50 text-rose-500 rounded-full flex items-center justify-center text-3xl mx-auto mb-8"><i className="fas fa-calendar-xmark"></i></div>
              <h3 className="text-2xl font-black text-[#1A202C] uppercase mb-4">Cancel Booking?</h3>
              <p className="text-gray-500 text-sm mb-10">Are you sure you want to cancel your registration for <span className="font-bold">"{event.title}"</span>?</p>
              <div className="flex flex-col gap-3">
                <button onClick={() => { onToggle(); setShowCancelConfirm(false); }} className="w-full py-4 bg-rose-600 text-white rounded-2xl font-black uppercase tracking-widest text-[10px] shadow-lg shadow-rose-200">Yes, Cancel Registration</button>
                <button onClick={() => setShowCancelConfirm(false)} className="w-full py-4 bg-gray-100 text-gray-500 rounded-2xl font-black uppercase tracking-widest text-[10px]">Keep My Booking</button>
              </div>
            </div>
          </div>
        </Portal>
      )}

      {showTicket && (
        <Portal>
          <div className="fixed inset-0 z-[10000] flex items-center justify-center p-4 md:p-6 bg-slate-900/70 backdrop-blur-md animate-in fade-in duration-300">
            <div ref={ticketRef} className="relative bg-white rounded-[3rem] w-full max-w-md overflow-hidden shadow-[0_50px_100px_rgba(0,0,0,0.3)] animate-in zoom-in-95 duration-500 border border-white/20">
              
              {/* Header - Now White Theme as Requested */}
              <div className="p-8 border-b border-gray-100 flex justify-between items-center bg-white">
                <div className="flex items-center gap-4">
                  <div className="w-[3px] h-10 bg-[#f97316] rounded-full"></div>
                  <img
                    src="/Rit-logo.png"
                    alt="RIT Logo"
                    className="h-10 w-auto object-contain"
                  />
                  <div className="flex flex-col leading-none">
                    <span className="text-[8px] font-black text-gray-400 uppercase tracking-[0.2em] mt-1">Secure Entry Pass</span>
                  </div>
                </div>
                <button onClick={() => setShowTicket(false)} className="w-10 h-10 rounded-full bg-slate-50 flex items-center justify-center text-slate-400 hover:text-slate-900 transition-all"><i className="fas fa-times"></i></button>
              </div>

              <div className="p-10">
                <div className="flex flex-col items-center mb-10">
                  <div className="w-48 h-48 bg-gray-50 rounded-[2.5rem] flex items-center justify-center mb-8 border border-gray-100 shadow-inner relative overflow-hidden group">
                    <img 
                      src={event.image} 
                      alt={event.title} 
                      className="w-full h-full object-cover" 
                      crossOrigin="anonymous"
                    />
                    {persistedTicket?.id && (
                      <div className="absolute bottom-2 bg-white/95 backdrop-blur-sm px-4 py-1 rounded-full border border-gray-200 shadow-sm">
                        <span className="text-[8px] font-black text-gray-800 uppercase tracking-widest">{persistedTicket.id}</span>
                      </div>
                    )}
                  </div>
                  <h4 className="text-3xl font-black text-[#1A202C] text-center mb-2 tracking-tighter uppercase leading-none">{event.title}</h4>
                  <div className="w-12 h-1 bg-[#f97316] rounded-full"></div>
                </div>

                <div className="grid grid-cols-2 gap-y-8 gap-x-10 border-t border-dashed border-gray-200 pt-8 mb-10">
                  <div>
                    <span className="block text-[10px] font-black text-gray-400 uppercase tracking-widest mb-1">Attendee</span>
                    <p className="text-sm font-black text-[#1A202C] truncate uppercase">{currentUserName}</p>
                  </div>
                  <div>
                    <span className="block text-[10px] font-black text-gray-400 uppercase tracking-widest mb-1">Year / Section</span>
                    <p className="text-sm font-black text-[#1A202C] truncate uppercase flex items-center gap-1.5">
                      {isExternal ? 'N/A' : (user?.year || 'N/A')} - {isExternal ? 'N/A' : (user?.section || 'N/A')}
                      {studentBatchName && !isExternal && <span className="px-1.5 py-0.5 bg-[#f97316]/10 text-[#f97316] text-[8px] font-black rounded">{studentBatchName}</span>}
                    </p>
                  </div>
                  {event.isTeamEvent && registration?.team_name && (
                    <div className="col-span-2">
                       <span className="block text-[10px] font-black text-gray-400 uppercase tracking-widest mb-1">Team Identity</span>
                       <p className="text-sm font-black text-[#f97316] uppercase tracking-tight">{registration.team_name}</p>
                    </div>
                  )}
                  <div>
                    <span className="block text-[10px] font-black text-gray-400 uppercase tracking-widest mb-1">Event Date</span>
                    <p className="text-sm font-black text-[#1A202C] truncate uppercase">
                      {(() => {
                        try {
                          const d = new Date(event.date);
                          if (isNaN(d.getTime())) return event.date.split(',')[0];
                          return d.toLocaleDateString('en-US', { day: 'numeric', month: 'short', year: 'numeric' });
                        } catch {
                          return event.date.split(',')[0];
                        }
                      })()}
                    </p>
                  </div>
                  <div>
                    <span className="block text-[10px] font-black text-gray-400 uppercase tracking-widest mb-1">Dept</span>
                    <p className="text-sm font-black text-[#1A202C] truncate uppercase">{registration?.dept || userDept || 'Student'}</p>
                  </div>
                </div>

                <div className="space-y-4">
                  <button 
                    onClick={async () => {
                      setIsSaving(true);
                      await handleDownload();
                      
                      // Handle bucket storage: since we transitioned to Firebase, we bypass the Supabase upload
                      if (ticketRef.current && registration?.id) {
                        try {
                           const dataUrl = await toPng(ticketRef.current, { quality: 1, backgroundColor: '#ffffff' });
                           const fileName = `Ticket_${registration.id}.png`;
                        } catch (err) {
                           console.error("Auto-archiving to bucket failed:", err);
                        }
                      }
                      setIsSaving(false);
                    }} 
                    disabled={isDownloading || isSaving} 
                    className="w-full py-5 bg-[#1A202C] text-white rounded-[2rem] font-black uppercase text-xs tracking-[0.3em] flex items-center justify-center gap-4 hover:bg-black transition-all shadow-xl shadow-gray-200 disabled:opacity-50"
                  >
                    {isDownloading || isSaving ? <><i className="fas fa-spinner fa-spin"></i> Processing...</> : <><i className="fas fa-download"></i> Save Pass</>}
                  </button>
                  <p className="text-[8px] text-center font-bold text-gray-400 uppercase tracking-widest">Digital Ticket ID: {persistedTicket?.id || 'GENERATING...'}</p>
                </div>
              </div>
              <div className="bg-[#f97316] h-3 w-full"></div>
            </div>
          </div>
        </Portal>
      )}

      {showSummary && (
        <Portal>
          <div className="fixed inset-0 z-[10000] flex items-center justify-center p-4 sm:p-6 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-300">
            <div className="bg-white rounded-[2rem] w-full max-w-lg shadow-2xl animate-in zoom-in-95 duration-500 max-h-[85vh] flex flex-col relative">
              <button 
                onClick={() => setShowSummary(false)}
                className="absolute top-6 right-6 w-8 h-8 rounded-full bg-slate-100 text-slate-500 hover:bg-slate-200 hover:text-slate-800 transition-all flex items-center justify-center z-10"
              >
                <i className="fas fa-times text-sm"></i>
              </button>
              
              <div className="p-8 overflow-y-auto flex-1 custom-scrollbar">
                <div className="flex items-center gap-4 mb-8 pb-6 border-b border-gray-100 pr-8">
                   {clubInfo && (
                     <img src={clubInfo.image} className="w-12 h-12 rounded-full object-cover border border-slate-200 shadow-sm" alt="" />
                   )}
                   <div>
                     <span className="block text-[10px] font-black text-[#f97316] uppercase tracking-[0.2em] mb-1">{event.club || 'Organized by'}</span>
                     <span className="text-[10px] font-bold text-gray-500 uppercase tracking-widest flex items-center gap-2">
                       <i className="fas fa-user text-[9px]"></i> {event.coordinator}
                     </span>
                   </div>
                </div>
                
                <div className="space-y-6 pb-6 mt-6 border-t border-gray-100 pt-6">
                   <div className="flex items-center gap-2 mb-2">
                      <div className="w-1 h-3 bg-[#f97316] rounded-full"></div>
                      <h4 className="text-[10px] font-black text-slate-800 uppercase tracking-[0.2em]">Summary</h4>
                   </div>
                   <div className="relative pt-2">
                      <i className="fas fa-quote-right absolute top-0 right-0 text-5xl text-slate-50 pointer-events-none -z-10"></i>
                      <p className="text-[14px] text-slate-600 leading-relaxed whitespace-pre-wrap font-medium">
                        {event.event_summary || "Details for this session will be provided soon."}
                      </p>
                   </div>
                </div>

                <div className="mt-4 shrink-0 border-t border-gray-100 pt-6">
                  <button 
                    onClick={() => setShowSummary(false)}
                    className="w-full py-4 bg-slate-900 text-white rounded-2xl font-black uppercase text-[10px] tracking-widest hover:bg-black transition-all shadow-xl shadow-slate-200 focus:outline-none focus:ring-4 focus:ring-slate-100"
                  >
                    Close Summary
                  </button>
                </div>
              </div>
            </div>
          </div>
        </Portal>
      )}
    </div>
  );
};

export default EventCard;
