---
export const prerender = false;
import Layout from '../../layouts/Layout.astro';
---

<Layout title="Sales Kiosk - Black Canyon Tickets">
  <script src="https://js.stripe.com/v3/"></script>
  <style>
    .bg-grid-pattern {
      background-image: 
        linear-gradient(rgba(255, 255, 255, 0.1) 1px, transparent 1px),
        linear-gradient(90deg, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
      background-size: 20px 20px;
    }
    
    .payment-method-option input:checked + .payment-method-card {
      border-color: rgb(59, 130, 246);
      background-color: rgba(59, 130, 246, 0.2);
    }
    
    /* Desktop layout */
    @media (min-width: 1024px) {
      .kiosk-container {
        height: 100vh;
        overflow: hidden;
      }
      
      .kiosk-content {
        height: 100vh;
        display: flex;
        flex-direction: column;
      }
      
      .kiosk-main {
        flex: 1;
        overflow: hidden;
        display: flex;
        gap: 2rem;
        padding: 1rem;
      }
      
      .ticket-types-section {
        flex: 1;
        overflow-y: auto;
      }
      
      .cart-section {
        width: 400px;
        flex-shrink: 0;
        overflow-y: auto;
      }
    }
    
    /* Mobile layout */
    @media (max-width: 1023px) {
      .kiosk-container {
        min-height: 100vh;
      }
      
      .kiosk-content {
        min-height: 100vh;
      }
      
      .kiosk-main {
        display: block;
        padding: 1rem;
      }
      
      .ticket-types-section {
        margin-bottom: 2rem;
      }
      
      .cart-section {
        width: 100%;
        position: sticky;
        bottom: 0;
        z-index: 10;
      }
    }
  </style>
  
  <div class="kiosk-container bg-gradient-to-br from-indigo-900 via-purple-900 to-slate-900">
    <!-- Animated background elements -->
    <div class="fixed inset-0 overflow-hidden pointer-events-none">
      <div class="absolute -top-40 -right-40 w-80 h-80 bg-gradient-to-br from-purple-600/20 to-pink-600/20 rounded-full blur-3xl animate-pulse"></div>
      <div class="absolute -bottom-40 -left-40 w-80 h-80 bg-gradient-to-br from-blue-600/20 to-cyan-600/20 rounded-full blur-3xl animate-pulse"></div>
      <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-96 h-96 bg-gradient-to-br from-indigo-600/10 to-purple-600/10 rounded-full blur-3xl animate-pulse"></div>
    </div>
    
    <!-- Grid pattern overlay -->
    <div class="absolute inset-0 bg-grid-pattern opacity-5"></div>
    
    <!-- PIN Entry Modal -->
    <div id="pin-entry-modal" class="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center">
      <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-3xl shadow-2xl max-w-md w-full mx-4">
        <!-- Modal Header -->
        <div class="text-center p-8 border-b border-white/20">
          <div class="w-20 h-20 bg-gradient-to-br from-blue-500/20 to-purple-500/20 rounded-full flex items-center justify-center mx-auto mb-6 border border-white/20">
            <svg class="w-10 h-10 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="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>
          <h2 class="text-2xl font-bold text-white mb-2">Sales Kiosk Access</h2>
          <p class="text-white/80 text-lg">Enter 4-digit PIN to access sales interface</p>
        </div>
        
        <!-- Modal Content -->
        <div class="p-8">
          <form id="pin-entry-form" class="space-y-6">
            <div>
              <label for="kiosk-pin-input" class="block text-lg font-medium text-white/90 mb-3">4-digit PIN</label>
              <input
                type="password"
                id="kiosk-pin-input"
                maxlength="4"
                pattern="[0-9]{4}"
                class="w-full px-6 py-4 bg-white/10 border border-white/30 rounded-2xl text-white text-center text-2xl font-mono placeholder-white/60 focus:ring-2 focus:ring-blue-400 focus:border-blue-400 transition-all duration-200"
                placeholder="••••"
                required
                autofocus
              />
            </div>
            
            <div id="pin-error" class="hidden bg-red-500/10 border border-red-400/30 rounded-xl p-4">
              <p class="text-red-200 text-center">
                <strong>Invalid PIN.</strong> Please try again.
              </p>
            </div>
            
            <button
              type="submit"
              id="pin-submit-btn"
              class="w-full bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white px-8 py-4 rounded-2xl font-bold text-xl transition-all duration-300 shadow-2xl hover:shadow-blue-500/25 hover:scale-105"
            >
              Access Kiosk
            </button>
          </form>
        </div>
      </div>
    </div>

    <!-- Credit Card Payment Modal -->
    <div id="credit-card-modal" class="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center hidden">
      <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-3xl shadow-2xl max-w-md w-full mx-4">
        <!-- Modal Header -->
        <div class="text-center p-6 border-b border-white/20">
          <div class="w-16 h-16 bg-gradient-to-br from-blue-500/20 to-purple-500/20 rounded-full flex items-center justify-center mx-auto mb-4 border border-white/20">
            <svg class="w-8 h-8 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
            </svg>
          </div>
          <h2 class="text-2xl font-bold text-white mb-2">Credit Card Payment</h2>
          <p class="text-white/80 text-lg">Total: <span id="payment-total">$0.00</span></p>
        </div>
        
        <!-- Payment Form -->
        <div class="p-6">
          <form id="payment-form">
            <div class="mb-4">
              <label class="block text-white text-sm font-medium mb-2">Card Information</label>
              <div id="card-element" class="bg-white/10 border border-white/20 rounded-lg p-4 min-h-[50px]">
                <!-- Stripe Elements will create form elements here -->
              </div>
              <div id="card-errors" class="text-red-400 text-sm mt-2 hidden"></div>
            </div>
            
            <div class="flex gap-4">
              <button
                type="button"
                id="cancel-payment-btn"
                class="flex-1 bg-white/10 hover:bg-white/20 text-white px-6 py-3 rounded-lg font-medium transition-all duration-200 border border-white/30"
              >
                Cancel
              </button>
              <button
                type="submit"
                id="submit-payment-btn"
                class="flex-1 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white px-6 py-3 rounded-lg font-medium transition-all duration-200 disabled:opacity-50"
                disabled
              >
                <span id="button-text">Pay Now</span>
                <div id="spinner" class="hidden">
                  <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                </div>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- Kiosk Interface (Hidden until PIN is entered) -->
    <div id="kiosk-interface" class="hidden kiosk-content">
      <!-- Kiosk Header -->
      <div class="bg-black/20 backdrop-blur-xl shadow-2xl border-b border-white/10 z-40">
        <div class="max-w-6xl mx-auto px-6 py-4">
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-4">
              <div class="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-500 rounded-xl flex items-center justify-center">
                <svg class="w-7 h-7 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
              </div>
              <div>
                <h1 class="text-2xl font-bold text-white">Sales Kiosk</h1>
                <p class="text-white/80" id="event-title-header">Loading event...</p>
              </div>
            </div>
            
            <div class="flex items-center gap-4">
              <button
                id="lock-kiosk-btn"
                class="bg-gradient-to-r from-amber-600 to-orange-600 hover:from-amber-700 hover:to-orange-700 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 flex items-center gap-2"
              >
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="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>
                Lock Kiosk
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Main Kiosk Content -->
      <main class="kiosk-main relative max-w-6xl mx-auto">
        <!-- Left Column: Event Info & Ticket Selection -->
        <div class="ticket-types-section">
          <!-- Event Info Card -->
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-3xl shadow-2xl mb-6 overflow-hidden">
            <div class="px-6 py-6 text-white">
              <div class="text-center">
                <h2 id="event-title" class="text-2xl font-bold mb-3 bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">Loading...</h2>
                <div class="flex items-center justify-center space-x-6 text-white/80 text-sm">
                  <div class="flex items-center space-x-2">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"></path>
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"></path>
                    </svg>
                    <span id="event-venue">--</span>
                  </div>
                  <div class="flex items-center space-x-2">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                    </svg>
                    <span id="event-date">--</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Ticket Selection -->
          <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-3xl shadow-2xl">
            <div class="px-6 py-6">
              <div class="flex items-center justify-between mb-4">
                <h3 class="text-xl font-bold text-white">Select Tickets</h3>
                <div class="flex items-center gap-2">
                  <label class="text-white text-sm">Filter:</label>
                  <select id="ticket-filter" class="bg-white/10 border border-white/20 rounded-lg px-3 py-1 text-white text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    <option value="all">All Tickets</option>
                    <option value="available">Available Only</option>
                    <option value="low-stock">Low Stock</option>
                  </select>
                </div>
              </div>
              <div id="ticket-types" class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                <!-- Ticket types will be loaded here -->
              </div>
            </div>
          </div>
        </div>

        <!-- Right Column: Cart Summary -->
        <div id="cart-summary" class="cart-section bg-white/10 backdrop-blur-xl border border-white/20 rounded-3xl shadow-2xl hidden">
          <div class="px-8 py-8">
            <h3 class="text-2xl font-bold text-white mb-6 text-center">Your Order</h3>
            <div id="cart-items" class="space-y-4 mb-6">
              <!-- Cart items will be displayed here -->
            </div>
            <div class="border-t border-white/20 pt-6">
              <div class="flex justify-between items-center text-white mb-6">
                <span class="text-xl font-semibold">Total:</span>
                <span id="cart-total" class="text-3xl font-bold">$0.00</span>
              </div>
              
              <!-- Payment Method Selection -->
              <div class="mb-6">
                <h4 class="text-lg font-semibold text-white mb-3">Payment Method</h4>
                <div class="grid grid-cols-2 gap-3">
                  <label class="payment-method-option">
                    <input type="radio" name="payment-method" value="cash" checked class="sr-only">
                    <div class="payment-method-card bg-white/10 hover:bg-white/20 border-2 border-white/30 rounded-xl p-3 cursor-pointer transition-all duration-200 text-center">
                      <div class="flex flex-col items-center">
                        <svg class="w-6 h-6 text-green-400 mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" />
                        </svg>
                        <span class="text-white font-medium text-sm">Cash</span>
                      </div>
                    </div>
                  </label>
                  
                  <label class="payment-method-option">
                    <input type="radio" name="payment-method" value="card" class="sr-only">
                    <div class="payment-method-card bg-white/10 hover:bg-white/20 border-2 border-white/30 rounded-xl p-3 cursor-pointer transition-all duration-200 text-center">
                      <div class="flex flex-col items-center">
                        <svg class="w-6 h-6 text-blue-400 mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
                        </svg>
                        <span class="text-white font-medium text-sm">Credit Card</span>
                      </div>
                    </div>
                  </label>
                </div>
              </div>
              
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <button
                  id="clear-cart-btn"
                  class="bg-white/10 hover:bg-white/20 text-white px-8 py-4 rounded-2xl font-medium transition-all duration-200 border border-white/30"
                >
                  Clear Cart
                </button>
                <button
                  id="proceed-checkout-btn"
                  class="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white px-8 py-6 rounded-2xl font-bold text-xl transition-all duration-300 shadow-2xl hover:shadow-blue-500/25 hover:scale-105 border border-white/20 min-h-[80px] flex items-center justify-center"
                >
                  Proceed to Checkout
                </button>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</Layout>

<script>
  import { supabase } from '../../lib/supabase';
  import { inventoryManager } from '../../lib/inventory';
  
  // Get slug from URL
  const pathSegments = window.location.pathname.split('/');
  const eventSlug = pathSegments[pathSegments.length - 1];
  
  // PIN management
  let kioskPin = null;
  let eventData = null;
  let ticketTypes = [];
  let cart = [];
  let activeReservations = new Map(); // Track active reservations for cart items
  
  // Elements
  const pinEntryModal = document.getElementById('pin-entry-modal');
  const kioskInterface = document.getElementById('kiosk-interface');
  const pinEntryForm = document.getElementById('pin-entry-form');
  const kioskPinInput = document.getElementById('kiosk-pin-input');
  const pinError = document.getElementById('pin-error');
  const lockKioskBtn = document.getElementById('lock-kiosk-btn');
  const ticketFilter = document.getElementById('ticket-filter');
  
  // Event info elements
  const eventTitle = document.getElementById('event-title');
  const eventTitleHeader = document.getElementById('event-title-header');
  const eventVenue = document.getElementById('event-venue');
  const eventDate = document.getElementById('event-date');
  
  // Cart elements
  const ticketTypesContainer = document.getElementById('ticket-types');
  const cartSummary = document.getElementById('cart-summary');
  const cartItems = document.getElementById('cart-items');
  const cartTotal = document.getElementById('cart-total');
  const clearCartBtn = document.getElementById('clear-cart-btn');
  const proceedCheckoutBtn = document.getElementById('proceed-checkout-btn');
  
  // Payment method selection
  const paymentMethodOptions = document.querySelectorAll('input[name="payment-method"]');
  let selectedPaymentMethod = 'cash'; // Default to cash
  
  // Credit card payment elements
  const creditCardModal = document.getElementById('credit-card-modal');
  const paymentForm = document.getElementById('payment-form');
  const paymentTotal = document.getElementById('payment-total');
  const cancelPaymentBtn = document.getElementById('cancel-payment-btn');
  const submitPaymentBtn = document.getElementById('submit-payment-btn');
  const buttonText = document.getElementById('button-text');
  const spinner = document.getElementById('spinner');
  const cardErrors = document.getElementById('card-errors');
  
  // Stripe integration
  let stripe = null;
  let elements = null;
  let cardElement = null;
  let currentPaymentIntent = null;
  
  // Initialize kiosk
  document.addEventListener('DOMContentLoaded', async () => {
    await loadEventData();
    
    // Initialize Stripe
    initializeStripe();
    
    // Check if kiosk is already unlocked for this event
    const savedPin = localStorage.getItem('kioskPin');
    const savedEventId = localStorage.getItem('kioskEventId');
    
    if (savedPin && savedEventId && eventData && savedEventId === eventData.id) {
      // Verify the stored PIN is still valid
      try {
        const response = await fetch('/api/kiosk/verify-pin', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            eventSlug: eventSlug,
            pin: savedPin
          })
        });

        const result = await response.json();

        if (response.ok && result.success) {
          kioskPin = savedPin;
          showKioskInterface();
        } else {
          // PIN is no longer valid, clear storage
          localStorage.removeItem('kioskPin');
          localStorage.removeItem('kioskEventId');
        }
      } catch (error) {
        console.error('Error verifying stored PIN:', error);
        localStorage.removeItem('kioskPin');
        localStorage.removeItem('kioskEventId');
      }
    }
  });
  
  // Load event data
  async function loadEventData() {
    try {
      const { data: event, error } = await supabase
        .from('events')
        .select(`
          *,
          ticket_types (
            id,
            name,
            price,
            quantity_available,
            quantity_sold,
            description
          )
        `)
        .eq('slug', eventSlug)
        .single();
      
      if (error) throw error;
      
      eventData = event;
      ticketTypes = event.ticket_types || [];
      
      // Update event info
      eventTitle.textContent = event.title;
      eventTitleHeader.textContent = event.title;
      eventVenue.textContent = event.venue;
      eventDate.textContent = new Date(event.start_time).toLocaleDateString('en-US', {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: 'numeric',
        minute: '2-digit'
      });
      
    } catch (error) {
      console.error('Error loading event data:', error);
      alert('Failed to load event data. Please try again.');
    }
  }
  
  
  // Show kiosk interface
  function showKioskInterface() {
    pinEntryModal.classList.add('hidden');
    kioskInterface.classList.remove('hidden');
    loadTicketTypes();
  }

  // Initialize Stripe
  function initializeStripe() {
    if (typeof Stripe !== 'undefined') {
      stripe = Stripe(import.meta.env.PUBLIC_STRIPE_PUBLISHABLE_KEY);
      elements = stripe.elements();
      
      // Create card element
      cardElement = elements.create('card', {
        style: {
          base: {
            fontSize: '16px',
            color: '#ffffff',
            '::placeholder': {
              color: '#9ca3af',
            },
          },
        },
      });
      
      // Mount card element
      cardElement.mount('#card-element');
      
      // Handle card validation
      cardElement.addEventListener('change', (event) => {
        const displayError = document.getElementById('card-errors');
        if (event.error) {
          displayError.textContent = event.error.message;
          displayError.classList.remove('hidden');
          submitPaymentBtn.disabled = true;
        } else {
          displayError.classList.add('hidden');
          submitPaymentBtn.disabled = false;
        }
      });
    }
  }
  
  // Load ticket types with filtering
  function loadTicketTypes() {
    ticketTypesContainer.innerHTML = '';
    
    const filterValue = ticketFilter.value;
    let filteredTicketTypes = ticketTypes;
    
    // Apply filter
    if (filterValue === 'available') {
      filteredTicketTypes = ticketTypes.filter(ticketType => {
        const available = ticketType.quantity_available - (ticketType.quantity_sold || 0);
        return available > 0;
      });
    } else if (filterValue === 'low-stock') {
      filteredTicketTypes = ticketTypes.filter(ticketType => {
        const available = ticketType.quantity_available - (ticketType.quantity_sold || 0);
        return available > 0 && available <= 10; // Less than or equal to 10 tickets
      });
    }
    
    filteredTicketTypes.forEach(ticketType => {
      const available = ticketType.quantity_available - (ticketType.quantity_sold || 0);
      
      const ticketCard = document.createElement('div');
      ticketCard.className = 'bg-white/10 border border-white/20 rounded-2xl p-6 hover:bg-white/20 transition-all duration-200';
      ticketCard.innerHTML = `
        <div class="text-center">
          <h4 class="text-xl font-bold text-white mb-2">${ticketType.name}</h4>
          <p class="text-white/80 text-sm mb-4">${ticketType.description || 'General admission'}</p>
          <div class="text-3xl font-bold text-blue-400 mb-4">$${(ticketType.price / 100).toFixed(2)}</div>
          <p class="text-white/60 text-sm mb-6">${available} available</p>
          <div class="flex items-center justify-center gap-4">
            <button 
              class="bg-white/10 hover:bg-white/20 text-white w-12 h-12 rounded-xl font-bold text-xl transition-all duration-200 ${available <= 0 ? 'opacity-50 cursor-not-allowed' : ''}"
              onclick="updateCart('${ticketType.id}', -1)"
              ${available <= 0 ? 'disabled' : ''}
            >
              -
            </button>
            <span class="text-white font-bold text-xl w-12 text-center" id="quantity-${ticketType.id}">0</span>
            <button 
              class="bg-white/10 hover:bg-white/20 text-white w-12 h-12 rounded-xl font-bold text-xl transition-all duration-200 ${available <= 0 ? 'opacity-50 cursor-not-allowed' : ''}"
              onclick="updateCart('${ticketType.id}', 1)"
              ${available <= 0 ? 'disabled' : ''}
            >
              +
            </button>
          </div>
        </div>
      `;
      
      ticketTypesContainer.appendChild(ticketCard);
    });
  }
  
  // Update cart
  window.updateCart = async function(ticketTypeId, change) {
    const ticketType = ticketTypes.find(t => t.id === ticketTypeId);
    if (!ticketType) return;
    
    const available = ticketType.quantity_available - (ticketType.quantity_sold || 0);
    const existingItem = cart.find(item => item.ticketTypeId === ticketTypeId);
    
    if (existingItem) {
      const newQuantity = existingItem.quantity + change;
      
      if (newQuantity <= 0) {
        // Remove item and release reservation
        const reservationId = activeReservations.get(ticketTypeId);
        if (reservationId) {
          try {
            await inventoryManager.releaseReservation(reservationId);
            activeReservations.delete(ticketTypeId);
          } catch (error) {
            console.error('Error releasing reservation:', error);
          }
        }
        cart = cart.filter(item => item.ticketTypeId !== ticketTypeId);
      } else if (newQuantity <= available) {
        // Update existing reservation
        try {
          const reservationId = activeReservations.get(ticketTypeId);
          if (reservationId) {
            await inventoryManager.releaseReservation(reservationId);
          }
          
          const reservation = await inventoryManager.reserveTickets(ticketTypeId, newQuantity, 15); // 15 minute hold
          activeReservations.set(ticketTypeId, reservation.id);
          existingItem.quantity = newQuantity;
        } catch (error) {
          console.error('Error updating reservation:', error);
          alert('Unable to reserve tickets. Please try again.');
          return;
        }
      } else {
        alert(`Only ${available} tickets available for ${ticketType.name}`);
        return;
      }
    } else if (change > 0 && change <= available) {
      try {
        // Reserve tickets before adding to cart
        const reservation = await inventoryManager.reserveTickets(ticketTypeId, change, 15); // 15 minute hold
        activeReservations.set(ticketTypeId, reservation.id);
        
        cart.push({
          ticketTypeId,
          name: ticketType.name,
          price: ticketType.price,
          quantity: change
        });
      } catch (error) {
        console.error('Error reserving tickets:', error);
        alert('Unable to reserve tickets. Please try again.');
        return;
      }
    }
    
    updateCartDisplay();
  };
  
  // Update cart display
  function updateCartDisplay() {
    // Update quantity displays
    ticketTypes.forEach(ticketType => {
      const quantitySpan = document.getElementById(`quantity-${ticketType.id}`);
      const cartItem = cart.find(item => item.ticketTypeId === ticketType.id);
      if (quantitySpan) {
        quantitySpan.textContent = cartItem ? cartItem.quantity : 0;
      }
    });
    
    // Update cart summary
    if (cart.length === 0) {
      cartSummary.classList.add('hidden');
    } else {
      cartSummary.classList.remove('hidden');
      
      cartItems.innerHTML = '';
      let total = 0;
      
      cart.forEach(item => {
        const itemTotal = item.price * item.quantity;
        total += itemTotal;
        
        const cartItem = document.createElement('div');
        cartItem.className = 'flex justify-between items-center p-4 bg-white/10 rounded-xl';
        cartItem.innerHTML = `
          <div>
            <span class="text-white font-medium">${item.name}</span>
            <span class="text-white/60 ml-2">x${item.quantity}</span>
          </div>
          <span class="text-white font-bold">$${(itemTotal / 100).toFixed(2)}</span>
        `;
        
        cartItems.appendChild(cartItem);
      });
      
      cartTotal.textContent = `$${(total / 100).toFixed(2)}`;
    }
  }
  
  // Payment method selection
  paymentMethodOptions.forEach(option => {
    option.addEventListener('change', (e) => {
      selectedPaymentMethod = e.target.value;
      console.log('Payment method selected:', selectedPaymentMethod);
    });
  });
  
  // Ticket type filtering
  ticketFilter?.addEventListener('change', () => {
    loadTicketTypes();
  });
  
  // Clear cart
  clearCartBtn?.addEventListener('click', async () => {
    // Release all reservations
    for (const [ticketTypeId, reservationId] of activeReservations) {
      try {
        await inventoryManager.releaseReservation(reservationId);
      } catch (error) {
        console.error('Error releasing reservation:', error);
      }
    }
    
    activeReservations.clear();
    cart = [];
    updateCartDisplay();
  });
  
  // Proceed to checkout
  proceedCheckoutBtn?.addEventListener('click', async () => {
    if (cart.length === 0) {
      alert('Please add tickets to your cart first.');
      return;
    }

    // Show confirmation dialog
    const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
    const formattedTotal = new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD'
    }).format(total / 100);

    const totalTickets = cart.reduce((sum, item) => sum + item.quantity, 0);
    const paymentMethodText = selectedPaymentMethod === 'cash' ? 'cash payment' : 'credit card payment';
    const confirmMessage = `Confirm Sale\n\nTotal: ${formattedTotal}\nTickets needed: ${totalTickets}\nPayment method: ${selectedPaymentMethod.toUpperCase()}\n\nYou will need to provide ${totalTickets} printed tickets from your inventory.\n\nProceed with ${paymentMethodText}?`;
    
    if (!confirm(confirmMessage)) {
      return;
    }

    // Show processing state
    const originalText = proceedCheckoutBtn.textContent;
    proceedCheckoutBtn.textContent = 'Processing...';
    proceedCheckoutBtn.disabled = true;

    try {
      // Get session token
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) {
        throw new Error('Not authenticated');
      }

      // Process purchase
      const response = await fetch('/api/kiosk/purchase', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${session.access_token}`
        },
        body: JSON.stringify({
          eventId: eventData.id,
          cart: cart,
          paymentMethod: selectedPaymentMethod,
          reservationIds: Array.from(activeReservations.values())
        })
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || 'Purchase failed');
      }

      // Show success message with instructions
      let successMessage = `Sale Recorded!\n\n`;
      successMessage += `Batch: ${result.purchase.batchNumber}\n`;
      successMessage += `Total: ${formattedTotal}\n`;
      successMessage += `Payment: ${selectedPaymentMethod.toUpperCase()}\n`;
      successMessage += `Tickets sold: ${result.purchase.ticketsCreated.length}\n\n`;
      successMessage += `Instructions:\n`;
      result.purchase.instructions.forEach((instruction, index) => {
        successMessage += `${index + 1}. ${instruction}\n`;
      });

      alert(successMessage);

      // Clear cart and reservations and reload ticket types to reflect new inventory
      activeReservations.clear();
      cart = [];
      updateCartDisplay();
      await loadEventData();

    } catch (error) {
      console.error('Purchase error:', error);
      alert('Sale failed: ' + error.message);
    } finally {
      // Restore button
      proceedCheckoutBtn.textContent = originalText;
      proceedCheckoutBtn.disabled = false;
    }
  });
  
  // PIN entry form
  pinEntryForm?.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const enteredPin = kioskPinInput.value.trim();
    
    if (!/^\d{4}$/.test(enteredPin)) {
      pinError.classList.remove('hidden');
      pinError.querySelector('p').innerHTML = '<strong>Invalid format.</strong> PIN must be exactly 4 digits.';
      return;
    }
    
    try {
      // Show loading state
      const submitBtn = document.getElementById('pin-submit-btn');
      const originalText = submitBtn.innerHTML;
      submitBtn.innerHTML = '<svg class="w-5 h-5 animate-spin mx-auto" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>';
      submitBtn.disabled = true;

      // Verify PIN with backend
      const response = await fetch('/api/kiosk/verify-pin', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          eventSlug: eventSlug,
          pin: enteredPin
        })
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || 'PIN verification failed');
      }

      if (result.success) {
        // Store successful PIN for this session
        localStorage.setItem('kioskPin', enteredPin);
        localStorage.setItem('kioskEventId', result.event.id);
        
        kioskPin = enteredPin;
        pinError.classList.add('hidden');
        showKioskInterface();
      } else {
        throw new Error('Invalid PIN');
      }

    } catch (error) {
      console.error('PIN verification error:', error);
      pinError.classList.remove('hidden');
      
      // Show specific error message
      let errorMessage = '<strong>Invalid PIN.</strong> Please try again.';
      if (error.message.includes('expired')) {
        errorMessage = '<strong>PIN expired.</strong> Please request a new PIN from the event organizer.';
      } else if (error.message.includes('No PIN set')) {
        errorMessage = '<strong>No PIN set.</strong> Please contact the event organizer to generate a PIN.';
      } else if (error.message.includes('Event not found')) {
        errorMessage = '<strong>Event not found.</strong> Please check the URL.';
      }
      
      pinError.querySelector('p').innerHTML = errorMessage;
      kioskPinInput.value = '';
      
    } finally {
      // Restore button
      const submitBtn = document.getElementById('pin-submit-btn');
      submitBtn.innerHTML = originalText;
      submitBtn.disabled = false;
    }
  });
  
  // Lock kiosk
  lockKioskBtn?.addEventListener('click', async () => {
    localStorage.removeItem('kioskPin');
    localStorage.removeItem('kioskEventId');
    kioskPin = null;
    
    // Release all reservations
    for (const [ticketTypeId, reservationId] of activeReservations) {
      try {
        await inventoryManager.releaseReservation(reservationId);
      } catch (error) {
        console.error('Error releasing reservation:', error);
      }
    }
    
    // Clear cart and UI
    activeReservations.clear();
    cart = [];
    updateCartDisplay();
    kioskInterface.classList.add('hidden');
    pinEntryModal.classList.remove('hidden');
    kioskPinInput.value = '';
    pinError.classList.add('hidden');
  });
  
  // Auto-format PIN input
  kioskPinInput?.addEventListener('input', (e) => {
    e.target.value = e.target.value.replace(/[^0-9]/g, '').slice(0, 4);
  });
  
  // Prevent navigation when kiosk is active
  window.addEventListener('beforeunload', (e) => {
    if (!kioskInterface.classList.contains('hidden')) {
      e.preventDefault();
      e.returnValue = '';
    }
  });
</script>