import { useState, useEffect } from 'react';
import { inventoryManager } from '../lib/inventory';
import { calculateFeeBreakdown } from '../lib/stripe';
import { 
  formatAvailabilityDisplay, 
  shouldShowTicketType, 
  defaultAvailabilitySettings,
  type EventAvailabilitySettings,
  type AvailabilityInfo 
} from '../lib/availabilityDisplay';

interface TicketType {
  id: string;
  name: string;
  description?: string;
  price: number;
  quantity_available?: number;
  is_active: boolean;
  requires_presale_code?: boolean;
  presale_start_time?: string;
  presale_end_time?: string;
  general_sale_start_time?: string;
}

interface EventData {
  id: string;
  title: string;
  ticket_types: TicketType[];
  availability_display_mode?: 'available_only' | 'show_quantity' | 'smart_threshold';
  availability_threshold?: number;
  show_sold_out?: boolean;
  low_stock_threshold?: number;
  availability_messages?: {
    available: string;
    low_stock: string;
    sold_out: string;
    unlimited: string;
  };
  organizations: {
    platform_fee_type?: string;
    platform_fee_percentage?: number;
    platform_fee_fixed?: number;
  };
}

interface Props {
  event: EventData;
}

export default function TicketCheckout({ event }: Props) {
  const [selectedTickets, setSelectedTickets] = useState<Map<string, any>>(new Map());
  const [currentReservations, setCurrentReservations] = useState<Map<string, any>>(new Map());
  const [availability, setAvailability] = useState<Map<string, AvailabilityInfo>>(new Map());
  const [loading, setLoading] = useState(true);
  const [timeRemaining, setTimeRemaining] = useState<string>('');
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [presaleCode, setPresaleCode] = useState('');
  const [presaleCodeValidated, setPresaleCodeValidated] = useState(false);
  const [presaleCodeData, setPresaleCodeData] = useState<any>(null);
  const [presaleCodeError, setPresaleCodeError] = useState('');
  const [expandedDescriptions, setExpandedDescriptions] = useState<Set<string>>(new Set());

  // Check if presale is currently active
  const hasActivePresale = event.ticket_types?.some(ticketType => {
    if (!ticketType.requires_presale_code) return false;
    
    const now = new Date();
    const presaleStart = ticketType.presale_start_time ? new Date(ticketType.presale_start_time) : null;
    const presaleEnd = ticketType.presale_end_time ? new Date(ticketType.presale_end_time) : null;
    const generalSaleStart = ticketType.general_sale_start_time ? new Date(ticketType.general_sale_start_time) : null;
    
    // If general sale hasn't started yet, check if we're in presale period
    if (generalSaleStart && now < generalSaleStart) {
      // If presale has specific timing, check if we're in the window
      if (presaleStart && presaleEnd) {
        return now >= presaleStart && now <= presaleEnd;
      } else if (presaleStart) {
        return now >= presaleStart;
      }
      return true; // Presale required but no specific timing - assume active
    }
    
    // If general sale has started, presale is no longer active
    return false;
  }) || false;

  const feeStructure = event?.organizations ? {
    fee_type: event.organizations.platform_fee_type,
    fee_percentage: event.organizations.platform_fee_percentage,
    fee_fixed: event.organizations.platform_fee_fixed
  } : null;

  // Get availability settings with defaults
  const availabilitySettings: EventAvailabilitySettings = {
    availability_display_mode: event.availability_display_mode || defaultAvailabilitySettings.availability_display_mode,
    availability_threshold: event.availability_threshold || defaultAvailabilitySettings.availability_threshold,
    show_sold_out: event.show_sold_out ?? defaultAvailabilitySettings.show_sold_out,
    low_stock_threshold: event.low_stock_threshold || defaultAvailabilitySettings.low_stock_threshold,
    availability_messages: event.availability_messages || defaultAvailabilitySettings.availability_messages
  };

  // Load availability for all ticket types
  useEffect(() => {
    async function loadAvailability() {
      const availabilityMap = new Map();
      
      for (const ticketType of event.ticket_types?.filter(tt => tt.is_active) || []) {
        try {
          const avail = await inventoryManager.getAvailability(ticketType.id);
          availabilityMap.set(ticketType.id, avail);
        } catch (error) {
          console.error('Error loading availability for', ticketType.id, error);
          availabilityMap.set(ticketType.id, { is_available: false, error: true });
        }
      }
      
      setAvailability(availabilityMap);
      setLoading(false);
    }

    loadAvailability();
  }, [event.ticket_types]);

  // Timer effect
  useEffect(() => {
    if (currentReservations.size === 0) return;

    const timer = setInterval(() => {
      const firstReservation = Array.from(currentReservations.values())[0];
      if (firstReservation) {
        const now = new Date().getTime();
        const expiry = new Date(firstReservation.expires_at).getTime();
        const timeLeft = expiry - now;

        if (timeLeft <= 0) {
          alert('Your ticket reservation has expired. Please select your tickets again.');
          window.location.reload();
        } else {
          const minutes = Math.floor(timeLeft / 60000);
          const seconds = Math.floor((timeLeft % 60000) / 1000);
          setTimeRemaining(`${minutes}:${seconds.toString().padStart(2, '0')}`);
        }
      }
    }, 1000);

    return () => clearInterval(timer);
  }, [currentReservations]);

  const handleQuantityChange = async (ticketTypeId: string, newQuantity: number) => {
    const currentQuantity = selectedTickets.get(ticketTypeId)?.quantity || 0;
    
    if (newQuantity === currentQuantity) return;

    console.log('Quantity change:', { ticketTypeId, currentQuantity, newQuantity });

    try {
      // Release existing reservation if any
      if (currentReservations.has(ticketTypeId)) {
        console.log('Releasing existing reservation...');
        await inventoryManager.releaseReservation(currentReservations.get(ticketTypeId).id);
        const newReservations = new Map(currentReservations);
        newReservations.delete(ticketTypeId);
        setCurrentReservations(newReservations);
      }

      if (newQuantity > 0) {
        console.log('Reserving tickets:', { ticketTypeId, quantity: newQuantity });
        // Reserve new tickets
        const reservation = await inventoryManager.reserveTickets(ticketTypeId, newQuantity, 15);
        console.log('Reservation successful:', reservation);
        
        const newReservations = new Map(currentReservations);
        newReservations.set(ticketTypeId, reservation);
        setCurrentReservations(newReservations);

        // Update selected tickets
        const ticketType = event.ticket_types?.find(tt => tt.id === ticketTypeId);
        const newSelected = new Map(selectedTickets);
        newSelected.set(ticketTypeId, {
          quantity: newQuantity,
          price: typeof ticketType?.price === 'string' ? Math.round(parseFloat(ticketType.price) * 100) : ticketType?.price,
          name: ticketType?.name,
          reservation_id: reservation.id
        });
        setSelectedTickets(newSelected);
      } else {
        // Remove from selected tickets
        const newSelected = new Map(selectedTickets);
        newSelected.delete(ticketTypeId);
        setSelectedTickets(newSelected);
      }
    } catch (error) {
      console.error('Error updating reservation:', error);
      console.error('Error details:', error);
      alert(error.message || 'Error reserving tickets. Please try again.');
    }
  };

  const calculateTotals = () => {
    let subtotal = 0;
    let totalQuantity = 0;

    for (const ticket of selectedTickets.values()) {
      subtotal += ticket.quantity * ticket.price;
      totalQuantity += ticket.quantity;
    }

    if (totalQuantity === 0) {
      return { subtotal: 0, platformFee: 0, total: 0 };
    }

    const avgPrice = subtotal / totalQuantity;
    const breakdown = calculateFeeBreakdown(avgPrice / 100, totalQuantity, feeStructure);

    return {
      subtotal,
      platformFee: breakdown.totalPlatformFee,
      total: subtotal + breakdown.totalPlatformFee
    };
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (selectedTickets.size === 0) return;

    try {
      // Create purchase attempt
      const items = Array.from(selectedTickets.entries()).map(([ticketTypeId, ticket]) => ({
        ticket_type_id: ticketTypeId,
        quantity: ticket.quantity,
        unit_price: ticket.price / 100
      }));

      const totals = calculateTotals();
      
      const purchaseAttempt = await inventoryManager.createPurchaseAttempt(
        event.id,
        email,
        name,
        items,
        totals.platformFee / 100
      );

      alert('Checkout integration coming soon! Your tickets are reserved.');
      console.log('Purchase attempt created:', purchaseAttempt);
      
    } catch (error) {
      console.error('Error creating purchase:', error);
      alert(error.message || 'Error processing purchase. Please try again.');
    }
  };

  const validatePresaleCode = async () => {
    if (!presaleCode.trim()) {
      setPresaleCodeError('Please enter a presale code');
      return;
    }

    try {
      const response = await fetch('/api/presale/validate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          code: presaleCode.trim(),
          event_id: event.id,
          customer_email: email || null,
          customer_session: sessionStorage.getItem('checkout_session') || null
        }),
      });

      const data = await response.json();

      if (data.success) {
        setPresaleCodeValidated(true);
        setPresaleCodeData(data);
        setPresaleCodeError('');
        // Store session for future validation
        if (!sessionStorage.getItem('checkout_session')) {
          sessionStorage.setItem('checkout_session', Math.random().toString(36));
        }
      } else {
        setPresaleCodeError(data.error || 'Invalid presale code');
      }
    } catch (error) {
      console.error('Error validating presale code:', error);
      setPresaleCodeError('Error validating code. Please try again.');
    }
  };

  const toggleDescription = (ticketTypeId: string) => {
    const newExpanded = new Set(expandedDescriptions);
    if (newExpanded.has(ticketTypeId)) {
      newExpanded.delete(ticketTypeId);
    } else {
      newExpanded.add(ticketTypeId);
    }
    setExpandedDescriptions(newExpanded);
  };

  const truncateDescription = (description: string, maxLength: number = 100) => {
    if (description.length <= maxLength) return description;
    return description.substring(0, maxLength) + '...';
  };

  const totals = calculateTotals();

  if (loading) {
    return <div className="text-center py-8">Loading ticket availability...</div>;
  }

  return (
    <div className="space-y-6">
      {/* Note: Header moved to parent component */}
      
      {/* Presale Code Entry - Only show if presale is active */}
      {hasActivePresale && !presaleCodeValidated && (
        <div className="mb-6 p-6 bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200 rounded-2xl">
          <div className="flex items-end gap-4">
            <div className="flex-1">
              <label htmlFor="presale-code" className="block text-sm font-semibold text-blue-900 mb-2">
                Presale Code Required
              </label>
              <input
                id="presale-code"
                type="text"
                value={presaleCode}
                onChange={(e) => {
                  setPresaleCode(e.target.value.toUpperCase());
                  setPresaleCodeError('');
                }}
                placeholder="Enter your presale code"
                className="w-full px-4 py-3 border-2 border-blue-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200 text-slate-900 placeholder-blue-400 bg-white hover:border-blue-400"
              />
              {presaleCodeError && (
                <p className="text-red-600 text-sm mt-2 font-medium">{presaleCodeError}</p>
              )}
            </div>
            <button
              type="button"
              onClick={validatePresaleCode}
              className="px-6 py-3 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-xl hover:from-blue-700 hover:to-indigo-700 font-semibold text-sm whitespace-nowrap transition-all duration-200 shadow-lg hover:shadow-xl"
            >
              Apply Code
            </button>
          </div>
        </div>
      )}

      {/* Presale Code Success - Compact version */}
      {presaleCodeValidated && presaleCodeData && (
        <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <svg className="w-4 h-4 text-green-600" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
              </svg>
              <span className="text-sm font-medium text-green-900">
                Presale access granted
              </span>
            </div>
            <button
              type="button"
              onClick={() => {
                setPresaleCodeValidated(false);
                setPresaleCodeData(null);
                setPresaleCode('');
              }}
              className="text-green-600 hover:text-green-800 text-sm font-medium"
            >
              Remove
            </button>
          </div>
        </div>
      )}
      
      {/* Ticket Type Selection */}
      <div className="space-y-4 mb-6">
        {event.ticket_types
          ?.filter(tt => tt.is_active)
          ?.filter(ticketType => {
            const avail = availability.get(ticketType.id);
            return avail ? shouldShowTicketType(avail, availabilitySettings) : true;
          })
          ?.filter(ticketType => {
            // If ticket type requires presale code, check if user has validated one
            // and if the presale code gives access to this ticket type
            if (ticketType.requires_presale_code) {
              if (!presaleCodeValidated || !presaleCodeData) {
                return false;
              }
              // Check if presale code gives access to this ticket type
              const hasAccess = presaleCodeData.accessible_ticket_types?.some(
                (accessibleType: any) => accessibleType.id === ticketType.id
              );
              if (!hasAccess) {
                return false;
              }
            }
            return true;
          })
          ?.map(ticketType => {
            const avail = availability.get(ticketType.id);
            const selectedQuantity = selectedTickets.get(ticketType.id)?.quantity || 0;
            const price = typeof ticketType.price === 'string' ? parseFloat(ticketType.price) : (ticketType.price / 100);
            
            // Get formatted availability display
            const availabilityDisplay = avail 
              ? formatAvailabilityDisplay(avail, availabilitySettings)
              : { text: 'Loading...', className: 'text-gray-500', showExactCount: false, isLowStock: false, isSoldOut: false };
            
            return (
              <div key={ticketType.id} className={`border-2 rounded-2xl p-6 transition-all duration-200 ${
                availabilityDisplay.isSoldOut 
                  ? 'bg-slate-50 opacity-75 border-slate-200' 
                  : selectedQuantity > 0
                    ? 'bg-gradient-to-br from-emerald-50 to-green-50 border-emerald-300 shadow-lg'
                    : 'bg-white border-slate-200 hover:border-slate-300 hover:shadow-md'
              }`}>
                <div className="flex justify-between items-start">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-3">
                      <h3 className="text-xl font-semibold text-slate-900">{ticketType.name}</h3>
                      {availabilityDisplay.isLowStock && (
                        <span className="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold bg-gradient-to-r from-orange-400 to-amber-400 text-white">
                          Low Stock
                        </span>
                      )}
                      {selectedQuantity > 0 && (
                        <span className="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold bg-gradient-to-r from-emerald-400 to-green-400 text-white">
                          {selectedQuantity} Selected
                        </span>
                      )}
                    </div>
                    {ticketType.description && (
                      <div className="mb-4 p-3 bg-slate-50 rounded-xl border border-slate-200">
                        <p className="text-sm text-slate-700 leading-relaxed whitespace-pre-line">
                          {expandedDescriptions.has(ticketType.id) 
                            ? ticketType.description 
                            : truncateDescription(ticketType.description)
                          }
                        </p>
                        {ticketType.description.length > 100 && (
                          <button
                            type="button"
                            onClick={() => toggleDescription(ticketType.id)}
                            className="mt-2 text-xs font-medium text-blue-600 hover:text-blue-800 transition-colors"
                          >
                            {expandedDescriptions.has(ticketType.id) ? 'Show less' : 'Show more'}
                          </button>
                        )}
                      </div>
                    )}
                    <div className="flex items-center justify-between">
                      <div>
                        <span className="text-2xl font-bold text-slate-900">
                          ${price.toFixed(2)}
                        </span>
                        <span className={`text-sm ml-3 font-medium ${availabilityDisplay.className}`}>
                          {availabilityDisplay.text}
                        </span>
                      </div>
                    </div>
                  </div>
                  <div className="ml-4">
                    <div className="flex items-center space-x-3">
                      <button
                        type="button"
                        onClick={() => handleQuantityChange(ticketType.id, Math.max(0, selectedQuantity - 1))}
                        disabled={selectedQuantity <= 0 || availabilityDisplay.isSoldOut}
                        className={`w-10 h-10 rounded-xl border-2 font-bold text-lg transition-all duration-200 ${
                          selectedQuantity <= 0 || availabilityDisplay.isSoldOut
                            ? 'border-slate-200 text-slate-300 cursor-not-allowed bg-slate-50'
                            : 'border-slate-300 text-slate-600 hover:border-red-400 hover:text-red-600 hover:bg-red-50 active:scale-95'
                        }`}
                      >
                        −
                      </button>
                      
                      <div className="w-12 text-center">
                        <span className="text-lg font-semibold text-slate-900">{selectedQuantity}</span>
                      </div>
                      
                      <button
                        type="button"
                        onClick={() => handleQuantityChange(ticketType.id, selectedQuantity + 1)}
                        disabled={selectedQuantity >= (avail?.available || 0) || availabilityDisplay.isSoldOut}
                        className={`w-10 h-10 rounded-xl border-2 font-bold text-lg transition-all duration-200 ${
                          selectedQuantity >= (avail?.available || 0) || availabilityDisplay.isSoldOut
                            ? 'border-slate-200 text-slate-300 cursor-not-allowed bg-slate-50'
                            : 'border-slate-300 text-slate-600 hover:border-green-400 hover:text-green-600 hover:bg-green-50 active:scale-95'
                        }`}
                      >
                        +
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        
        {/* Show message if no tickets available without presale code */}
        {event.ticket_types?.filter(tt => tt.is_active).length > 0 && 
         event.ticket_types?.filter(tt => tt.is_active)
           ?.filter(ticketType => {
             const avail = availability.get(ticketType.id);
             return avail ? shouldShowTicketType(avail, availabilitySettings) : true;
           })
           ?.filter(ticketType => {
             if (ticketType.requires_presale_code) {
               if (!presaleCodeValidated || !presaleCodeData) {
                 return false;
               }
               const hasAccess = presaleCodeData.accessible_ticket_types?.some(
                 (accessibleType: any) => accessibleType.id === ticketType.id
               );
               if (!hasAccess) {
                 return false;
               }
             }
             return true;
           }).length === 0 && (
          <div className="text-center py-6 bg-yellow-50 border border-yellow-200 rounded-lg">
            <div className="w-12 h-12 mx-auto text-yellow-400 mb-3">
              <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
              </svg>
            </div>
            <h3 className="text-lg font-medium text-yellow-900 mb-2">Presale Access Required</h3>
            <p className="text-yellow-700 text-sm">
              This event is currently in presale. Enter your presale code above to access tickets.
            </p>
          </div>
        )}
      </div>

      {/* Reservation Timer */}
      {currentReservations.size > 0 && (
        <div className="bg-gradient-to-r from-amber-50 to-yellow-50 border-2 border-amber-200 rounded-2xl p-4">
          <div className="flex items-center">
            <svg className="h-6 w-6 text-amber-500 mr-3" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z" clipRule="evenodd" />
            </svg>
            <span className="text-sm font-semibold text-amber-800">
              Tickets reserved for {timeRemaining}
            </span>
          </div>
        </div>
      )}

      {/* Order Summary */}
      {selectedTickets.size > 0 && (
        <div className="bg-gradient-to-br from-slate-50 to-white border-2 border-slate-200 rounded-2xl p-6 shadow-lg">
          <h3 className="text-xl font-semibold text-slate-900 mb-4 flex items-center">
            <div className="w-3 h-3 bg-gradient-to-r from-emerald-500 to-green-500 rounded-full mr-3"></div>
            Order Summary
          </h3>
          <div className="space-y-3 mb-4">
            {Array.from(selectedTickets.entries()).map(([ticketTypeId, ticket]) => (
              <div key={ticketTypeId} className="flex justify-between items-center p-3 bg-white rounded-xl border border-slate-200">
                <span className="font-medium text-slate-900">{ticket.quantity}x {ticket.name}</span>
                <span className="font-semibold text-slate-900">${((ticket.quantity * ticket.price) / 100).toFixed(2)}</span>
              </div>
            ))}
          </div>
          <div className="border-t-2 border-slate-200 pt-4">
            <div className="flex justify-between text-slate-600 mb-2">
              <span>Subtotal:</span>
              <span>${(totals.subtotal / 100).toFixed(2)}</span>
            </div>
            <div className="flex justify-between text-slate-600 mb-3">
              <span>Platform fee:</span>
              <span>${(totals.platformFee / 100).toFixed(2)}</span>
            </div>
            <div className="flex justify-between text-xl font-bold text-slate-900 pt-3 border-t border-slate-200">
              <span>Total:</span>
              <span>${(totals.total / 100).toFixed(2)}</span>
            </div>
          </div>
          
          {/* Customer Information - Only show when tickets are selected */}
          <form onSubmit={handleSubmit} className="mt-6 space-y-4">
            <div className="space-y-4">
              <div>
                <label htmlFor="email" className="block text-sm font-semibold text-slate-700 mb-2">
                  Email Address
                </label>
                <input
                  type="email"
                  id="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                  className="block w-full px-4 py-3 border-2 border-slate-200 rounded-xl shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200 text-slate-900 placeholder-slate-400 bg-white hover:border-slate-300"
                  placeholder="your@email.com"
                />
              </div>

              <div>
                <label htmlFor="name" className="block text-sm font-semibold text-slate-700 mb-2">
                  Full Name
                </label>
                <input
                  type="text"
                  id="name"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  required
                  className="block w-full px-4 py-3 border-2 border-slate-200 rounded-xl shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200 text-slate-900 placeholder-slate-400 bg-white hover:border-slate-300"
                  placeholder="Your Name"
                />
              </div>
            </div>

            <button
              type="submit"
              className="w-full py-4 px-6 rounded-2xl font-semibold text-lg transition-all duration-200 bg-gradient-to-r from-emerald-600 to-green-600 hover:from-emerald-700 hover:to-green-700 text-white shadow-xl hover:shadow-2xl transform hover:scale-[1.02]"
            >
              Complete Purchase
            </button>
          </form>
        </div>
      )}

      {/* Call to Action - Show when no tickets selected */}
      {selectedTickets.size === 0 && (
        <div className="text-center py-8 px-6 bg-gradient-to-br from-slate-50 to-slate-100 rounded-2xl border-2 border-dashed border-slate-300">
          <div className="w-16 h-16 mx-auto mb-4 bg-gradient-to-br from-slate-400 to-slate-500 rounded-full flex items-center justify-center">
            <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-slate-700 mb-2">Select Your Tickets</h3>
          <p className="text-slate-500">Choose your preferred seating and quantity above to continue</p>
        </div>
      )}

      <div className="mt-4 text-center">
        <p className="text-xs text-gray-500">
          Secure checkout powered by Stripe • Tickets reserved for 15 minutes
        </p>
      </div>
    </div>
  );
}