import React, { 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 SelectedTicket {
  quantity: number;
  price: number;
  name: string;
}

interface Reservation {
  id: string;
  ticketTypeId: string;
  quantity: number;
  expiresAt: Date;
}

interface PresaleCodeData {
  id: string;
  code: string;
  discount_percentage?: number;
  discount_fixed?: number;
  usage_limit?: number;
  usage_count?: number;
  accessible_ticket_types?: { id: string; name: string }[];
}

interface Props {
  event: EventData;
}

export default function TicketCheckout({ event }: Props) {
  const [selectedTickets, setSelectedTickets] = useState<Map<string, SelectedTicket>>(new Map());
  const [currentReservations, setCurrentReservations] = useState<Map<string, Reservation>>(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<PresaleCodeData | null>(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('Availability check error for ticket type:', 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]);

  // Cleanup effect - release reservations when component unmounts or on page unload
  useEffect(() => {
    const handleBeforeUnload = () => {
      // Release all active reservations
      currentReservations.forEach(async (reservation) => {
        try {
          await inventoryManager.releaseReservation(reservation.id);
        } catch (error) {
          console.error('Reservation release error during unload:', error);
          // Silently fail - page is unloading
        }
      });
    };

    window.addEventListener('beforeunload', handleBeforeUnload);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
      // Also release reservations on component unmount
      handleBeforeUnload();
    };
  }, [currentReservations]);

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

    try {
      // Release existing reservation if any
      if (currentReservations.has(ticketTypeId)) {
        const existingReservation = currentReservations.get(ticketTypeId);
        try {
          await inventoryManager.releaseReservation(existingReservation.id);
        } catch (releaseError) {
          console.error('Reservation release error:', releaseError);
          // Continue anyway - the reservation might have already expired
        }
        
        // Always remove from local state regardless of API result
        const newReservations = new Map(currentReservations);
        newReservations.delete(ticketTypeId);
        setCurrentReservations(newReservations);
      }

      if (newQuantity > 0) {
        // Reserve new tickets
        const reservation = await inventoryManager.reserveTickets(ticketTypeId, newQuantity, 15);
        
        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) {
      // If it's a reservation error, still update the UI but show a warning
      if (error.message && error.message.includes('Reservation not found')) {
        
        // Update selected tickets even if reservation failed
        if (newQuantity > 0) {
          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: null // No reservation ID if it failed
          });
          setSelectedTickets(newSelected);
        } else {
          const newSelected = new Map(selectedTickets);
          newSelected.delete(ticketTypeId);
          setSelectedTickets(newSelected);
        }
      } else {
        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.');
      
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Error processing purchase. Please try again.';
      alert(errorMessage);
    }
  };

  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('Presale code validation error:', 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" style={{color: 'var(--ui-text-secondary)'}}>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-4 sm:p-6 rounded-2xl backdrop-blur-lg" style={{background: 'linear-gradient(to bottom right, var(--glass-bg), var(--glass-bg-lg))', border: '2px solid var(--glass-border)'}}>
          <div className="flex flex-col sm:flex-row sm:items-end gap-3 sm:gap-4">
            <div className="flex-1">
              <label htmlFor="presale-code" className="block text-sm font-semibold mb-2" style={{color: 'var(--glass-text-accent)'}}>
                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 rounded-xl focus:ring-2 transition-all duration-200 backdrop-blur-lg"
                style={{
                  borderColor: 'var(--glass-border)',
                  focusRingColor: 'var(--glass-border-focus)',
                  focusBorderColor: 'var(--glass-border-focus)',
                  color: 'var(--ui-text-primary)',
                  background: 'var(--glass-bg-input)',
                  '::placeholder': { color: 'var(--glass-placeholder)' }
                }}
                onFocus={(e) => {
                  e.target.style.borderColor = 'var(--glass-border-focus)';
                  e.target.style.boxShadow = '0 0 0 2px var(--glass-border-focus-shadow)';
                }}
                onBlur={(e) => {
                  e.target.style.borderColor = 'var(--glass-border)';
                  e.target.style.boxShadow = 'none';
                }}
                onMouseEnter={(e) => (e.target as HTMLElement).style.borderColor = 'var(--glass-border-focus)'}
                onMouseLeave={(e) => e.target.style.borderColor = 'var(--glass-border)'}
              />
              {presaleCodeError && (
                <p className="text-sm mt-2 font-medium" style={{color: 'var(--error-color)'}}>{presaleCodeError}</p>
              )}
            </div>
            <button
              type="button"
              onClick={validatePresaleCode}
              className="w-full sm:w-auto px-6 py-3 rounded-xl font-semibold text-sm whitespace-nowrap transition-all duration-200 shadow-lg hover:shadow-xl touch-manipulation min-h-[44px]"
              style={{
                background: 'linear-gradient(to right, var(--glass-text-accent), var(--premium-gold))',
                color: 'var(--glass-text-primary)'
              }}
              onMouseEnter={(e) => {
                e.target.style.background = 'linear-gradient(to right, var(--glass-border-focus), var(--premium-gold-border))';
                e.target.style.transform = 'scale(1.02)';
              }}
              onMouseLeave={(e) => {
                e.target.style.background = 'linear-gradient(to right, var(--glass-text-accent), var(--premium-gold))';
                e.target.style.transform = 'scale(1)';
              }}
            >
              Apply Code
            </button>
          </div>
        </div>
      )}

      {/* Presale Code Success - Compact version */}
      {presaleCodeValidated && presaleCodeData && (
        <div className="mb-4 p-3 rounded-lg backdrop-blur-lg" style={{background: 'var(--success-bg)', border: '1px solid var(--success-border)'}}>
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <svg className="w-4 h-4" style={{color: 'var(--success-color)'}} 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" style={{color: 'var(--success-color)'}}>
                Presale access granted
              </span>
            </div>
            <button
              type="button"
              onClick={() => {
                setPresaleCodeValidated(false);
                setPresaleCodeData(null);
                setPresaleCode('');
              }}
              className="text-sm font-medium transition-colors"
              style={{color: 'var(--success-color)'}}
              onMouseEnter={(e) => (e.target as HTMLElement).style.color = 'var(--ui-text-primary)'}
              onMouseLeave={(e) => (e.target as HTMLElement).style.color = 'var(--success-color)'}
            >
              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: { id: string; name: string }) => 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: '', showExactCount: false, isLowStock: false, isSoldOut: false };
            
            return (
              <div 
                key={ticketType.id} 
                className="border-2 rounded-2xl p-4 sm:p-6 transition-all duration-200 backdrop-blur-lg"
                style={{
                  background: availabilityDisplay.isSoldOut 
                    ? 'var(--ui-bg-secondary)'
                    : selectedQuantity > 0
                      ? 'linear-gradient(to bottom right, var(--success-bg), var(--glass-bg-lg))'
                      : 'var(--ui-bg-elevated)',
                  borderColor: availabilityDisplay.isSoldOut 
                    ? 'var(--ui-border-secondary)'
                    : selectedQuantity > 0
                      ? 'var(--success-border)'
                      : 'var(--ui-border-primary)',
                  opacity: availabilityDisplay.isSoldOut ? 0.75 : 1,
                  boxShadow: selectedQuantity > 0 ? '0 10px 25px var(--ui-shadow)' : undefined
                }}
                onMouseEnter={(e) => {
                  if (!availabilityDisplay.isSoldOut && selectedQuantity === 0) {
                    e.target.style.borderColor = 'var(--glass-border-focus)';
                    e.target.style.boxShadow = '0 4px 12px var(--ui-shadow)'
                  }
                }}
                onMouseLeave={(e) => {
                  if (!availabilityDisplay.isSoldOut && selectedQuantity === 0) {
                    e.target.style.borderColor = 'var(--ui-border-primary)';
                    e.target.style.boxShadow = 'none';
                  }
                }}
              >
                <div className="flex flex-col sm:flex-row sm:justify-between sm:items-start gap-4">
                  <div className="flex-1">
                    <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 mb-3">
                      <h3 className="text-lg sm:text-xl font-semibold" style={{color: 'var(--ui-text-primary)'}}>{ticketType.name}</h3>
                      <div className="flex gap-2">
                        {availabilityDisplay.isLowStock && (
                          <span className="inline-flex items-center px-2 sm:px-3 py-1 rounded-full text-xs font-semibold" style={{background: 'linear-gradient(to right, var(--warning-color), var(--premium-gold))', color: 'var(--glass-text-primary)'}}>
                            Low Stock
                          </span>
                        )}
                        {selectedQuantity > 0 && (
                          <span className="inline-flex items-center px-2 sm:px-3 py-1 rounded-full text-xs font-semibold" style={{background: 'linear-gradient(to right, var(--success-color), var(--success-color))', color: 'var(--glass-text-primary)'}}>
                            {selectedQuantity} Selected
                          </span>
                        )}
                      </div>
                    </div>
                    {ticketType.description && (
                      <div className="mb-4 p-3 rounded-xl backdrop-blur-lg" style={{background: 'var(--ui-bg-secondary)', border: '1px solid var(--ui-border-secondary)'}}>
                        <p className="text-sm leading-relaxed whitespace-pre-line" style={{color: 'var(--ui-text-secondary)'}}>
                          {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 transition-colors"
                            style={{color: 'var(--glass-text-accent)'}}
                            onMouseEnter={(e) => (e.target as HTMLElement).style.color = 'var(--ui-text-primary)'}
                            onMouseLeave={(e) => e.target.style.color = 'var(--glass-text-accent)'}
                          >
                            {expandedDescriptions.has(ticketType.id) ? 'Show less' : 'Show more'}
                          </button>
                        )}
                      </div>
                    )}
                    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                      <div>
                        <span className="text-xl sm:text-2xl font-bold" style={{color: 'var(--ui-text-primary)'}}>
                          ${price.toFixed(2)}
                        </span>
                        <span className="text-sm block sm:inline sm:ml-3 font-medium" style={{color: availabilityDisplay.isSoldOut ? 'var(--error-color)' : availabilityDisplay.isLowStock ? 'var(--warning-color)' : 'var(--ui-text-secondary)'}}>
                          {availabilityDisplay.text}
                        </span>
                      </div>
                    </div>
                  </div>
                  <div className="flex-shrink-0">
                    <div className="flex items-center justify-center sm:justify-start space-x-3">
                      <button
                        type="button"
                        onClick={() => handleQuantityChange(ticketType.id, Math.max(0, selectedQuantity - 1))}
                        disabled={selectedQuantity <= 0 || availabilityDisplay.isSoldOut}
                        className="w-12 h-12 rounded-xl border-2 font-bold text-lg transition-all duration-200 touch-manipulation"
                        style={{
                          borderColor: selectedQuantity <= 0 || availabilityDisplay.isSoldOut 
                            ? 'var(--ui-border-secondary)' 
                            : 'var(--ui-border-primary)',
                          color: selectedQuantity <= 0 || availabilityDisplay.isSoldOut 
                            ? 'var(--ui-text-muted)' 
                            : 'var(--ui-text-secondary)',
                          background: selectedQuantity <= 0 || availabilityDisplay.isSoldOut 
                            ? 'var(--ui-bg-secondary)' 
                            : 'var(--ui-bg-elevated)',
                          cursor: selectedQuantity <= 0 || availabilityDisplay.isSoldOut ? 'not-allowed' : 'pointer'
                        }}
                        onMouseEnter={(e) => {
                          if (!(selectedQuantity <= 0 || availabilityDisplay.isSoldOut)) {
                            e.target.style.borderColor = 'var(--error-border)';
                            e.target.style.color = 'var(--error-color)';
                            e.target.style.background = 'var(--error-bg)';
                          }
                        }}
                        onMouseLeave={(e) => {
                          if (!(selectedQuantity <= 0 || availabilityDisplay.isSoldOut)) {
                            e.target.style.borderColor = 'var(--ui-border-primary)';
                            e.target.style.color = 'var(--ui-text-secondary)';
                            e.target.style.background = 'var(--ui-bg-elevated)';
                          }
                        }}
                      >
                        −
                      </button>
                      
                      <div className="w-12 text-center">
                        <span className="text-lg font-semibold" style={{color: 'var(--ui-text-primary)'}}>{selectedQuantity}</span>
                      </div>
                      
                      <button
                        type="button"
                        onClick={() => handleQuantityChange(ticketType.id, selectedQuantity + 1)}
                        disabled={selectedQuantity >= (avail?.available || 0) || availabilityDisplay.isSoldOut}
                        className="w-12 h-12 rounded-xl border-2 font-bold text-lg transition-all duration-200 touch-manipulation"
                        style={{
                          borderColor: selectedQuantity >= (avail?.available || 0) || availabilityDisplay.isSoldOut 
                            ? 'var(--ui-border-secondary)' 
                            : 'var(--ui-border-primary)',
                          color: selectedQuantity >= (avail?.available || 0) || availabilityDisplay.isSoldOut 
                            ? 'var(--ui-text-muted)' 
                            : 'var(--ui-text-secondary)',
                          background: selectedQuantity >= (avail?.available || 0) || availabilityDisplay.isSoldOut 
                            ? 'var(--ui-bg-secondary)' 
                            : 'var(--ui-bg-elevated)',
                          cursor: selectedQuantity >= (avail?.available || 0) || availabilityDisplay.isSoldOut ? 'not-allowed' : 'pointer'
                        }}
                        onMouseEnter={(e) => {
                          if (!(selectedQuantity >= (avail?.available || 0) || availabilityDisplay.isSoldOut)) {
                            e.target.style.borderColor = 'var(--success-border)';
                            e.target.style.color = 'var(--success-color)';
                            e.target.style.background = 'var(--success-bg)';
                          }
                        }}
                        onMouseLeave={(e) => {
                          if (!(selectedQuantity >= (avail?.available || 0) || availabilityDisplay.isSoldOut)) {
                            e.target.style.borderColor = 'var(--ui-border-primary)';
                            e.target.style.color = 'var(--ui-text-secondary)';
                            e.target.style.background = 'var(--ui-bg-elevated)';
                          }
                        }}
                      >
                        +
                      </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: { id: string; name: string }) => accessibleType.id === ticketType.id
               );
               if (!hasAccess) {
                 return false;
               }
             }
             return true;
           }).length === 0 && (
          <div className="text-center py-6 rounded-lg backdrop-blur-lg" style={{background: 'var(--warning-bg)', border: '1px solid var(--warning-border)'}}>
            <div className="w-12 h-12 mx-auto mb-3" style={{color: 'var(--warning-color)'}}>
              <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 mb-2" style={{color: 'var(--warning-color)'}}>Presale Access Required</h3>
            <p className="text-sm" style={{color: 'var(--ui-text-secondary)'}}>
              This event is currently in presale. Enter your presale code above to access tickets.
            </p>
          </div>
        )}
      </div>

      {/* Reservation Timer */}
      {currentReservations.size > 0 && (
        <div className="rounded-2xl p-4 backdrop-blur-lg" style={{background: 'linear-gradient(to right, var(--warning-bg), var(--premium-gold-bg))', border: '2px solid var(--warning-border)'}}>
          <div className="flex items-center">
            <svg className="h-6 w-6 mr-3" style={{color: 'var(--warning-color)'}} 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" style={{color: 'var(--warning-color)'}}>
              Tickets reserved for {timeRemaining}
            </span>
          </div>
        </div>
      )}

      {/* Order Summary */}
      {selectedTickets.size > 0 && (
        <div className="rounded-2xl p-4 sm:p-6 shadow-lg backdrop-blur-lg" style={{background: 'linear-gradient(to bottom right, var(--ui-bg-secondary), var(--ui-bg-elevated))', border: '2px solid var(--ui-border-primary)'}}>
          <h3 className="text-lg sm:text-xl font-semibold mb-4 flex items-center" style={{color: 'var(--ui-text-primary)'}}>
            <div className="w-3 h-3 rounded-full mr-3" style={{background: 'linear-gradient(to right, var(--success-color), var(--success-color))'}}></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 rounded-xl backdrop-blur-lg" style={{background: 'var(--ui-bg-elevated)', border: '1px solid var(--ui-border-secondary)'}}>
                <span className="font-medium truncate mr-2" style={{color: 'var(--ui-text-primary)'}}>{ticket.quantity}x {ticket.name}</span>
                <span className="font-semibold whitespace-nowrap" style={{color: 'var(--ui-text-primary)'}}>${((ticket.quantity * ticket.price) / 100).toFixed(2)}</span>
              </div>
            ))}
          </div>
          <div className="pt-4" style={{borderTop: '2px solid var(--ui-border-secondary)'}}>
            <div className="flex justify-between mb-2" style={{color: 'var(--ui-text-secondary)'}}>
              <span>Subtotal:</span>
              <span>${(totals.subtotal / 100).toFixed(2)}</span>
            </div>
            <div className="flex justify-between mb-3" style={{color: 'var(--ui-text-secondary)'}}>
              <span>Platform fee:</span>
              <span>${(totals.platformFee / 100).toFixed(2)}</span>
            </div>
            <div className="flex justify-between text-lg sm:text-xl font-bold pt-3" style={{color: 'var(--ui-text-primary)', borderTop: '1px solid var(--ui-border-secondary)'}}>
              <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-4 sm:mt-6 space-y-4">
            <div className="space-y-4">
              <div>
                <label htmlFor="email" className="block text-sm font-semibold mb-2" style={{color: 'var(--ui-text-secondary)'}}>
                  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 rounded-xl shadow-sm focus:ring-2 transition-all duration-200 backdrop-blur-lg"
                  style={{
                    borderColor: 'var(--ui-border-primary)',
                    background: 'var(--ui-bg-elevated)',
                    color: 'var(--ui-text-primary)',
                    '::placeholder': { color: 'var(--glass-placeholder)' }
                  }}
                  onFocus={(e) => {
                    e.target.style.borderColor = 'var(--glass-border-focus)';
                    e.target.style.boxShadow = '0 0 0 2px var(--glass-border-focus-shadow)';
                  }}
                  onBlur={(e) => {
                    e.target.style.borderColor = 'var(--ui-border-primary)';
                    e.target.style.boxShadow = 'none';
                  }}
                  onMouseEnter={(e) => (e.target as HTMLElement).style.borderColor = 'var(--glass-border-focus)'}
                  onMouseLeave={(e) => e.target.style.borderColor = 'var(--ui-border-primary)'}
                  placeholder="your@email.com"
                />
              </div>

              <div>
                <label htmlFor="name" className="block text-sm font-semibold mb-2" style={{color: 'var(--ui-text-secondary)'}}>
                  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 rounded-xl shadow-sm focus:ring-2 transition-all duration-200 backdrop-blur-lg"
                  style={{
                    borderColor: 'var(--ui-border-primary)',
                    background: 'var(--ui-bg-elevated)',
                    color: 'var(--ui-text-primary)',
                    '::placeholder': { color: 'var(--glass-placeholder)' }
                  }}
                  onFocus={(e) => {
                    e.target.style.borderColor = 'var(--glass-border-focus)';
                    e.target.style.boxShadow = '0 0 0 2px var(--glass-border-focus-shadow)';
                  }}
                  onBlur={(e) => {
                    e.target.style.borderColor = 'var(--ui-border-primary)';
                    e.target.style.boxShadow = 'none';
                  }}
                  onMouseEnter={(e) => (e.target as HTMLElement).style.borderColor = 'var(--glass-border-focus)'}
                  onMouseLeave={(e) => e.target.style.borderColor = 'var(--ui-border-primary)'}
                  placeholder="Your Name"
                />
              </div>
            </div>

            <button
              type="submit"
              className="w-full py-4 px-6 rounded-2xl font-semibold text-base sm:text-lg transition-all duration-200 shadow-xl hover:shadow-2xl transform hover:scale-[1.02] touch-manipulation min-h-[44px]"
              style={{
                background: 'linear-gradient(to right, var(--success-color), var(--success-color))',
                color: 'var(--glass-text-primary)'
              }}
              onMouseEnter={(e) => {
                e.target.style.background = 'linear-gradient(to right, var(--success-color), var(--success-border))';
                e.target.style.transform = 'scale(1.02)';
              }}
              onMouseLeave={(e) => {
                e.target.style.background = 'linear-gradient(to right, var(--success-color), var(--success-color))';
                e.target.style.transform = 'scale(1)';
              }}
            >
              Complete Purchase
            </button>
          </form>
        </div>
      )}

      {/* Call to Action - Show when no tickets selected */}
      {selectedTickets.size === 0 && (
        <div className="text-center py-8 px-6 rounded-2xl border-2 border-dashed backdrop-blur-lg" style={{background: 'linear-gradient(to bottom right, var(--ui-bg-secondary), var(--ui-bg-elevated))', borderColor: 'var(--ui-border-primary)'}}>
          <div className="w-16 h-16 mx-auto mb-4 rounded-full flex items-center justify-center" style={{background: 'linear-gradient(to bottom right, var(--ui-text-muted), var(--ui-text-secondary))'}}>
            <svg className="w-8 h-8" style={{color: 'var(--glass-text-primary)'}} 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 mb-2" style={{color: 'var(--ui-text-secondary)'}}>Select Your Tickets</h3>
          <p style={{color: 'var(--ui-text-tertiary)'}}>Choose your preferred seating and quantity above to continue</p>
        </div>
      )}

      <div className="mt-4 text-center">
        <p className="text-xs" style={{color: 'var(--ui-text-tertiary)'}}>
          Secure checkout powered by Stripe • Tickets reserved for 15 minutes
        </p>
      </div>
    </div>
  );
}