---
export const prerender = false;

import Layout from '../../../layouts/Layout.astro';
import Navigation from '../../../components/Navigation.astro';
---

<Layout title="Event Management - Black Canyon Tickets">
  <div class="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100">
    <Navigation 
      title="Event Management" 
      showBackLink={true} 
      backLinkUrl="/dashboard" 
      backLinkText="← All Events" 
    />

    <main class="max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
      <!-- Event Header -->
      <div class="bg-gradient-to-r from-slate-800 to-slate-900 rounded-3xl shadow-2xl mb-8 overflow-hidden">
        <div class="px-8 py-12 text-white">
          <div class="flex justify-between items-start">
            <div class="flex-1">
              <h1 id="event-title" class="text-4xl font-light mb-3 tracking-wide">Loading...</h1>
              <div class="flex items-center space-x-6 text-slate-200 mb-4">
                <div class="flex items-center space-x-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="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-5 h-5" 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>
              <p id="event-description" class="text-slate-300 max-w-2xl leading-relaxed">Loading event details...</p>
            </div>
            <div class="flex flex-col items-end space-y-3">
              <div class="flex space-x-3">
                <a
                  id="preview-link"
                  href="#"
                  target="_blank"
                  class="bg-white/10 hover:bg-white/20 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 backdrop-blur-sm"
                >
                  Preview Page
                </a>
                <button
                  id="edit-event-btn"
                  class="bg-white/90 hover:bg-white text-slate-900 px-6 py-3 rounded-xl font-medium transition-all duration-200"
                >
                  Edit Event
                </button>
              </div>
              <div class="text-right">
                <div class="text-3xl font-semibold" id="total-revenue">$0</div>
                <div class="text-sm text-slate-300">Total Revenue</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Quick Stats -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-white rounded-2xl p-6 shadow-lg border border-slate-200/50">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-semibold text-slate-600 uppercase tracking-wide">Tickets Sold</p>
              <p id="tickets-sold" class="text-3xl font-light text-slate-900 mt-1">0</p>
            </div>
            <div class="w-12 h-12 bg-emerald-100 rounded-xl flex items-center justify-center">
              <svg class="w-6 h-6 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="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"></path>
              </svg>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-2xl p-6 shadow-lg border border-slate-200/50">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-semibold text-slate-600 uppercase tracking-wide">Available</p>
              <p id="tickets-available" class="text-3xl font-light text-slate-900 mt-1">--</p>
            </div>
            <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
              <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path>
              </svg>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-2xl p-6 shadow-lg border border-slate-200/50">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-semibold text-slate-600 uppercase tracking-wide">Check-ins</p>
              <p id="checked-in" class="text-3xl font-light text-slate-900 mt-1">0</p>
            </div>
            <div class="w-12 h-12 bg-purple-100 rounded-xl flex items-center justify-center">
              <svg class="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              </svg>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-2xl p-6 shadow-lg border border-slate-200/50">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-semibold text-slate-600 uppercase tracking-wide">Net Revenue</p>
              <p id="net-revenue" class="text-3xl font-light text-slate-900 mt-1">$0</p>
            </div>
            <div class="w-12 h-12 bg-amber-100 rounded-xl flex items-center justify-center">
              <svg class="w-6 h-6 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1"></path>
              </svg>
            </div>
          </div>
        </div>
      </div>

      <!-- Management Tabs -->
      <div class="bg-white rounded-3xl shadow-xl border border-slate-200/50 overflow-hidden">
        <!-- Tab Navigation -->
        <div class="border-b border-slate-200">
          <nav class="flex space-x-8 px-8">
            <button
              id="tab-tickets"
              class="tab-button border-b-2 border-slate-800 text-slate-800 py-4 px-1 text-sm font-semibold transition-colors duration-200"
            >
              Ticket Types
            </button>
            <button
              id="tab-venue"
              class="tab-button border-b-2 border-transparent text-slate-500 hover:text-slate-700 py-4 px-1 text-sm font-semibold transition-colors duration-200"
            >
              Venue & Seating
            </button>
            <button
              id="tab-orders"
              class="tab-button border-b-2 border-transparent text-slate-500 hover:text-slate-700 py-4 px-1 text-sm font-semibold transition-colors duration-200"
            >
              Sales & Orders
            </button>
            <button
              id="tab-attendees"
              class="tab-button border-b-2 border-transparent text-slate-500 hover:text-slate-700 py-4 px-1 text-sm font-semibold transition-colors duration-200"
            >
              Guest List
            </button>
            <button
              id="tab-presale"
              class="tab-button border-b-2 border-transparent text-slate-500 hover:text-slate-700 py-4 px-1 text-sm font-semibold transition-colors duration-200"
            >
              Presale Codes
            </button>
            <button
              id="tab-discount"
              class="tab-button border-b-2 border-transparent text-slate-500 hover:text-slate-700 py-4 px-1 text-sm font-semibold transition-colors duration-200"
            >
              Discount Codes
            </button>
            <button
              id="tab-addons"
              class="tab-button border-b-2 border-transparent text-slate-500 hover:text-slate-700 py-4 px-1 text-sm font-semibold transition-colors duration-200"
            >
              Premium Add-ons
            </button>
            <button
              id="tab-settings"
              class="tab-button border-b-2 border-transparent text-slate-500 hover:text-slate-700 py-4 px-1 text-sm font-semibold transition-colors duration-200"
            >
              Settings
            </button>
          </nav>
        </div>

        <!-- Tab Content -->
        <div class="p-8">
          <!-- Ticket Types Tab -->
          <div id="content-tickets" class="tab-content">
            <div class="flex justify-between items-center mb-8">
              <div>
                <h2 class="text-2xl font-light text-slate-900 mb-2">Ticket Types</h2>
                <p class="text-slate-600">Manage pricing, availability, and ticket variations for your event</p>
              </div>
              <button
                id="add-ticket-type-btn"
                class="bg-gradient-to-r from-slate-800 to-slate-900 hover:from-slate-900 hover:to-black text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg"
              >
                <svg class="w-5 h-5 inline-block mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                </svg>
                Add Ticket Type
              </button>
            </div>

            <div id="ticket-types-list" class="space-y-4">
              <!-- Ticket types will be loaded here -->
            </div>

            <!-- Empty state for ticket types -->
            <div id="ticket-types-empty" class="text-center py-12 hidden">
              <div class="w-24 h-24 mx-auto text-slate-400 mb-4">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" 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"></path>
                </svg>
              </div>
              <h3 class="text-xl font-light text-slate-900 mb-2">No ticket types created</h3>
              <p class="text-slate-600 mb-6">Create different ticket types with varying prices and access levels</p>
              <button
                onclick="showTicketTypeModal()"
                class="bg-slate-800 hover:bg-slate-900 text-white px-6 py-3 rounded-xl font-medium transition-colors duration-200"
              >
                Create Your First Ticket Type
              </button>
            </div>
          </div>

          <!-- Venue & Seating Tab -->
          <div id="content-venue" class="tab-content hidden">
            <div class="flex justify-between items-center mb-8">
              <div>
                <h2 class="text-2xl font-light text-slate-900 mb-2">Venue & Seating</h2>
                <p class="text-slate-600">Configure venue details and seating arrangements</p>
              </div>
              <div class="flex space-x-3">
                <button
                  id="manage-venues-btn"
                  class="bg-white border border-slate-300 hover:bg-slate-50 text-slate-700 px-6 py-3 rounded-xl font-medium transition-colors duration-200"
                >
                  Manage Venues
                </button>
                <button
                  id="create-seating-map-btn"
                  onclick="console.log('Button clicked'); openSeatingMapModal();"
                  class="bg-gradient-to-r from-slate-800 to-slate-900 hover:from-slate-900 hover:to-black text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg"
                >
                  Create Seating Map
                </button>
              </div>
            </div>

            <div id="venue-content">
              <!-- Existing Seating Maps -->
              <div class="mb-8">
                <h3 class="text-xl font-medium text-slate-900 mb-4">Available Seating Maps</h3>
                <div id="seating-maps-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  <!-- Seating maps will be loaded here -->
                </div>
              </div>

              <!-- Current Event Seating Configuration -->
              <div class="bg-slate-50 rounded-xl p-6 mb-8">
                <h3 class="text-xl font-medium text-slate-900 mb-4">Current Event Seating</h3>
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                  <div>
                    <label for="seating-type" class="block text-sm font-semibold text-slate-700 mb-2">Seating Type</label>
                    <select
                      id="seating-type"
                      name="seating_type"
                      class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    >
                      <option value="general_admission">General Admission</option>
                      <option value="assigned_seating">Assigned Seating</option>
                      <option value="mixed">Mixed (Both)</option>
                    </select>
                  </div>
                  <div>
                    <label for="seating-map-select" class="block text-sm font-semibold text-slate-700 mb-2">Seating Map</label>
                    <select
                      id="seating-map-select"
                      name="seating_map_id"
                      class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    >
                      <option value="">No seating map</option>
                      <!-- Options will be loaded here -->
                    </select>
                  </div>
                </div>
                <div class="mt-6">
                  <button
                    type="button"
                    onclick="updateEventSeating()"
                    class="bg-gradient-to-r from-slate-800 to-slate-900 hover:from-slate-900 hover:to-black text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg"
                  >
                    Update Seating Configuration
                  </button>
                </div>
              </div>

              <!-- Seating Map Preview -->
              <div id="seating-preview" class="bg-white rounded-xl border border-slate-200 p-6 hidden">
                <h3 class="text-xl font-medium text-slate-900 mb-4">Seating Map Preview</h3>
                <div id="seating-chart" class="border rounded-lg p-4 min-h-[400px] bg-slate-50">
                  <!-- Seating chart visualization will be rendered here -->
                </div>
              </div>
            </div>
          </div>

            <div class="flex justify-between items-center mb-8">
              <div>
                <h2 class="text-2xl font-light text-slate-900 mb-2">Sales Analytics</h2>
                <p class="text-slate-600">Track sales performance and revenue insights</p>
              </div>
              <div class="flex space-x-3">
                <button
                  id="refresh-analytics-btn"
                  class="bg-white border border-slate-300 hover:bg-slate-50 text-slate-700 px-4 py-2 rounded-xl text-sm font-medium transition-colors duration-200"
                >
                  <svg class="w-4 h-4 inline-block mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                  </svg>
                  Refresh
                </button>
                <button
                  id="export-analytics-btn"
                  class="bg-gradient-to-r from-slate-800 to-slate-900 hover:from-slate-900 hover:to-black text-white px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200 shadow-lg"
                >
                  <svg class="w-4 h-4 inline-block mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                  </svg>
                  Export CSV
                </button>
              </div>
            </div>
            
            <!-- Analytics Loading State -->
            <div id="analytics-loading" class="text-center py-12 hidden">
              <div class="animate-spin rounded-full h-10 w-10 border-2 border-slate-800 border-t-transparent mx-auto mb-4"></div>
              <p class="text-slate-600 font-medium">Loading analytics data...</p>
            </div>

            <!-- Analytics Content -->
            <div id="analytics-content" class="">
              <!-- Revenue Breakdown Cards -->
              <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
                <div class="bg-gradient-to-br from-emerald-50 to-emerald-100 rounded-2xl p-6 border border-emerald-200">
                  <div class="flex items-center justify-between">
                    <div>
                      <p class="text-sm font-semibold text-emerald-700 uppercase tracking-wide">Gross Revenue</p>
                      <p id="analytics-gross-revenue" class="text-3xl font-light text-emerald-900 mt-1">$0</p>
                    </div>
                    <div class="w-12 h-12 bg-emerald-200 rounded-xl flex items-center justify-center">
                      <svg class="w-6 h-6 text-emerald-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1"></path>
                      </svg>
                    </div>
                  </div>
                </div>

                <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-2xl p-6 border border-blue-200">
                  <div class="flex items-center justify-between">
                    <div>
                      <p class="text-sm font-semibold text-blue-700 uppercase tracking-wide">Your Payout</p>
                      <p id="analytics-net-revenue" class="text-3xl font-light text-blue-900 mt-1">$0</p>
                    </div>
                    <div class="w-12 h-12 bg-blue-200 rounded-xl flex items-center justify-center">
                      <svg class="w-6 h-6 text-blue-700" 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-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z"></path>
                      </svg>
                    </div>
                  </div>
                </div>

                <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-2xl p-6 border border-purple-200">
                  <div class="flex items-center justify-between">
                    <div>
                      <p class="text-sm font-semibold text-purple-700 uppercase tracking-wide">Avg. Ticket Price</p>
                      <p id="analytics-avg-price" class="text-3xl font-light text-purple-900 mt-1">$0</p>
                    </div>
                    <div class="w-12 h-12 bg-purple-200 rounded-xl flex items-center justify-center">
                      <svg class="w-6 h-6 text-purple-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
                      </svg>
                    </div>
                  </div>
                </div>

                <div class="bg-gradient-to-br from-amber-50 to-amber-100 rounded-2xl p-6 border border-amber-200">
                  <div class="flex items-center justify-between">
                    <div>
                      <p class="text-sm font-semibold text-amber-700 uppercase tracking-wide">Conversion Rate</p>
                      <p id="analytics-conversion-rate" class="text-3xl font-light text-amber-900 mt-1">0%</p>
                    </div>
                    <div class="w-12 h-12 bg-amber-200 rounded-xl flex items-center justify-center">
                      <svg class="w-6 h-6 text-amber-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"></path>
                      </svg>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Charts Row -->
              <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
                <!-- Sales Over Time Chart -->
                <div class="bg-white rounded-2xl p-6 shadow-lg border border-slate-200">
                  <h3 class="text-lg font-semibold text-slate-900 mb-4">Sales Over Time</h3>
                  <div class="h-64 flex items-center justify-center">
                    <div id="sales-chart" class="w-full h-full">
                      <!-- Chart will be rendered here -->
                      <canvas id="sales-over-time-chart" class="w-full h-full"></canvas>
                    </div>
                  </div>
                </div>

                <!-- Revenue Breakdown Pie Chart -->
                <div class="bg-white rounded-2xl p-6 shadow-lg border border-slate-200">
                  <h3 class="text-lg font-semibold text-slate-900 mb-4">Revenue Breakdown</h3>
                  <div class="h-64 flex items-center justify-center">
                    <div id="revenue-breakdown" class="w-full h-full">
                      <!-- Pie chart will be rendered here -->
                      <canvas id="revenue-breakdown-chart" class="w-full h-full"></canvas>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Performance Tables Row -->
              <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
                <!-- Ticket Type Performance -->
                <div class="bg-white rounded-2xl p-6 shadow-lg border border-slate-200">
                  <h3 class="text-lg font-semibold text-slate-900 mb-4">Ticket Type Performance</h3>
                  <div class="overflow-x-auto">
                    <table class="w-full">
                      <thead>
                        <tr class="border-b border-slate-200">
                          <th class="text-left py-3 text-sm font-semibold text-slate-600">Type</th>
                          <th class="text-right py-3 text-sm font-semibold text-slate-600">Sold</th>
                          <th class="text-right py-3 text-sm font-semibold text-slate-600">Available</th>
                          <th class="text-right py-3 text-sm font-semibold text-slate-600">Revenue</th>
                        </tr>
                      </thead>
                      <tbody id="ticket-type-performance">
                        <!-- Performance data will be loaded here -->
                      </tbody>
                    </table>
                  </div>
                </div>

                <!-- Recent Sales -->
                <div class="bg-white rounded-2xl p-6 shadow-lg border border-slate-200">
                  <h3 class="text-lg font-semibold text-slate-900 mb-4">Recent Sales</h3>
                  <div class="space-y-3 max-h-64 overflow-y-auto">
                    <div id="recent-sales-list">
                      <!-- Recent sales will be loaded here -->
                    </div>
                  </div>
                </div>
              </div>

              <!-- Sales Velocity and Trends -->
              <div class="bg-gradient-to-r from-slate-50 to-slate-100 rounded-2xl p-6 border border-slate-200">
                <h3 class="text-lg font-semibold text-slate-900 mb-4">Sales Insights</h3>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <div class="text-center">
                    <div class="text-2xl font-bold text-slate-900" id="sales-velocity">0</div>
                    <div class="text-sm text-slate-600">Sales Last 24h</div>
                  </div>
                  <div class="text-center">
                    <div class="text-2xl font-bold text-slate-900" id="sales-trend">→</div>
                    <div class="text-sm text-slate-600">Sales Trend</div>
                  </div>
                  <div class="text-center">
                    <div class="text-2xl font-bold text-slate-900" id="days-until-event">--</div>
                    <div class="text-sm text-slate-600">Days Until Event</div>
                  </div>
                </div>
              </div>

            </div>

            <!-- No Data State -->
            <div id="analytics-no-data" class="text-center py-16 hidden">
              <div class="w-24 h-24 mx-auto text-slate-400 mb-4">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2-2V7a2 2 0 012-2h2a2 2 0 002 2v2a2 2 0 002 2h2a2 2 0 002-2V7a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 00-2 2v6a2 2 0 01-2 2H9a2 2 0 01-2-2z"></path>
                </svg>
              </div>
              <h3 class="text-xl font-light text-slate-900 mb-2">No sales data yet</h3>
              <p class="text-slate-600 mb-6">Analytics will appear here once tickets are sold for this event.</p>
              <a
                href="#"
                id="share-event-link"
                class="bg-slate-800 hover:bg-slate-900 text-white px-6 py-3 rounded-xl font-medium transition-colors duration-200"
              >
                Share Event to Start Selling
              </a>
            </div>
          </div>

          <!-- Sales & Orders Tab -->
          <div id="content-orders" class="tab-content hidden">
            <div class="flex justify-between items-center mb-6">
              <div>
                <h2 class="text-2xl font-light text-slate-900 mb-2">Sales & Orders</h2>
                <p class="text-slate-600">View all ticket sales and manage individual orders</p>
              </div>
              <div class="flex space-x-3">
                <button
                  id="export-sales-btn"
                  class="bg-white border border-slate-300 hover:bg-slate-50 text-slate-700 px-6 py-3 rounded-xl font-medium transition-colors duration-200"
                >
                  Export Sales CSV
                </button>
              </div>
            </div>

            <!-- Search and Filter Bar -->
            <div class="bg-slate-50 rounded-xl p-6 mb-6 border border-slate-200">
              <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <div>
                  <label for="sales-search-email" class="block text-sm font-medium text-slate-700 mb-2">Search by Email</label>
                  <input
                    type="text"
                    id="sales-search-email"
                    placeholder="customer@example.com"
                    class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent text-sm"
                  >
                </div>
                <div>
                  <label for="sales-search-name" class="block text-sm font-medium text-slate-700 mb-2">Search by Name</label>
                  <input
                    type="text"
                    id="sales-search-name"
                    placeholder="Customer Name"
                    class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent text-sm"
                  >
                </div>
                <div>
                  <label for="sales-filter-status" class="block text-sm font-medium text-slate-700 mb-2">Filter by Status</label>
                  <select
                    id="sales-filter-status"
                    class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent text-sm"
                  >
                    <option value="">All Statuses</option>
                    <option value="active">Active Tickets</option>
                    <option value="checked_in">Checked In</option>
                    <option value="refund_requested">Refund Requested</option>
                    <option value="refund_completed">Refunded</option>
                  </select>
                </div>
                <div>
                  <label for="sales-filter-ticket-type" class="block text-sm font-medium text-slate-700 mb-2">Ticket Type</label>
                  <select
                    id="sales-filter-ticket-type"
                    class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent text-sm"
                  >
                    <option value="">All Types</option>
                    <!-- Ticket types will be populated dynamically -->
                  </select>
                </div>
              </div>
              <div class="flex justify-between items-center mt-4">
                <div class="flex space-x-3">
                  <button
                    onclick="searchSales()"
                    class="bg-slate-800 hover:bg-slate-900 text-white px-4 py-2 rounded-lg font-medium transition-colors text-sm"
                  >
                    Search & Filter
                  </button>
                  <button
                    onclick="clearSalesFilters()"
                    class="bg-white border border-slate-300 hover:bg-slate-50 text-slate-700 px-4 py-2 rounded-lg font-medium transition-colors text-sm"
                  >
                    Clear Filters
                  </button>
                </div>
                <div class="text-sm text-slate-600">
                  <span id="orders-results-count">Loading...</span>
                </div>
              </div>
            </div>

            <div id="orders-content">
              <!-- Orders content will be loaded here -->
            </div>

            <!-- Pagination -->
            <div id="orders-pagination" class="mt-6 flex justify-center">
              <!-- Pagination will be loaded here -->
            </div>
          </div>

          <!-- Guest List Tab -->
          <div id="content-attendees" class="tab-content hidden">
            <div class="flex justify-between items-center mb-8">
              <div>
                <h2 class="text-2xl font-light text-slate-900 mb-2">Guest List</h2>
                <p class="text-slate-600">Manage attendees and check-in status</p>
              </div>
              <div class="flex space-x-3">
                <button
                  id="export-guests-btn"
                  class="bg-white border border-slate-300 hover:bg-slate-50 text-slate-700 px-6 py-3 rounded-xl font-medium transition-colors duration-200"
                >
                  Export CSV
                </button>
                <a
                  href="/scan"
                  class="bg-gradient-to-r from-slate-800 to-slate-900 hover:from-slate-900 hover:to-black text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg inline-block"
                >
                  Scan Tickets
                </a>
              </div>
            </div>

            <div id="attendees-content">
              <!-- Attendees content will be loaded here -->
            </div>
          </div>

          <!-- Presale Codes Tab -->
          <div id="content-presale" class="tab-content hidden">
            <div class="flex justify-between items-center mb-8">
              <div>
                <h2 class="text-2xl font-light text-slate-900 mb-2">Presale Codes</h2>
                <p class="text-slate-600">Manage early access codes for ticket sales before general public</p>
              </div>
              <button
                id="add-presale-code-btn"
                class="bg-gradient-to-r from-slate-800 to-slate-900 hover:from-slate-900 hover:to-black text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg"
              >
                <svg class="w-5 h-5 inline-block mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                </svg>
                Add Presale Code
              </button>
            </div>

            <div id="presale-codes-list" class="space-y-4">
              <!-- Presale codes will be loaded here -->
            </div>

            <!-- Empty state for presale codes -->
            <div id="presale-codes-empty" class="text-center py-12 hidden">
              <div class="w-24 h-24 mx-auto text-slate-400 mb-4">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" 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"></path>
                </svg>
              </div>
              <h3 class="text-xl font-light text-slate-900 mb-2">No presale codes created</h3>
              <p class="text-slate-600 mb-6">Create presale codes to offer early access and discounts to your customers</p>
              <button
                onclick="showPresaleCodeModal()"
                class="bg-slate-800 hover:bg-slate-900 text-white px-6 py-3 rounded-xl font-medium transition-colors duration-200"
              >
                Create Your First Presale Code
              </button>
            </div>
          </div>

          <!-- Discount Codes Tab -->
          <div id="content-discount" class="tab-content hidden">
            <div class="flex justify-between items-center mb-8">
              <div>
                <h2 class="text-2xl font-light text-slate-900 mb-2">Discount Codes</h2>
                <p class="text-slate-600">Manage promotional discount codes for your event</p>
              </div>
              <button
                id="add-discount-code-btn"
                class="bg-gradient-to-r from-slate-800 to-slate-900 hover:from-slate-900 hover:to-black text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg"
              >
                <svg class="w-5 h-5 inline-block mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                </svg>
                Add Discount Code
              </button>
            </div>

            <div id="discount-codes-list" class="space-y-4">
              <!-- Discount codes will be loaded here -->
            </div>

            <!-- Empty state for discount codes -->
            <div id="discount-codes-empty" class="text-center py-12 hidden">
              <div class="w-24 h-24 mx-auto text-slate-400 mb-4">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" 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"></path>
                </svg>
              </div>
              <h3 class="text-xl font-light text-slate-900 mb-2">No discount codes created</h3>
              <p class="text-slate-600 mb-6">Create discount codes to offer promotional pricing to your customers</p>
              <button
                onclick="showDiscountCodeModal()"
                class="bg-slate-800 hover:bg-slate-900 text-white px-6 py-3 rounded-xl font-medium transition-colors duration-200"
              >
                Create Your First Discount Code
              </button>
            </div>
          </div>

          <!-- Add-ons Tab -->
          <div id="content-addons" class="tab-content hidden">
            <div class="max-w-4xl">
              <h2 class="text-2xl font-light text-slate-900 mb-2">Premium Add-ons</h2>
              <p class="text-slate-600 mb-8">Manage premium features and services for your event</p>

              <!-- Current Add-ons -->
              <div class="bg-white rounded-2xl shadow-lg border border-slate-200/50 mb-8">
                <div class="px-6 py-4 border-b border-slate-200 bg-slate-50 rounded-t-2xl">
                  <h3 class="text-lg font-semibold text-slate-900">Active Add-ons</h3>
                </div>
                <div class="p-6">
                  <div id="current-addons-list" class="space-y-4">
                    <!-- Current add-ons will be loaded here -->
                  </div>
                </div>
              </div>

              <!-- Available Add-ons -->
              <div class="bg-white rounded-2xl shadow-lg border border-slate-200/50">
                <div class="px-6 py-4 border-b border-slate-200 bg-slate-50 rounded-t-2xl">
                  <h3 class="text-lg font-semibold text-slate-900">Available Add-ons</h3>
                </div>
                <div class="p-6">
                  <div id="available-addons-list" class="grid gap-6 md:grid-cols-2">
                    <!-- Available add-ons will be loaded here -->
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Settings Tab -->
          <div id="content-settings" class="tab-content hidden">
            <div class="max-w-4xl">
              <h2 class="text-2xl font-light text-slate-900 mb-2">Event Settings</h2>
              <p class="text-slate-600 mb-8">Configure how ticket availability is displayed to customers</p>

              <!-- Availability Display Settings -->
              <div class="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-2xl p-6 mb-8 border border-blue-100">
                <h3 class="text-lg font-semibold text-slate-900 mb-4 flex items-center">
                  <svg class="w-5 h-5 text-blue-600 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                  </svg>
                  Availability Display Settings
                </h3>
                
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                  <!-- Display Mode -->
                  <div class="space-y-3">
                    <label class="block text-sm font-semibold text-slate-700">Display Mode</label>
                    <div class="space-y-2">
                      <label class="flex items-center">
                        <input type="radio" name="availability_display_mode" value="available_only" class="text-blue-600 focus:ring-blue-500" checked>
                        <span class="ml-2 text-sm text-slate-700">
                          <span class="font-medium">Available Only</span> - Show "Available" or "Sold Out"
                        </span>
                      </label>
                      <label class="flex items-center">
                        <input type="radio" name="availability_display_mode" value="show_quantity" class="text-blue-600 focus:ring-blue-500">
                        <span class="ml-2 text-sm text-slate-700">
                          <span class="font-medium">Show Quantity</span> - Always show exact number available
                        </span>
                      </label>
                      <label class="flex items-center">
                        <input type="radio" name="availability_display_mode" value="smart_threshold" class="text-blue-600 focus:ring-blue-500">
                        <span class="ml-2 text-sm text-slate-700">
                          <span class="font-medium">Smart Threshold</span> - Show count when below threshold
                        </span>
                      </label>
                    </div>
                  </div>

                  <!-- Threshold Settings -->
                  <div class="space-y-4">
                    <div>
                      <label for="availability_threshold" class="block text-sm font-semibold text-slate-700 mb-2">
                        Smart Threshold
                      </label>
                      <input
                        type="number"
                        id="availability_threshold"
                        name="availability_threshold"
                        min="1"
                        max="100"
                        value="10"
                        class="block w-full border-slate-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                      >
                      <p class="mt-1 text-xs text-slate-500">Show exact count when tickets drop below this number</p>
                    </div>

                    <div>
                      <label for="low_stock_threshold" class="block text-sm font-semibold text-slate-700 mb-2">
                        Low Stock Warning
                      </label>
                      <input
                        type="number"
                        id="low_stock_threshold"
                        name="low_stock_threshold"
                        min="1"
                        max="50"
                        value="5"
                        class="block w-full border-slate-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                      >
                      <p class="mt-1 text-xs text-slate-500">Show "Low Stock" badge when below this number</p>
                    </div>
                  </div>
                </div>

                <!-- Additional Options -->
                <div class="mt-6 pt-6 border-t border-blue-200">
                  <h4 class="text-md font-semibold text-slate-900 mb-3">Additional Options</h4>
                  <div class="space-y-3">
                    <label class="flex items-center">
                      <input type="checkbox" name="show_sold_out" class="text-blue-600 focus:ring-blue-500" checked>
                      <span class="ml-2 text-sm text-slate-700">Show sold out tickets in checkout</span>
                    </label>
                  </div>
                </div>

                <!-- Custom Messages -->
                <div class="mt-6 pt-6 border-t border-blue-200">
                  <h4 class="text-md font-semibold text-slate-900 mb-3">Custom Messages</h4>
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label for="msg_available" class="block text-sm font-medium text-slate-700 mb-1">Available Message</label>
                      <input
                        type="text"
                        id="msg_available"
                        name="msg_available"
                        value="Available"
                        class="block w-full border-slate-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                      >
                    </div>
                    <div>
                      <label for="msg_low_stock" class="block text-sm font-medium text-slate-700 mb-1">Low Stock Message</label>
                      <input
                        type="text"
                        id="msg_low_stock"
                        name="msg_low_stock"
                        value="&#123;count&#125; left"
                        class="block w-full border-slate-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                      >
                      <p class="mt-1 text-xs text-slate-500">Use &#123;count&#125; for the number</p>
                    </div>
                    <div>
                      <label for="msg_sold_out" class="block text-sm font-medium text-slate-700 mb-1">Sold Out Message</label>
                      <input
                        type="text"
                        id="msg_sold_out"
                        name="msg_sold_out"
                        value="Sold out"
                        class="block w-full border-slate-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                      >
                    </div>
                    <div>
                      <label for="msg_unlimited" class="block text-sm font-medium text-slate-700 mb-1">Unlimited Message</label>
                      <input
                        type="text"
                        id="msg_unlimited"
                        name="msg_unlimited"
                        value="Available"
                        class="block w-full border-slate-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                      >
                    </div>
                  </div>
                </div>

                <!-- Save Button -->
                <div class="mt-6 pt-6 border-t border-blue-200">
                  <button
                    id="save-availability-settings"
                    class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg font-semibold transition-colors duration-200 shadow-md hover:shadow-lg"
                  >
                    Save Availability Settings
                  </button>
                </div>
              </div>

              <!-- Preview Section -->
              <div class="bg-gradient-to-r from-gray-50 to-slate-50 rounded-2xl p-6 border border-slate-200">
                <h3 class="text-lg font-semibold text-slate-900 mb-4">Preview</h3>
                <p class="text-slate-600 mb-4">Here's how different availability scenarios will appear to customers:</p>
                
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <!-- High Stock Preview -->
                  <div class="bg-white rounded-lg p-4 border border-slate-200">
                    <h4 class="font-medium text-slate-900">General Admission</h4>
                    <p class="text-lg font-semibold text-slate-900 mt-1">$125.00</p>
                    <span id="preview-high-stock" class="text-sm text-green-600">Available</span>
                  </div>
                  
                  <!-- Low Stock Preview -->
                  <div class="bg-white rounded-lg p-4 border border-slate-200">
                    <div class="flex items-center gap-2">
                      <h4 class="font-medium text-slate-900">VIP Tickets</h4>
                      <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-orange-100 text-orange-800">
                        Low Stock
                      </span>
                    </div>
                    <p class="text-lg font-semibold text-slate-900 mt-1">$350.00</p>
                    <span id="preview-low-stock" class="text-sm text-orange-600">3 left</span>
                  </div>
                  
                  <!-- Sold Out Preview -->
                  <div class="bg-gray-50 rounded-lg p-4 border border-slate-200 opacity-75">
                    <h4 class="font-medium text-slate-900">Early Bird</h4>
                    <p class="text-lg font-semibold text-slate-900 mt-1">$95.00</p>
                    <span id="preview-sold-out" class="text-sm text-red-600">Sold out</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</Layout>

    <!-- Ticket Type Modal -->
    <div id="ticket-type-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm hidden z-50">
      <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-3xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
          <form id="ticket-type-form" class="p-8">
            <div class="mb-8">
              <h2 id="ticket-modal-title" class="text-3xl font-light text-slate-900 mb-2">Create Ticket Type</h2>
              <p class="text-slate-600">Define pricing and availability for this ticket type</p>
            </div>

            <div class="space-y-6">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label for="ticket-name" class="block text-sm font-semibold text-slate-700 mb-2">Ticket Name</label>
                  <input
                    type="text"
                    id="ticket-name"
                    name="name"
                    required
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    placeholder="General Admission, VIP, Early Bird"
                  />
                </div>
                
                <div>
                  <label for="ticket-price" class="block text-sm font-semibold text-slate-700 mb-2">Price ($)</label>
                  <input
                    type="number"
                    id="ticket-price"
                    name="price"
                    step="0.01"
                    min="0"
                    required
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    placeholder="125.00"
                  />
                </div>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label for="ticket-quantity" class="block text-sm font-semibold text-slate-700 mb-2">Quantity Available</label>
                  <input
                    type="number"
                    id="ticket-quantity"
                    name="quantity_available"
                    min="1"
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    placeholder="100 (leave empty for unlimited)"
                  />
                </div>
                
                <div>
                  <label for="ticket-sort-order" class="block text-sm font-semibold text-slate-700 mb-2">Display Order</label>
                  <input
                    type="number"
                    id="ticket-sort-order"
                    name="sort_order"
                    min="0"
                    value="0"
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                  />
                </div>
              </div>

              <div>
                <label for="ticket-description" class="block text-sm font-semibold text-slate-700 mb-2">Description (Optional)</label>
                <textarea
                  id="ticket-description"
                  name="description"
                  rows="3"
                  class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                  placeholder="Special perks, access levels, or restrictions for this ticket type"
                ></textarea>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label class="block text-sm font-semibold text-slate-700 mb-2">Sale Start (Optional)</label>
                  <div class="grid grid-cols-2 gap-3">
                    <div>
                      <label for="ticket-sale-start-date" class="block text-xs font-medium text-slate-600 mb-1">Date</label>
                      <input
                        type="date"
                        id="ticket-sale-start-date"
                        name="sale_start_date"
                        class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200 text-sm"
                      />
                    </div>
                    <div>
                      <label for="ticket-sale-start-time" class="block text-xs font-medium text-slate-600 mb-1">Time</label>
                      <select
                        id="ticket-sale-start-time"
                        name="sale_start_time_select"
                        class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200 text-sm"
                      >
                        <option value="">Select time</option>
                        <option value="09:00">9:00 AM</option>
                        <option value="12:00">12:00 PM</option>
                        <option value="15:00">3:00 PM</option>
                        <option value="18:00">6:00 PM</option>
                        <option value="21:00">9:00 PM</option>
                      </select>
                    </div>
                  </div>
                </div>
                
                <div>
                  <label class="block text-sm font-semibold text-slate-700 mb-2">Sale End (Optional)</label>
                  <div class="grid grid-cols-2 gap-3">
                    <div>
                      <label for="ticket-sale-end-date" class="block text-xs font-medium text-slate-600 mb-1">Date</label>
                      <input
                        type="date"
                        id="ticket-sale-end-date"
                        name="sale_end_date"
                        class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200 text-sm"
                      />
                    </div>
                    <div>
                      <label for="ticket-sale-end-time" class="block text-xs font-medium text-slate-600 mb-1">Time</label>
                      <select
                        id="ticket-sale-end-time"
                        name="sale_end_time_select"
                        class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200 text-sm"
                      >
                        <option value="">Select time</option>
                        <option value="09:00">9:00 AM</option>
                        <option value="12:00">12:00 PM</option>
                        <option value="15:00">3:00 PM</option>
                        <option value="18:00">6:00 PM</option>
                        <option value="21:00">9:00 PM</option>
                        <option value="23:59">11:59 PM</option>
                      </select>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="flex justify-end space-x-4 mt-8 pt-6 border-t border-slate-200">
              <button
                type="button"
                onclick="closeTicketTypeModal()"
                class="px-6 py-3 border border-slate-300 text-slate-700 rounded-xl hover:bg-slate-50 font-medium transition-colors duration-200"
              >
                Cancel
              </button>
              <button
                type="submit"
                class="px-8 py-3 bg-gradient-to-r from-slate-800 to-slate-900 text-white rounded-xl hover:from-slate-900 hover:to-black font-medium transition-all duration-200"
              >
                <span id="ticket-submit-text">Create Ticket Type</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- Presale Code Modal -->
    <div id="presale-code-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm hidden z-50">
      <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-3xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
          <form id="presale-code-form" class="p-8">
            <div class="mb-8">
              <h2 id="presale-modal-title" class="text-3xl font-light text-slate-900 mb-2">Create Presale Code</h2>
              <p class="text-slate-600">Create a code for early access to ticket sales</p>
            </div>

            <div class="space-y-6">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label for="presale-code" class="block text-sm font-semibold text-slate-700 mb-2">Code</label>
                  <input
                    type="text"
                    id="presale-code"
                    name="code"
                    required
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    placeholder="EARLY2024"
                  />
                </div>
                
                <div>
                  <label for="presale-usage-limit" class="block text-sm font-semibold text-slate-700 mb-2">Usage Limit</label>
                  <input
                    type="number"
                    id="presale-usage-limit"
                    name="usage_limit"
                    min="1"
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    placeholder="Leave empty for unlimited"
                  />
                </div>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label for="presale-customer-usage-limit" class="block text-sm font-semibold text-slate-700 mb-2">Per Customer Limit</label>
                  <input
                    type="number"
                    id="presale-customer-usage-limit"
                    name="customer_usage_limit"
                    min="1"
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    placeholder="Leave empty for unlimited"
                  />
                </div>

                <div>
                  <label class="block text-sm font-semibold text-slate-700 mb-2">Code Type</label>
                  <div class="flex items-center p-4 bg-blue-50 rounded-xl border border-blue-200">
                    <svg class="w-5 h-5 text-blue-600 mr-3" 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"></path>
                    </svg>
                    <span class="text-blue-800 font-medium">Early Access Only</span>
                  </div>
                  <p class="text-xs text-slate-500 mt-2">This code provides early access to tickets before general sales begin</p>
                </div>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label class="block text-sm font-semibold text-slate-700 mb-2">Valid From</label>
                  <div class="grid grid-cols-2 gap-3">
                    <div>
                      <label for="presale-valid-from-date" class="block text-xs font-medium text-slate-600 mb-1">Date</label>
                      <input
                        type="date"
                        id="presale-valid-from-date"
                        name="valid_from_date"
                        class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200 text-sm"
                      />
                    </div>
                    <div>
                      <label for="presale-valid-from-time" class="block text-xs font-medium text-slate-600 mb-1">Time</label>
                      <select
                        id="presale-valid-from-time"
                        name="valid_from_time"
                        class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200 text-sm"
                      >
                        <option value="">Select time</option>
                        <option value="09:00">9:00 AM</option>
                        <option value="12:00">12:00 PM</option>
                        <option value="15:00">3:00 PM</option>
                        <option value="18:00">6:00 PM</option>
                        <option value="21:00">9:00 PM</option>
                      </select>
                    </div>
                  </div>
                </div>
                
                <div>
                  <label class="block text-sm font-semibold text-slate-700 mb-2">Valid Until</label>
                  <div class="grid grid-cols-2 gap-3">
                    <div>
                      <label for="presale-valid-until-date" class="block text-xs font-medium text-slate-600 mb-1">Date</label>
                      <input
                        type="date"
                        id="presale-valid-until-date"
                        name="valid_until_date"
                        class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200 text-sm"
                      />
                    </div>
                    <div>
                      <label for="presale-valid-until-time" class="block text-xs font-medium text-slate-600 mb-1">Time</label>
                      <select
                        id="presale-valid-until-time"
                        name="valid_until_time"
                        class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200 text-sm"
                      >
                        <option value="">Select time</option>
                        <option value="09:00">9:00 AM</option>
                        <option value="12:00">12:00 PM</option>
                        <option value="15:00">3:00 PM</option>
                        <option value="18:00">6:00 PM</option>
                        <option value="21:00">9:00 PM</option>
                        <option value="23:59">11:59 PM</option>
                      </select>
                    </div>
                  </div>
                </div>
              </div>

              <div>
                <label for="presale-description" class="block text-sm font-semibold text-slate-700 mb-2">Description (Optional)</label>
                <textarea
                  id="presale-description"
                  name="description"
                  rows="3"
                  class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                  placeholder="Internal description for this presale code"
                ></textarea>
              </div>

              <div>
                <label class="block text-sm font-semibold text-slate-700 mb-2">Applicable Ticket Types</label>
                <div id="ticket-types-checkboxes" class="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <!-- Ticket type checkboxes will be loaded here -->
                </div>
              </div>
            </div>

            <div class="flex justify-end space-x-4 mt-8 pt-6 border-t border-slate-200">
              <button
                type="button"
                onclick="closePresaleCodeModal()"
                class="px-6 py-3 border border-slate-300 text-slate-700 rounded-xl hover:bg-slate-50 font-medium transition-colors duration-200"
              >
                Cancel
              </button>
              <button
                type="submit"
                class="px-8 py-3 bg-gradient-to-r from-slate-800 to-slate-900 text-white rounded-xl hover:from-slate-900 hover:to-black font-medium transition-all duration-200"
              >
                <span id="presale-submit-text">Create Presale Code</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- Discount Code Modal -->
    <div id="discount-code-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm hidden z-50">
      <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-3xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
          <form id="discount-code-form" class="p-8">
            <div class="mb-8">
              <h2 id="discount-modal-title" class="text-3xl font-light text-slate-900 mb-2">Create Discount Code</h2>
              <p class="text-slate-600">Create a promotional discount code for your event</p>
            </div>

            <div class="space-y-6">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label for="discount-code" class="block text-sm font-semibold text-slate-700 mb-2">Code</label>
                  <input
                    type="text"
                    id="discount-code"
                    name="code"
                    required
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    placeholder="SAVE20"
                  />
                </div>
                
                <div>
                  <label for="discount-usage-limit" class="block text-sm font-semibold text-slate-700 mb-2">Usage Limit</label>
                  <input
                    type="number"
                    id="discount-usage-limit"
                    name="usage_limit"
                    min="1"
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    placeholder="Leave empty for unlimited"
                  />
                </div>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label for="discount-customer-usage-limit" class="block text-sm font-semibold text-slate-700 mb-2">Per Customer Limit</label>
                  <input
                    type="number"
                    id="discount-customer-usage-limit"
                    name="customer_usage_limit"
                    min="1"
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    placeholder="Leave empty for unlimited"
                  />
                </div>

                <div>
                  <label for="discount-discount-type" class="block text-sm font-semibold text-slate-700 mb-2">Discount Type</label>
                  <select
                    id="discount-discount-type"
                    name="discount_type"
                    required
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                  >
                    <option value="">Select discount type</option>
                    <option value="percentage">Percentage Off</option>
                    <option value="fixed">Fixed Amount Off</option>
                  </select>
                </div>
              </div>

              <div>
                <label for="discount-discount-value" class="block text-sm font-semibold text-slate-700 mb-2">Discount Value</label>
                <input
                  type="number"
                  id="discount-discount-value"
                  name="discount_value"
                  step="0.01"
                  min="0"
                  required
                  class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                  placeholder="Enter discount amount"
                />
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label class="block text-sm font-semibold text-slate-700 mb-2">Valid From</label>
                  <div class="grid grid-cols-2 gap-3">
                    <div>
                      <label for="discount-valid-from-date" class="block text-xs font-medium text-slate-600 mb-1">Date</label>
                      <input
                        type="date"
                        id="discount-valid-from-date"
                        name="valid_from_date"
                        class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200 text-sm"
                      />
                    </div>
                    <div>
                      <label for="discount-valid-from-time" class="block text-xs font-medium text-slate-600 mb-1">Time</label>
                      <select
                        id="discount-valid-from-time"
                        name="valid_from_time"
                        class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200 text-sm"
                      >
                        <option value="">Select time</option>
                        <option value="09:00">9:00 AM</option>
                        <option value="12:00">12:00 PM</option>
                        <option value="15:00">3:00 PM</option>
                        <option value="18:00">6:00 PM</option>
                        <option value="21:00">9:00 PM</option>
                      </select>
                    </div>
                  </div>
                </div>
                
                <div>
                  <label class="block text-sm font-semibold text-slate-700 mb-2">Valid Until</label>
                  <div class="grid grid-cols-2 gap-3">
                    <div>
                      <label for="discount-valid-until-date" class="block text-xs font-medium text-slate-600 mb-1">Date</label>
                      <input
                        type="date"
                        id="discount-valid-until-date"
                        name="valid_until_date"
                        class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200 text-sm"
                      />
                    </div>
                    <div>
                      <label for="discount-valid-until-time" class="block text-xs font-medium text-slate-600 mb-1">Time</label>
                      <select
                        id="discount-valid-until-time"
                        name="valid_until_time"
                        class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200 text-sm"
                      >
                        <option value="">Select time</option>
                        <option value="09:00">9:00 AM</option>
                        <option value="12:00">12:00 PM</option>
                        <option value="15:00">3:00 PM</option>
                        <option value="18:00">6:00 PM</option>
                        <option value="21:00">9:00 PM</option>
                        <option value="23:59">11:59 PM</option>
                      </select>
                    </div>
                  </div>
                </div>
              </div>

              <div>
                <label for="discount-description" class="block text-sm font-semibold text-slate-700 mb-2">Description (Optional)</label>
                <textarea
                  id="discount-description"
                  name="description"
                  rows="3"
                  class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                  placeholder="Internal description for this discount code"
                ></textarea>
              </div>

              <div>
                <label class="block text-sm font-semibold text-slate-700 mb-2">Applicable Ticket Types</label>
                <div id="discount-ticket-types-checkboxes" class="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <!-- Ticket type checkboxes will be loaded here -->
                </div>
              </div>
            </div>

            <div class="flex justify-end space-x-4 mt-8 pt-6 border-t border-slate-200">
              <button
                type="button"
                onclick="closeDiscountCodeModal()"
                class="px-6 py-3 border border-slate-300 text-slate-700 rounded-xl hover:bg-slate-50 font-medium transition-colors duration-200"
              >
                Cancel
              </button>
              <button
                type="submit"
                class="px-8 py-3 bg-gradient-to-r from-slate-800 to-slate-900 text-white rounded-xl hover:from-slate-900 hover:to-black font-medium transition-all duration-200"
              >
                <span id="discount-submit-text">Create Discount Code</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- Seating Map Modal -->
    <div id="seating-map-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm hidden z-50">
      <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-3xl shadow-2xl max-w-5xl w-full h-[85vh] overflow-hidden flex flex-col">
          <form id="seating-map-form" class="flex-1 flex flex-col overflow-hidden">
            <!-- Header -->
            <div class="flex-shrink-0 p-6 border-b border-slate-200">
              <h2 id="seating-modal-title" class="text-2xl font-light text-slate-900 mb-1">Create Seating Map</h2>
              <p class="text-slate-600">Design a seating layout for your venue</p>
            </div>

            <!-- Content with Tabs -->
            <div class="flex-1 flex overflow-hidden">
              <!-- Sidebar -->
              <div class="w-80 bg-slate-50 border-r border-slate-200 p-6 overflow-y-auto">
                <div class="space-y-6">
                  <!-- Basic Info -->
                  <div>
                    <h3 class="text-lg font-medium text-slate-900 mb-4">Basic Information</h3>
                    <div class="space-y-4">
                      <div>
                        <label for="seating-map-name" class="block text-sm font-medium text-slate-700 mb-2">Map Name</label>
                        <input
                          type="text"
                          id="seating-map-name"
                          name="name"
                          required
                          class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                          placeholder="Main Theater Layout"
                          oninput="updateModalPreview()"
                        />
                      </div>
                      <div>
                        <label for="venue-name-input" class="block text-sm font-medium text-slate-700 mb-2">Venue Name</label>
                        <input
                          type="text"
                          id="venue-name-input"
                          name="venue_name"
                          required
                          class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                          placeholder="Grand Theater"
                          oninput="updateModalPreview()"
                        />
                      </div>
                    </div>
                  </div>

                  <!-- Layout Type -->
                  <div>
                    <h3 class="text-lg font-medium text-slate-900 mb-4">Layout Type</h3>
                    <div class="space-y-3">
                      <label class="flex items-center p-3 border border-slate-300 rounded-lg cursor-pointer hover:bg-slate-50">
                        <input type="radio" name="layout_type" value="theater" class="mr-3" checked onchange="updateLayoutPreview()">
                        <div>
                          <div class="font-medium">Theater</div>
                          <div class="text-sm text-slate-600">Rows of individual seats</div>
                        </div>
                      </label>
                      <label class="flex items-center p-3 border border-slate-300 rounded-lg cursor-pointer hover:bg-slate-50">
                        <input type="radio" name="layout_type" value="reception" class="mr-3" onchange="updateLayoutPreview()">
                        <div>
                          <div class="font-medium">Reception</div>
                          <div class="text-sm text-slate-600">Round tables for events</div>
                        </div>
                      </label>
                      <label class="flex items-center p-3 border border-slate-300 rounded-lg cursor-pointer hover:bg-slate-50">
                        <input type="radio" name="layout_type" value="concert_hall" class="mr-3" onchange="updateLayoutPreview()">
                        <div>
                          <div class="font-medium">Concert Hall</div>
                          <div class="text-sm text-slate-600">Mixed GA and reserved</div>
                        </div>
                      </label>
                      <label class="flex items-center p-3 border border-slate-300 rounded-lg cursor-pointer hover:bg-slate-50">
                        <input type="radio" name="layout_type" value="general" class="mr-3" onchange="updateLayoutPreview()">
                        <div>
                          <div class="font-medium">General Admission</div>
                          <div class="text-sm text-slate-600">Standing room only</div>
                        </div>
                      </label>
                    </div>
                  </div>

                  <!-- Configuration -->
                  <div id="layout-config">
                    <h3 class="text-lg font-medium text-slate-900 mb-4">Configuration</h3>
                    <!-- Dynamic content will be loaded here -->
                  </div>

                  <!-- Total Capacity -->
                  <div>
                    <label for="total-capacity-input" class="block text-sm font-medium text-slate-700 mb-2">Total Capacity</label>
                    <input
                      type="number"
                      id="total-capacity-input"
                      name="total_capacity"
                      required
                      min="1"
                      max="10000"
                      value="100"
                      class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                      oninput="updateModalPreview()"
                    />
                  </div>

                  <!-- Description -->
                  <div>
                    <label for="seating-description" class="block text-sm font-medium text-slate-700 mb-2">Description (Optional)</label>
                    <textarea
                      id="seating-description"
                      name="description"
                      rows="3"
                      class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                      placeholder="Additional details..."
                    ></textarea>
                  </div>
                </div>
              </div>

              <!-- Main Content Area -->
              <div class="flex-1 flex flex-col min-h-0">
                <!-- Layout Editor -->
                <div class="flex-1 p-6 overflow-y-auto">
                  <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-medium text-slate-900">Visual Layout Editor</h3>
                    <div class="flex space-x-2">
                      <button type="button" onclick="resetLayout()" class="px-3 py-1 text-sm bg-slate-100 text-slate-700 rounded-lg hover:bg-slate-200">
                        Reset
                      </button>
                      <button type="button" onclick="autoArrangeLayout()" class="px-3 py-1 text-sm bg-slate-800 text-white rounded-lg hover:bg-slate-900">
                        Auto Arrange
                      </button>
                    </div>
                  </div>

                  <div id="layout-editor" class="border-2 border-dashed border-slate-300 rounded-lg bg-slate-50 relative h-80">
                    <div class="absolute inset-0" id="layout-canvas">
                      <div class="text-center text-slate-500 py-20">
                        Select a layout type to start designing
                      </div>
                    </div>
                    
                    <!-- Stage Marker -->
                    <div id="stage-marker" class="absolute top-4 left-1/2 transform -translate-x-1/2 bg-slate-800 text-white px-4 py-2 rounded-lg text-sm font-medium opacity-75">
                      STAGE
                    </div>
                  </div>

                  <!-- Layout Tools -->
                  <div class="mt-4 flex justify-center">
                    <div class="flex space-x-2">
                      <button type="button" onclick="addTable()" class="px-4 py-2 text-sm bg-amber-100 text-amber-800 rounded-lg hover:bg-amber-200 flex items-center space-x-2">
                        <span>➕</span>
                        <span>Add Table</span>
                      </button>
                      <button type="button" onclick="addSeatRow()" class="px-4 py-2 text-sm bg-green-100 text-green-800 rounded-lg hover:bg-green-200 flex items-center space-x-2">
                        <span>➕</span>
                        <span>Add Row</span>
                      </button>
                      <button type="button" onclick="addGeneralArea()" class="px-4 py-2 text-sm bg-blue-100 text-blue-800 rounded-lg hover:bg-blue-200 flex items-center space-x-2">
                        <span>➕</span>
                        <span>Add Area</span>
                      </button>
                      <button type="button" onclick="clearLayout()" class="px-4 py-2 text-sm bg-red-100 text-red-800 rounded-lg hover:bg-red-200 flex items-center space-x-2">
                        <span>🗑️</span>
                        <span>Clear</span>
                      </button>
                    </div>
                  </div>
                </div>

                <!-- Footer Actions -->
                <div class="flex-shrink-0 p-6 bg-slate-50 border-t border-slate-200">
                  <div class="flex justify-end space-x-4">
                    <button
                      type="button"
                      onclick="closeSeatingMapModal()"
                      class="px-6 py-3 border border-slate-300 text-slate-700 rounded-xl hover:bg-white font-medium transition-colors duration-200"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      class="px-8 py-3 bg-gradient-to-r from-slate-800 to-slate-900 text-white rounded-xl hover:from-slate-900 hover:to-black font-medium transition-all duration-200"
                    >
                      <span id="seating-submit-text">Create Seating Map</span>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- Embed Widget Modal -->
    <div id="embed-widget-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm hidden z-50">
      <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-3xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col">
          <!-- Header -->
          <div class="px-8 py-6 border-b border-slate-200 bg-gradient-to-r from-blue-50 to-indigo-50">
            <div class="flex items-center justify-between">
              <div class="flex items-center space-x-3">
                <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
                  <span class="text-2xl">🎫</span>
                </div>
                <div>
                  <h3 class="text-2xl font-semibold text-slate-900">Embed Widget</h3>
                  <p class="text-slate-600">Get your customizable ticket widget</p>
                </div>
              </div>
              <button
                type="button"
                onclick="closeEmbedWidgetModal()"
                class="text-slate-400 hover:text-slate-600 transition-colors"
              >
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
              </button>
            </div>
          </div>

          <!-- Content -->
          <div class="flex-1 overflow-y-auto p-8">
            <div class="space-y-6">
              <!-- Instructions -->
              <div class="bg-blue-50 rounded-xl p-6 border border-blue-200">
                <h4 class="font-semibold text-blue-900 mb-2">How to Use</h4>
                <ul class="text-blue-800 text-sm space-y-1">
                  <li>• Click "Open Customization Page" to customize your widget's appearance</li>
                  <li>• Copy the generated embed code</li>
                  <li>• Paste it into your website's HTML</li>
                  <li>• The widget will automatically match your site's design</li>
                </ul>
              </div>

              <!-- Features -->
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="flex items-center space-x-3 p-4 bg-green-50 rounded-lg border border-green-200">
                  <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                  </svg>
                  <span class="text-green-800 text-sm">Fully customizable colors</span>
                </div>
                <div class="flex items-center space-x-3 p-4 bg-green-50 rounded-lg border border-green-200">
                  <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                  </svg>
                  <span class="text-green-800 text-sm">Mobile responsive</span>
                </div>
                <div class="flex items-center space-x-3 p-4 bg-green-50 rounded-lg border border-green-200">
                  <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                  </svg>
                  <span class="text-green-800 text-sm">Auto-resizing iframe</span>
                </div>
                <div class="flex items-center space-x-3 p-4 bg-green-50 rounded-lg border border-green-200">
                  <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                  </svg>
                  <span class="text-green-800 text-sm">Secure payment processing</span>
                </div>
              </div>

              <!-- Quick Links -->
              <div class="space-y-4">
                <h4 class="text-lg font-semibold text-slate-900">Quick Access</h4>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <!-- Customization Page -->
                  <div class="border border-slate-200 rounded-xl p-6 hover:border-slate-300 transition-colors">
                    <h5 class="font-semibold text-slate-900 mb-2">Customize Widget</h5>
                    <p class="text-slate-600 text-sm mb-4">Open the full customization interface with live preview</p>
                    <button
                      onclick="openCustomizationPage()"
                      class="w-full bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg font-medium transition-colors"
                    >
                      Open Customization Page
                    </button>
                  </div>

                  <!-- Direct Widget Link -->
                  <div class="border border-slate-200 rounded-xl p-6 hover:border-slate-300 transition-colors">
                    <h5 class="font-semibold text-slate-900 mb-2">Direct Widget Link</h5>
                    <p class="text-slate-600 text-sm mb-4">Link directly to your ticket widget</p>
                    <button
                      onclick="copyDirectLink()"
                      class="w-full bg-slate-600 hover:bg-slate-700 text-white px-4 py-2 rounded-lg font-medium transition-colors"
                    >
                      Copy Widget Link
                    </button>
                  </div>
                </div>
              </div>

              <!-- Basic Embed Code -->
              <div class="space-y-3">
                <h4 class="text-lg font-semibold text-slate-900">Basic Embed Code</h4>
                <p class="text-slate-600 text-sm">Copy this code and paste it into your website:</p>
                <div class="bg-slate-900 rounded-lg p-4 overflow-x-auto">
                  <pre class="text-green-400 text-sm font-mono" id="basic-embed-preview">Loading...</pre>
                </div>
                <button
                  onclick="copyBasicEmbedCode()"
                  class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
                >
                  Copy Basic Code
                </button>
              </div>
            </div>
          </div>

          <!-- Footer -->
          <div class="px-8 py-6 border-t border-slate-200 bg-slate-50">
            <div class="flex justify-end space-x-3">
              <button
                type="button"
                onclick="closeEmbedWidgetModal()"
                class="px-6 py-2 text-slate-700 bg-white border border-slate-300 rounded-lg hover:bg-slate-50 transition-colors"
              >
                Close
              </button>
              <button
                type="button"
                onclick="openCustomizationPage()"
                class="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
              >
                Customize Widget
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</Layout>

<script>
  import { supabase } from '../../../lib/supabase';

  // Global variables for layout editor
  let layoutItems = [];
  let selectedItem = null;
  let isDragging = false;
  let dragOffset = { x: 0, y: 0 };

  const eventId = window.location.pathname.split('/')[2];
  console.log('Event ID extracted from URL:', eventId);
  let currentEvent = null;
  let currentTicketTypeId = null;
  let currentTab = 'tickets';
  let organizationId = null;

  // DOM Elements
  const userNameSpan = document.getElementById('user-name');
  const logoutBtn = document.getElementById('logout-btn');
  const ticketTypeModal = document.getElementById('ticket-type-modal');
  const ticketTypeForm = document.getElementById('ticket-type-form');

  // Load user data
  async function loadUserData() {
    const { data: { session } } = await supabase.auth.getSession();
    if (!session) {
      return null;
    }

    const { data: user, error: userError } = await supabase
      .from('users')
      .select('name, email, organization_id, role')
      .eq('id', session.user.id)
      .single();

    if (userError) {
      console.error('Error loading user:', userError);
      throw userError;
    }

    if (user) {
      userNameSpan.textContent = user.name || user.email;
      organizationId = user.organization_id;
      
      console.log('User loaded:', user);
      console.log('Organization ID set to:', organizationId);
      
      // Check if user is admin and show admin dashboard link
      if (user.role === 'admin') {
        const adminLink = document.getElementById('admin-dashboard-link');
        if (adminLink) {
          adminLink.classList.remove('hidden');
        }
      }
    }

    return { session, user };
  }

  // Check authentication
  async function checkAuth() {
    try {
      const result = await loadUserData();
      if (!result || !result.session) {
        console.log('No session found, redirecting to login');
        window.location.href = '/login';
        return null;
      }
      console.log('Authentication successful, session:', result.session);
      return result.session;
    } catch (error) {
      console.error('Error in checkAuth:', error);
      window.location.href = '/login';
      return null;
    }
  }

  // Load event details
  async function loadEvent() {
    try {
      console.log('Loading event with ID:', eventId);
      
      const { data: event, error } = await supabase
        .from('events')
        .select(`
          *,
          venues(name, address)
        `)
        .eq('id', eventId)
        .single();

      if (error) {
        console.error('Error loading event:', error);
        throw error;
      }

      if (!event) {
        console.error('No event found with ID:', eventId);
        throw new Error('Event not found');
      }

      console.log('Event loaded successfully:', event);
      
      // Check if user has permission to manage this event
      const { data: { user } } = await supabase.auth.getUser();
      const { data: userProfile } = await supabase
        .from('users')
        .select('organization_id, role')
        .eq('id', user.id)
        .single();
        
      const isAdmin = userProfile?.role === 'admin';
      const canManage = isAdmin || 
                       event.created_by === user.id || 
                       event.organization_id === userProfile?.organization_id;
      
      if (!canManage) {
        console.error('User does not have permission to manage this event');
        alert('You do not have permission to manage this event.');
        window.location.href = '/dashboard';
        return;
      }
      
      currentEvent = event;

      // Update page title
      document.title = `${event.title} - Event Management`;
      document.getElementById('event-title').textContent = event.title;
      document.getElementById('event-venue').textContent = event.venues?.name || event.venue;
      document.getElementById('event-date').textContent = new Date(event.start_time).toLocaleDateString('en-US', {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: 'numeric',
        minute: '2-digit'
      });
      document.getElementById('event-description').textContent = event.description || 'No description provided';
      document.getElementById('preview-link').href = `/e/${event.slug}`;

      await loadEventStats();
      await loadTicketTypes();

    } catch (error) {
      console.error('Error loading event:', error);
      alert('Error loading event. Please check the URL and try again.');
      window.location.href = '/dashboard';
    }
  }

  // Load event statistics
  async function loadEventStats() {
    try {
      // Get ticket sales data
      const { data: tickets, error } = await supabase
        .from('tickets')
        .select('price, checked_in')
        .eq('event_id', eventId);

      if (error) throw error;

      const ticketsSold = tickets.length;
      const checkedIn = tickets.filter(t => t.checked_in).length;
      const totalRevenue = tickets.reduce((sum, t) => sum + t.price, 0);

      document.getElementById('tickets-sold').textContent = ticketsSold.toLocaleString();
      document.getElementById('checked-in').textContent = checkedIn.toLocaleString();
      document.getElementById('total-revenue').textContent = `$${totalRevenue.toFixed(2)}`;
      document.getElementById('net-revenue').textContent = `$${(totalRevenue * 0.97).toFixed(2)}`; // Assume 3% platform fee

      // Get available tickets
      const { data: ticketTypes } = await supabase
        .from('ticket_types')
        .select('quantity_available, quantity_sold')
        .eq('event_id', eventId);

      const totalAvailable = ticketTypes
        ?.filter(tt => tt.quantity_available)
        ?.reduce((sum, tt) => sum + (tt.quantity_available - tt.quantity_sold), 0) || 'Unlimited';

      document.getElementById('tickets-available').textContent = totalAvailable === 'Unlimited' ? '∞' : totalAvailable.toLocaleString();

    } catch (error) {
      console.error('Error loading event stats:', error);
    }
  }

  // Load ticket types
  async function loadTicketTypes() {
    try {
      const { data: ticketTypes, error } = await supabase
        .from('ticket_types')
        .select('*')
        .eq('event_id', eventId)
        .order('sort_order', { ascending: true });

      if (error) throw error;

      const container = document.getElementById('ticket-types-list');
      const emptyState = document.getElementById('ticket-types-empty');

      if (ticketTypes.length === 0) {
        container.classList.add('hidden');
        emptyState.classList.remove('hidden');
        return;
      }

      container.classList.remove('hidden');
      emptyState.classList.add('hidden');

      container.innerHTML = ticketTypes.map(ticketType => `
        <div class="bg-slate-50 rounded-2xl p-6 border border-slate-200">
          <div class="flex justify-between items-start">
            <div class="flex-1">
              <div class="flex items-center space-x-3 mb-3">
                <h3 class="text-xl font-semibold text-slate-900">${ticketType.name}</h3>
                <span class="px-3 py-1 bg-slate-200 text-slate-700 rounded-full text-sm font-medium">
                  $${ticketType.price.toFixed(2)}
                </span>
                ${!ticketType.is_active ? '<span class="px-3 py-1 bg-red-100 text-red-700 rounded-full text-sm font-medium">Inactive</span>' : ''}
              </div>
              
              ${ticketType.description ? `<p class="text-slate-600 mb-3">${ticketType.description}</p>` : ''}
              
              <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                <div>
                  <span class="block text-slate-500">Sold</span>
                  <span class="font-semibold text-slate-900">${ticketType.quantity_sold || 0}</span>
                </div>
                <div>
                  <span class="block text-slate-500">Available</span>
                  <span class="font-semibold text-slate-900">
                    ${ticketType.quantity_available ? (ticketType.quantity_available - (ticketType.quantity_sold || 0)) : '∞'}
                  </span>
                </div>
                <div>
                  <span class="block text-slate-500">Revenue</span>
                  <span class="font-semibold text-slate-900">$${((ticketType.quantity_sold || 0) * ticketType.price).toFixed(2)}</span>
                </div>
                <div>
                  <span class="block text-slate-500">Status</span>
                  <span class="font-semibold ${ticketType.is_active ? 'text-emerald-600' : 'text-red-600'}">
                    ${ticketType.is_active ? 'Active' : 'Inactive'}
                  </span>
                </div>
              </div>
            </div>
            
            <div class="flex space-x-2 ml-6">
              <button
                onclick="editTicketType('${ticketType.id}')"
                class="text-slate-600 hover:text-slate-900 font-medium transition-colors duration-200"
              >
                Edit
              </button>
              <button
                onclick="toggleTicketType('${ticketType.id}', ${!ticketType.is_active})"
                class="text-slate-600 hover:text-slate-900 font-medium transition-colors duration-200"
              >
                ${ticketType.is_active ? 'Deactivate' : 'Activate'}
              </button>
              <button
                onclick="deleteTicketType('${ticketType.id}')"
                class="text-red-600 hover:text-red-800 font-medium transition-colors duration-200"
              >
                Delete
              </button>
            </div>
          </div>
        </div>
      `).join('');

    } catch (error) {
      console.error('Error loading ticket types:', error);
    }
  }

  // Tab switching
  function switchTab(tabName) {
    currentTab = tabName;
    
    // Update tab buttons
    document.querySelectorAll('.tab-button').forEach(btn => {
      btn.classList.remove('border-slate-800', 'text-slate-800');
      btn.classList.add('border-transparent', 'text-slate-500');
    });
    
    document.getElementById(`tab-${tabName}`).classList.remove('border-transparent', 'text-slate-500');
    document.getElementById(`tab-${tabName}`).classList.add('border-slate-800', 'text-slate-800');

    // Update content
    document.querySelectorAll('.tab-content').forEach(content => {
      content.classList.add('hidden');
    });
    
    document.getElementById(`content-${tabName}`).classList.remove('hidden');

    // Load tab-specific content
    loadTabContent(tabName);
  }

  // Load content for specific tab
  async function loadTabContent(tabName) {
    switch (tabName) {
      case 'tickets':
        await loadTicketTypes();
        break;
      case 'venue':
        await loadVenueContent();
        break;
      case 'analytics':
        await loadAnalyticsContent();
        break;
      case 'orders':
        await loadSalesContent();
        break;
      case 'attendees':
        await loadAttendeesContent();
        break;
      case 'presale':
        await loadPresaleCodesContent();
        break;
      case 'discount':
        await loadDiscountCodesContent();
        break;
      case 'addons':
        await loadAddonsContent();
        break;
      case 'settings':
        await loadSettingsContent();
        break;
    }
  }

  // Placeholder functions for other tabs
  async function loadVenueContent() {
    try {
      console.log('Loading venue content for event:', eventId, 'organization:', organizationId);
      
      // Ensure user is loaded and organizationId is available
      if (!organizationId) {
        console.log('Organization ID not available, loading user first...');
        await loadUserData();
        
        if (!organizationId) {
          throw new Error('Unable to load organization information. Please refresh the page and try again.');
        }
      }
      
      // Load current event seating configuration
      const { data: event, error: eventError } = await supabase
        .from('events')
        .select('seating_type, seating_map_id')
        .eq('id', eventId)
        .single();

      if (eventError) throw eventError;
      
      console.log('Event seating config:', event);

      // Load all available seating maps for this organization
      const { data: seatingMaps, error: mapsError } = await supabase
        .from('seating_maps')
        .select('*')
        .eq('organization_id', organizationId)
        .order('name');

      if (mapsError) throw mapsError;
      
      console.log('Seating maps loaded:', seatingMaps);

      // Update seating type select
      const seatingTypeSelect = document.getElementById('seating-type');
      if (event.seating_type) {
        seatingTypeSelect.value = event.seating_type;
      }

      // Update seating map select
      const seatingMapSelect = document.getElementById('seating-map-select');
      seatingMapSelect.innerHTML = '<option value="">No seating map</option>';
      
      seatingMaps.forEach(map => {
        const option = document.createElement('option');
        option.value = map.id;
        option.textContent = `${map.name} (${map.total_capacity} seats)`;
        if (event.seating_map_id === map.id) {
          option.selected = true;
        }
        seatingMapSelect.appendChild(option);
      });

      // Render seating maps grid
      const seatingMapsGrid = document.getElementById('seating-maps-grid');
      seatingMapsGrid.innerHTML = '';

      if (seatingMaps.length === 0) {
        seatingMapsGrid.innerHTML = `
          <div class="col-span-full text-center py-12">
            <div class="text-slate-400 text-lg mb-4">No seating maps created yet</div>
            <button onclick="openSeatingMapModal()" class="bg-slate-800 text-white px-6 py-3 rounded-xl font-medium hover:bg-slate-900 transition-colors">
              Create Your First Seating Map
            </button>
          </div>
        `;
      } else {
        seatingMaps.forEach(map => {
          const mapCard = document.createElement('div');
          mapCard.className = 'bg-white rounded-xl border border-slate-200 p-6 hover:shadow-lg transition-shadow';
          mapCard.innerHTML = `
            <div class="flex justify-between items-start mb-4">
              <div>
                <h4 class="text-lg font-medium text-slate-900">${map.name}</h4>
                <p class="text-sm text-slate-600">${map.venue_name}</p>
              </div>
              <div class="flex space-x-2">
                <button onclick="editSeatingMap('${map.id}')" class="text-slate-600 hover:text-slate-800 p-1">
                  <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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                  </svg>
                </button>
                <button onclick="deleteSeatingMap('${map.id}')" class="text-red-600 hover:text-red-800 p-1">
                  <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                  </svg>
                </button>
              </div>
            </div>
            <div class="text-sm text-slate-600 mb-4">
              <div class="flex justify-between">
                <span>Total Capacity:</span>
                <span class="font-medium">${map.total_capacity}</span>
              </div>
              <div class="flex justify-between">
                <span>Created:</span>
                <span>${new Date(map.created_at).toLocaleDateString()}</span>
              </div>
            </div>
            <div class="flex space-x-3">
              <button onclick="previewSeatingMap('${map.id}')" class="flex-1 bg-slate-100 text-slate-700 px-4 py-2 rounded-lg hover:bg-slate-200 transition-colors font-medium">
                Preview
              </button>
              <button onclick="useSeatingMap('${map.id}')" class="flex-1 bg-slate-800 text-white px-4 py-2 rounded-lg hover:bg-slate-900 transition-colors font-medium">
                Use for Event
              </button>
            </div>
          `;
          seatingMapsGrid.appendChild(mapCard);
        });
      }

      // Show preview if a seating map is selected
      if (event.seating_map_id) {
        await previewSeatingMap(event.seating_map_id);
      }

    } catch (error) {
      console.error('Error loading venue content:', error);
      document.getElementById('venue-content').innerHTML = `
        <div class="text-red-600 bg-red-50 p-4 rounded-lg">
          <p class="font-medium">Error loading venue content</p>
          <p class="text-sm">${error.message}</p>
        </div>
      `;
    }
  }

  async function loadSalesContent(filters = {}) {
    try {
      // Load ticket types for filter dropdown
      await loadTicketTypesForFilter();

      // Build query with filters
      let query = supabase
        .from('tickets')
        .select(`
          *,
          ticket_types (
            name,
            price
          )
        `)
        .eq('event_id', eventId);

      // Apply filters
      if (filters.email) {
        query = query.ilike('purchaser_email', `%${filters.email}%`);
      }
      if (filters.name) {
        query = query.ilike('purchaser_name', `%${filters.name}%`);
      }
      if (filters.status) {
        switch (filters.status) {
          case 'active':
            query = query.eq('refund_status', 'none').eq('checked_in', false);
            break;
          case 'checked_in':
            query = query.eq('checked_in', true);
            break;
          case 'refund_requested':
            query = query.eq('refund_status', 'requested');
            break;
          case 'refund_completed':
            query = query.eq('refund_status', 'completed');
            break;
        }
      }
      if (filters.ticketType) {
        query = query.eq('ticket_type_id', filters.ticketType);
      }

      query = query.order('created_at', { ascending: false });

      const { data: tickets, error } = await query;

      if (error) throw error;

      // Update results count
      document.getElementById('orders-results-count').textContent = 
        `${tickets.length} ticket${tickets.length !== 1 ? 's' : ''} found`;

      if (tickets.length === 0) {
        document.getElementById('orders-content').innerHTML = `
          <div class="text-center py-8">
            <svg class="w-16 h-16 mx-auto text-slate-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="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"></path>
            </svg>
            <p class="text-slate-500 text-lg">No tickets found</p>
            <p class="text-slate-400 text-sm mt-1">Try adjusting your search filters</p>
          </div>
        `;
        return;
      }

      const ticketsHtml = `
        <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
          <div class="px-6 py-4 border-b border-slate-200 bg-slate-50">
            <h3 class="text-lg font-semibold text-slate-900">Tickets Found (${tickets.length})</h3>
          </div>
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead class="bg-slate-50 border-b border-slate-200">
                <tr>
                  <th class="text-left py-3 px-4 font-medium text-slate-700">Ticket ID</th>
                  <th class="text-left py-3 px-4 font-medium text-slate-700">Customer</th>
                  <th class="text-left py-3 px-4 font-medium text-slate-700">Type</th>
                  <th class="text-left py-3 px-4 font-medium text-slate-700">Price</th>
                  <th class="text-left py-3 px-4 font-medium text-slate-700">Seat</th>
                  <th class="text-left py-3 px-4 font-medium text-slate-700">Status</th>
                  <th class="text-left py-3 px-4 font-medium text-slate-700">Purchase Date</th>
                  <th class="text-left py-3 px-4 font-medium text-slate-700">Actions</th>
                </tr>
              </thead>
              <tbody class="divide-y divide-slate-200">
                ${tickets.map(ticket => `
                  <tr class="hover:bg-slate-50">
                    <td class="py-3 px-4">
                      <div class="font-mono text-sm text-slate-600">${ticket.uuid.substring(0, 8)}...</div>
                    </td>
                    <td class="py-3 px-4">
                      <div class="text-sm">
                        <div class="font-medium text-slate-900">${ticket.purchaser_name || 'Not provided'}</div>
                        <div class="text-slate-500">${ticket.purchaser_email}</div>
                      </div>
                    </td>
                    <td class="py-3 px-4">
                      <span class="text-sm text-slate-700">${ticket.ticket_types?.name || 'General'}</span>
                    </td>
                    <td class="py-3 px-4">
                      <span class="text-sm font-medium text-slate-900">$${ticket.price}</span>
                    </td>
                    <td class="py-3 px-4">
                      <span class="text-sm text-slate-700">${ticket.seat_number || 'General Admission'}</span>
                      ${ticket.section ? `<br><span class="text-xs text-slate-500">${ticket.section}</span>` : ''}
                    </td>
                    <td class="py-3 px-4">
                      <div class="flex flex-col space-y-1">
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${ticket.checked_in ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}">
                          ${ticket.checked_in ? 'Checked In' : 'Not Checked In'}
                        </span>
                        ${ticket.refund_status && ticket.refund_status !== 'none' ? `
                          <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                            Refund: ${ticket.refund_status.replace('_', ' ')}
                          </span>
                        ` : ''}
                      </div>
                    </td>
                    <td class="py-3 px-4">
                      <span class="text-sm text-slate-700">${new Date(ticket.created_at).toLocaleDateString()}</span>
                      <br>
                      <span class="text-xs text-slate-500">${new Date(ticket.created_at).toLocaleTimeString()}</span>
                    </td>
                    <td class="py-3 px-4 w-40">
                      <div class="flex items-center justify-start space-x-2 min-h-[32px]">
                        <button 
                          onclick="viewTicket('${ticket.uuid}')"
                          class="text-blue-600 hover:text-blue-900 text-sm font-medium whitespace-nowrap"
                        >
                          View
                        </button>
                        <div class="w-20 flex justify-center">
                          ${!ticket.checked_in ? `
                            <button 
                              onclick="checkInTicket('${ticket.id}')"
                              class="text-green-600 hover:text-green-900 text-sm font-medium whitespace-nowrap"
                            >
                              Check In
                            </button>
                          ` : `
                            <span class="text-xs text-green-600 font-medium">✓ Checked</span>
                          `}
                        </div>
                        <div class="w-16 flex justify-end">
                          ${ticket.refund_status === 'none' ? `
                            <div class="relative inline-block text-left">
                              <button 
                                onclick="toggleRefundDropdown('${ticket.id}')"
                                class="text-slate-500 hover:text-slate-700 text-xs border border-slate-300 hover:border-slate-400 rounded px-2 py-1 transition-colors whitespace-nowrap"
                              >
                                ⋯ More
                              </button>
                              <div id="refund-dropdown-${ticket.id}" class="hidden absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg z-10 border border-slate-200">
                                <div class="py-1">
                                  <button 
                                    onclick="initiateRefund('${ticket.id}', '${ticket.price}', '${ticket.purchaser_name || ticket.purchaser_email}')"
                                    class="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors"
                                  >
                                    🔄 Process Refund
                                  </button>
                                </div>
                              </div>
                            </div>
                          ` : `
                            <span class="text-xs text-slate-500 capitalize whitespace-nowrap">${ticket.refund_status.replace('_', ' ')}</span>
                          `}
                        </div>
                      </div>
                    </td>
                  </tr>
                `).join('')}
              </tbody>
            </table>
          </div>
        </div>
      `;

      document.getElementById('orders-content').innerHTML = ticketsHtml;
    } catch (error) {
      console.error('Error loading tickets:', error);
      document.getElementById('orders-content').innerHTML = `
        <div class="text-red-600 bg-red-50 p-4 rounded-lg">
          <p class="font-medium">Error loading tickets</p>
          <p class="text-sm">${error.message}</p>
        </div>
      `;
      document.getElementById('orders-results-count').textContent = 'Error loading tickets';
    }
  }

  async function loadTicketTypesForFilter() {
    try {
      const { data: ticketTypes, error } = await supabase
        .from('ticket_types')
        .select('id, name')
        .eq('event_id', eventId)
        .eq('is_active', true)
        .order('name');

      if (error) throw error;

      const select = document.getElementById('sales-filter-ticket-type');
      if (select) {
        select.innerHTML = '<option value="">All Types</option>' +
          ticketTypes.map(type => 
            `<option value="${type.id}">${type.name}</option>`
          ).join('');
      }
    } catch (error) {
      console.error('Error loading ticket types for filter:', error);
    }
  }

  function searchSales() {
    const filters = {
      email: document.getElementById('sales-search-email').value.trim(),
      name: document.getElementById('sales-search-name').value.trim(),
      status: document.getElementById('sales-filter-status').value,
      ticketType: document.getElementById('sales-filter-ticket-type').value
    };

    loadSalesContent(filters);
  }

  function clearSalesFilters() {
    document.getElementById('sales-search-email').value = '';
    document.getElementById('sales-search-name').value = '';
    document.getElementById('sales-filter-status').value = '';
    document.getElementById('sales-filter-ticket-type').value = '';
    
    loadSalesContent();
  }

  // Add search on Enter key
  document.addEventListener('DOMContentLoaded', function() {
    const searchInputs = ['sales-search-email', 'sales-search-name'];
    searchInputs.forEach(inputId => {
      const input = document.getElementById(inputId);
      if (input) {
        input.addEventListener('keypress', function(e) {
          if (e.key === 'Enter') {
            searchSales();
          }
        });
      }
    });
  });

  async function loadAnalyticsContent() {
    try {
      // Show loading state initially
      document.getElementById('analytics-loading').classList.remove('hidden');
      document.getElementById('analytics-content').classList.add('hidden');
      document.getElementById('analytics-no-data').classList.add('hidden');
      
      // Get all tickets for this event to calculate analytics
      const { data: tickets, error } = await supabase
        .from('tickets')
        .select(`
          *,
          ticket_types (
            name,
            price
          )
        `)
        .eq('event_id', eventId);

      if (error) throw error;

      // Calculate analytics
      const totalTickets = tickets.length;
      const grossRevenue = tickets.reduce((sum, ticket) => sum + parseFloat(ticket.price), 0);
      const checkedInCount = tickets.filter(t => t.checked_in).length;
      const refundedTickets = tickets.filter(t => t.refund_status !== 'none');
      const refundedAmount = refundedTickets.reduce((sum, ticket) => sum + (parseFloat(ticket.refund_amount) || 0), 0);
      const netRevenue = grossRevenue - refundedAmount;
      const avgTicketPrice = totalTickets > 0 ? grossRevenue / totalTickets : 0;
      
      // Calculate platform fee (2.5% + $1.50 per ticket)
      const platformFee = tickets.reduce((sum, ticket) => {
        const ticketFee = (parseFloat(ticket.price) * 0.025) + 1.50;
        return sum + ticketFee;
      }, 0);
      
      const organizerPayout = netRevenue - platformFee;

      // Update analytics display
      document.getElementById('analytics-gross-revenue').textContent = `$${grossRevenue.toFixed(2)}`;
      document.getElementById('analytics-net-revenue').textContent = `$${organizerPayout.toFixed(2)}`;
      document.getElementById('analytics-avg-price').textContent = `$${avgTicketPrice.toFixed(2)}`;
      
      // Conversion rate (assuming 100% since we don't track visits yet)
      const conversionRate = totalTickets > 0 ? '100%' : '0%';
      document.getElementById('analytics-conversion-rate').textContent = conversionRate;

      // Update ticket performance table
      const ticketTypeMap = new Map();
      tickets.forEach(ticket => {
        const typeName = ticket.ticket_types?.name || 'General';
        if (!ticketTypeMap.has(typeName)) {
          ticketTypeMap.set(typeName, {
            name: typeName,
            sold: 0,
            revenue: 0,
            price: parseFloat(ticket.ticket_types?.price || ticket.price)
          });
        }
        const typeData = ticketTypeMap.get(typeName);
        typeData.sold++;
        typeData.revenue += parseFloat(ticket.price);
      });

      const ticketPerformanceHtml = Array.from(ticketTypeMap.values()).map(type => `
        <tr>
          <td class="py-3 text-slate-900 font-medium">${type.name}</td>
          <td class="py-3 text-right text-slate-700">${type.sold}</td>
          <td class="py-3 text-right text-slate-700">--</td>
          <td class="py-3 text-right text-slate-900 font-medium">$${type.revenue.toFixed(2)}</td>
        </tr>
      `).join('');

      document.getElementById('ticket-type-performance').innerHTML = ticketPerformanceHtml;

      // Update recent sales
      const recentTickets = tickets
        .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
        .slice(0, 5);

      const recentSalesHtml = recentTickets.map(ticket => `
        <div class="flex justify-between items-center py-3 border-b border-slate-100 last:border-b-0">
          <div>
            <div class="font-medium text-slate-900">${ticket.purchaser_name || 'Anonymous'}</div>
            <div class="text-sm text-slate-500">${ticket.ticket_types?.name || 'General'}</div>
          </div>
          <div class="text-right">
            <div class="font-medium text-slate-900">$${ticket.price}</div>
            <div class="text-sm text-slate-500">${new Date(ticket.created_at).toLocaleDateString()}</div>
          </div>
        </div>
      `).join('');

      document.getElementById('recent-sales-list').innerHTML = recentSalesHtml || '<p class="text-slate-500 text-sm">No recent sales</p>';

      // Update sales insights
      const last24hSales = tickets.filter(ticket => {
        const ticketDate = new Date(ticket.created_at);
        const yesterday = new Date();
        yesterday.setDate(yesterday.getDate() - 1);
        return ticketDate > yesterday;
      }).length;

      document.getElementById('sales-velocity').textContent = last24hSales;

      // Simple trend calculation
      const lastWeekSales = tickets.filter(ticket => {
        const ticketDate = new Date(ticket.created_at);
        const lastWeek = new Date();
        lastWeek.setDate(lastWeek.getDate() - 7);
        return ticketDate > lastWeek;
      }).length;

      const prevWeekSales = tickets.filter(ticket => {
        const ticketDate = new Date(ticket.created_at);
        const twoWeeksAgo = new Date();
        twoWeeksAgo.setDate(twoWeeksAgo.getDate() - 14);
        const lastWeek = new Date();
        lastWeek.setDate(lastWeek.getDate() - 7);
        return ticketDate > twoWeeksAgo && ticketDate <= lastWeek;
      }).length;

      let trendIndicator = '→';
      if (lastWeekSales > prevWeekSales) trendIndicator = '↗';
      else if (lastWeekSales < prevWeekSales) trendIndicator = '↘';

      document.getElementById('sales-trend').textContent = trendIndicator;

      // Days until event
      const eventDate = new Date(await getEventDate());
      const today = new Date();
      const daysUntil = Math.ceil((eventDate - today) / (1000 * 60 * 60 * 24));
      document.getElementById('days-until-event').textContent = daysUntil > 0 ? daysUntil : '0';

      // Hide loading state and show analytics content (including upgrade banner)
      document.getElementById('analytics-loading').classList.add('hidden');
      document.getElementById('analytics-content').classList.remove('hidden');
      document.getElementById('analytics-no-data').classList.add('hidden');

    } catch (error) {
      console.error('Error loading analytics:', error);
      // Hide loading state and show no-data state on error
      document.getElementById('analytics-loading').classList.add('hidden');
      document.getElementById('analytics-content').classList.add('hidden');
      document.getElementById('analytics-no-data').classList.remove('hidden');
    }
  }

  async function getEventDate() {
    try {
      const { data: event, error } = await supabase
        .from('events')
        .select('start_time')
        .eq('id', eventId)
        .single();
      
      return event?.start_time || new Date();
    } catch (error) {
      return new Date();
    }
  }

  async function loadAttendeesContent() {
    try {
      const { data: tickets, error } = await supabase
        .from('tickets')
        .select(`
          *,
          ticket_types (
            name,
            price
          ),
          purchase_attempts (
            id,
            purchaser_email,
            purchaser_name,
            created_at
          )
        `)
        .eq('event_id', eventId)
        .order('created_at', { ascending: false });

      if (error) throw error;

      if (tickets.length === 0) {
        document.getElementById('attendees-content').innerHTML = `
          <div class="text-center py-12">
            <svg class="w-16 h-16 mx-auto text-slate-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
            </svg>
            <p class="text-slate-500 text-lg">No attendees yet</p>
            <p class="text-slate-400 text-sm mt-1">Attendees will appear here once tickets are purchased</p>
          </div>
        `;
        return;
      }

      // Group tickets by purchaser email
      const attendeeMap = new Map();
      tickets.forEach(ticket => {
        const email = ticket.purchaser_email;
        if (!attendeeMap.has(email)) {
          attendeeMap.set(email, {
            name: ticket.purchaser_name || 'Not provided',
            email: email,
            tickets: [],
            totalSpent: 0,
            checkedIn: 0,
            refunded: 0
          });
        }
        const attendee = attendeeMap.get(email);
        attendee.tickets.push(ticket);
        attendee.totalSpent += parseFloat(ticket.price);
        if (ticket.checked_in) attendee.checkedIn++;
        if (ticket.refund_status !== 'none') attendee.refunded++;
      });

      const attendees = Array.from(attendeeMap.values());

      const attendeesHtml = `
        <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
          <div class="px-6 py-4 border-b border-slate-200 bg-slate-50 flex justify-between items-center">
            <h3 class="text-lg font-semibold text-slate-900">Attendees (${attendees.length})</h3>
            <div class="flex space-x-2">
              <button
                onclick="exportGuestList()"
                class="text-sm bg-slate-600 hover:bg-slate-700 text-white px-4 py-2 rounded-lg transition-colors"
              >
                Export CSV
              </button>
            </div>
          </div>
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead class="bg-slate-50 border-b border-slate-200">
                <tr>
                  <th class="text-left py-3 px-4 font-medium text-slate-700">Name</th>
                  <th class="text-left py-3 px-4 font-medium text-slate-700">Email</th>
                  <th class="text-left py-3 px-4 font-medium text-slate-700">Tickets</th>
                  <th class="text-left py-3 px-4 font-medium text-slate-700">Total Spent</th>
                  <th class="text-left py-3 px-4 font-medium text-slate-700">Check-in Status</th>
                  <th class="text-left py-3 px-4 font-medium text-slate-700">Actions</th>
                </tr>
              </thead>
              <tbody class="divide-y divide-slate-200">
                ${attendees.map(attendee => `
                  <tr class="hover:bg-slate-50">
                    <td class="py-3 px-4">
                      <div class="font-medium text-slate-900">${attendee.name}</div>
                    </td>
                    <td class="py-3 px-4">
                      <div class="text-sm text-slate-600">${attendee.email}</div>
                    </td>
                    <td class="py-3 px-4">
                      <div class="text-sm">
                        <span class="font-medium">${attendee.tickets.length}</span> tickets
                        ${attendee.refunded > 0 ? `<br><span class="text-xs text-red-600">${attendee.refunded} refunded</span>` : ''}
                      </div>
                    </td>
                    <td class="py-3 px-4">
                      <span class="text-sm font-medium text-slate-900">$${attendee.totalSpent.toFixed(2)}</span>
                    </td>
                    <td class="py-3 px-4">
                      <div class="text-sm">
                        ${attendee.checkedIn > 0 ? `
                          <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                            ${attendee.checkedIn}/${attendee.tickets.length} Checked In
                          </span>
                        ` : `
                          <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                            Not Checked In
                          </span>
                        `}
                      </div>
                    </td>
                    <td class="py-3 px-4">
                      <div class="flex space-x-2">
                        <button 
                          onclick="viewAttendeeDetails('${attendee.email}')"
                          class="text-blue-600 hover:text-blue-900 text-sm font-medium"
                        >
                          View Details
                        </button>
                        ${attendee.refunded === 0 ? `
                          <button 
                            onclick="refundAttendee('${attendee.email}')"
                            class="text-red-600 hover:text-red-900 text-sm font-medium"
                          >
                            Refund All
                          </button>
                        ` : ''}
                      </div>
                    </td>
                  </tr>
                `).join('')}
              </tbody>
            </table>
          </div>
        </div>
      `;

      document.getElementById('attendees-content').innerHTML = attendeesHtml;
    } catch (error) {
      console.error('Error loading attendees:', error);
      document.getElementById('attendees-content').innerHTML = `
        <div class="text-red-600 bg-red-50 p-4 rounded-lg">
          <p class="font-medium">Error loading attendees</p>
          <p class="text-sm">${error.message}</p>
        </div>
      `;
    }
  }

  // Venue management functions
  async function updateEventSeating() {
    try {
      const seatingType = document.getElementById('seating-type').value;
      const seatingMapIdValue = document.getElementById('seating-map-select').value;
      const seatingMapId = seatingMapIdValue === '' ? null : seatingMapIdValue;

      const { error } = await supabase
        .from('events')
        .update({
          seating_type: seatingType,
          seating_map_id: seatingMapId
        })
        .eq('id', eventId);

      if (error) throw error;

      // Reload the venue content to reflect changes
      await loadVenueContent();
      
      // Show success message
      showToast('Seating configuration updated successfully!', 'success');
    } catch (error) {
      console.error('Error updating event seating:', error);
      showToast('Error updating seating configuration', 'error');
    }
  }

  async function previewSeatingMap(mapId) {
    try {
      console.log('Previewing seating map:', mapId);
      
      const { data: seatingMap, error } = await supabase
        .from('seating_maps')
        .select('*')
        .eq('id', mapId)
        .single();

      if (error) throw error;

      console.log('Seating map data:', seatingMap);

      const previewContainer = document.getElementById('seating-preview');
      const chartContainer = document.getElementById('seating-chart');
      
      if (!previewContainer || !chartContainer) {
        console.error('Preview containers not found');
        return;
      }
      
      previewContainer.classList.remove('hidden');
      
      // Enhanced visualization based on layout data
      const layoutData = seatingMap.layout_data || {};
      const sections = layoutData.sections || [];
      const layoutType = layoutData.type || 'general';
      
      let chartHTML = `
        <div class="text-center mb-8">
          <div class="bg-gradient-to-r from-slate-800 to-slate-900 text-white rounded-2xl p-6 shadow-lg">
            <h4 class="text-2xl font-light mb-3 tracking-wide">${seatingMap.name}</h4>
            <div class="flex items-center justify-center space-x-6 text-slate-200">
              <div class="flex items-center space-x-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="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 class="font-medium">${seatingMap.venue_name}</span>
              </div>
              <div class="flex items-center space-x-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="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                </svg>
                <span class="font-medium">${seatingMap.total_capacity} seats</span>
              </div>
            </div>
            <div class="mt-3 px-3 py-1 bg-white/10 rounded-full inline-block">
              <span class="text-xs font-medium uppercase tracking-wide">${layoutType} Layout</span>
            </div>
          </div>
        </div>
        <div class="seating-layout bg-gradient-to-br from-slate-50 to-white rounded-2xl p-8 shadow-xl border border-slate-200">
      `;

      if (sections.length > 0) {
        chartHTML += '<div class="space-y-6">';
        
        sections.forEach(section => {
          chartHTML += `
            <div class="bg-white border-2 border-slate-200 rounded-2xl p-6 shadow-lg hover:shadow-xl transition-shadow duration-200">
              <div class="flex items-center justify-between mb-4">
                <h5 class="text-lg font-semibold text-slate-800 flex items-center">
                  <div class="w-3 h-3 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full mr-3"></div>
                  ${section.name}
                </h5>
                <div class="px-3 py-1 bg-slate-100 rounded-full">
                  <span class="text-xs font-medium text-slate-600">
                    ${section.capacity || (section.rows * section.seatsPerRow) || (section.tables * section.seatsPerTable) || 0} seats
                  </span>
                </div>
              </div>
          `;
          
          // Different rendering based on section type
          if (section.rows && section.seatsPerRow) {
            // Theater-style seating with rows
            chartHTML += `
              <div class="mb-4 p-3 bg-gradient-to-r from-slate-50 to-slate-100 rounded-lg border">
                <div class="flex items-center justify-between">
                  <span class="text-sm font-medium text-slate-700">Theater Layout</span>
                  <div class="flex items-center space-x-4 text-xs text-slate-500">
                    <span>Rows ${section.startRow || 'A'} - ${String.fromCharCode((section.startRow || 'A').charCodeAt(0) + section.rows - 1)}</span>
                    <span>•</span>
                    <span>${section.seatsPerRow} seats per row</span>
                  </div>
                </div>
              </div>
              <div class="space-y-3 p-4 bg-slate-50 rounded-xl">
                <div class="text-center mb-4">
                  <div class="inline-block px-4 py-2 bg-gradient-to-r from-amber-400 to-orange-400 text-white rounded-lg shadow-md">
                    <span class="text-sm font-semibold">🎭 STAGE</span>
                  </div>
                </div>
            `;
            
            for (let row = 0; row < section.rows; row++) {
              const rowLetter = String.fromCharCode((section.startRow || 'A').charCodeAt(0) + row);
              chartHTML += `
                <div class="flex items-center justify-center gap-3">
                  <span class="text-sm font-bold text-slate-600 w-6 text-center">${rowLetter}</span>
                  <div class="flex gap-1">
              `;
              
              for (let seat = 0; seat < section.seatsPerRow; seat++) {
                const seatClass = section.pricing === 'premium' 
                  ? 'bg-gradient-to-br from-amber-400 to-yellow-500 border-amber-500' 
                  : 'bg-gradient-to-br from-emerald-400 to-green-500 border-emerald-500';
                chartHTML += `<div class="w-6 h-6 ${seatClass} rounded-lg border-2 shadow-sm hover:shadow-md transition-shadow cursor-pointer" title="${rowLetter}${seat + 1}"></div>`;
              }
              
              chartHTML += `
                  </div>
                  <span class="text-sm font-bold text-slate-600 w-6 text-center">${rowLetter}</span>
                </div>
              `;
            }
            
            chartHTML += '</div>';
          } else if (section.tables) {
            // Reception-style with tables
            chartHTML += `
              <div class="mb-4 p-3 bg-gradient-to-r from-slate-50 to-slate-100 rounded-lg border">
                <div class="flex items-center justify-between">
                  <span class="text-sm font-medium text-slate-700">Reception Layout</span>
                  <div class="flex items-center space-x-4 text-xs text-slate-500">
                    <span>${section.tables} tables</span>
                    <span>•</span>
                    <span>${section.seatsPerTable || 8} seats per table</span>
                  </div>
                </div>
              </div>
              <div class="p-6 bg-gradient-to-br from-slate-50 to-slate-100 rounded-xl">
                <div class="grid grid-cols-4 gap-4 justify-items-center">
            `;
            
            for (let table = 0; table < section.tables; table++) {
              chartHTML += `
                <div class="relative group">
                  <div class="w-16 h-16 bg-gradient-to-br from-amber-300 to-orange-400 rounded-full flex items-center justify-center text-sm font-bold text-white shadow-lg border-4 border-white hover:shadow-xl transition-shadow cursor-pointer">
                    ${table + 1}
                  </div>
                  <div class="absolute -top-2 -right-2 w-6 h-6 bg-gradient-to-br from-blue-400 to-purple-500 rounded-full flex items-center justify-center text-xs font-bold text-white shadow-md">
                    ${section.seatsPerTable || 8}
                  </div>
                </div>
              `;
            }
            
            chartHTML += '</div></div>';
          } else {
            // General admission or simple capacity
            const capacity = section.capacity || 0;
            const gridCols = Math.min(Math.ceil(Math.sqrt(capacity)), 20);
            
            chartHTML += `
              <div class="mb-4 p-3 bg-gradient-to-r from-slate-50 to-slate-100 rounded-lg border">
                <div class="flex items-center justify-between">
                  <span class="text-sm font-medium text-slate-700">General Admission</span>
                  <div class="flex items-center space-x-4 text-xs text-slate-500">
                    <span>${capacity} capacity</span>
                    <span>•</span>
                    <span>Open seating</span>
                  </div>
                </div>
              </div>
              <div class="p-6 bg-gradient-to-br from-slate-50 to-slate-100 rounded-xl">
                <div class="grid gap-2 justify-items-center" style="grid-template-columns: repeat(${gridCols}, 1fr);">
            `;
            
            for (let i = 0; i < capacity; i++) {
              const seatClass = section.type === 'wheelchair' 
                ? 'bg-gradient-to-br from-blue-400 to-indigo-500 border-blue-500' 
                : 'bg-gradient-to-br from-emerald-400 to-green-500 border-emerald-500';
              chartHTML += `<div class="w-5 h-5 ${seatClass} rounded-lg border-2 shadow-sm hover:shadow-md transition-shadow cursor-pointer" title="Seat ${i + 1}"></div>`;
            }
            
            chartHTML += '</div></div>';
          }
          
          chartHTML += `
            </div>
          `;
        });
        
        chartHTML += '</div>';
      } else {
        chartHTML += `
          <div class="bg-gradient-to-br from-slate-100 to-slate-200 border-2 border-dashed border-slate-300 rounded-2xl p-12 text-center">
            <div class="mx-auto w-16 h-16 bg-gradient-to-br from-slate-400 to-slate-500 rounded-full flex items-center justify-center mb-4">
              <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"></path>
              </svg>
            </div>
            <p class="text-lg font-medium text-slate-600 mb-2">No Detailed Layout Available</p>
            <p class="text-sm text-slate-500 mb-4">This venue has basic capacity information only</p>
            <div class="inline-flex items-center px-4 py-2 bg-white rounded-full shadow-sm">
              <svg class="w-4 h-4 text-slate-400 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
              </svg>
              <span class="text-sm font-medium text-slate-600">Total Capacity: ${seatingMap.total_capacity} seats</span>
            </div>
          </div>
        `;
      }

      chartHTML += `
        </div>
        <div class="mt-8 p-4 bg-white rounded-xl border border-slate-200">
          <h6 class="text-sm font-semibold text-slate-700 mb-3">Legend</h6>
          <div class="flex flex-wrap gap-4">
            <div class="flex items-center space-x-2">
              <div class="w-4 h-4 bg-gradient-to-br from-emerald-400 to-green-500 rounded-lg border-2 border-emerald-500"></div>
              <span class="text-xs text-slate-600">Standard Seating</span>
            </div>
            <div class="flex items-center space-x-2">
              <div class="w-4 h-4 bg-gradient-to-br from-amber-400 to-yellow-500 rounded-lg border-2 border-amber-500"></div>
              <span class="text-xs text-slate-600">Premium Seating</span>
            </div>
            <div class="flex items-center space-x-2">
              <div class="w-4 h-4 bg-gradient-to-br from-blue-400 to-indigo-500 rounded-lg border-2 border-blue-500"></div>
              <span class="text-xs text-slate-600">Accessible Seating</span>
            </div>
            <div class="flex items-center space-x-2">
              <div class="w-4 h-4 bg-gradient-to-br from-amber-300 to-orange-400 rounded-full border-2 border-white"></div>
              <span class="text-xs text-slate-600">Reception Tables</span>
            </div>
          </div>
        </div>
      </div>`;
      
      console.log('Setting chart HTML:', chartHTML.length, 'characters');
      chartContainer.innerHTML = chartHTML;
      
      // Scroll the preview into view
      previewContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
      
    } catch (error) {
      console.error('Error previewing seating map:', error);
      
      const chartContainer = document.getElementById('seating-chart');
      if (chartContainer) {
        chartContainer.innerHTML = `
          <div class="text-red-600 bg-red-50 p-4 rounded-lg">
            <p class="font-medium">Error loading seating map preview</p>
            <p class="text-sm">${error.message}</p>
          </div>
        `;
      }
      
      // Still show the preview container even with error
      const previewContainer = document.getElementById('seating-preview');
      if (previewContainer) {
        previewContainer.classList.remove('hidden');
      }
    }
  }

  async function useSeatingMap(mapId) {
    try {
      // Get the seating map details for confirmation
      const { data: seatingMap, error: mapError } = await supabase
        .from('seating_maps')
        .select('name, total_capacity')
        .eq('id', mapId)
        .single();

      if (mapError) throw mapError;

      // Confirm the action
      if (!confirm(`Assign "${seatingMap.name}" (${seatingMap.total_capacity} seats) to this event? This will change the seating type to "Assigned Seating".`)) {
        return;
      }

      const { error } = await supabase
        .from('events')
        .update({
          seating_map_id: mapId,
          seating_type: 'assigned_seating'
        })
        .eq('id', eventId);

      if (error) throw error;

      // Reload the venue content to reflect changes
      await loadVenueContent();
      
      showToast(`"${seatingMap.name}" assigned to event successfully!`, 'success');
    } catch (error) {
      console.error('Error assigning seating map:', error);
      showToast('Error assigning seating map: ' + error.message, 'error');
    }
  }

  async function deleteSeatingMap(mapId) {
    if (!confirm('Are you sure you want to delete this seating map? This action cannot be undone.')) {
      return;
    }

    try {
      const { error } = await supabase
        .from('seating_maps')
        .delete()
        .eq('id', mapId);

      if (error) throw error;

      // Reload the venue content to reflect changes
      await loadVenueContent();
      
      showToast('Seating map deleted successfully!', 'success');
    } catch (error) {
      console.error('Error deleting seating map:', error);
      showToast('Error deleting seating map', 'error');
    }
  }

  function openSeatingMapModal() {
    console.log('Opening seating map modal...');
    
    const modal = document.getElementById('seating-map-modal');
    if (!modal) {
      console.error('Seating map modal not found!');
      alert('Error: Modal not found. Please refresh the page and try again.');
      return;
    }
    
    modal.classList.remove('hidden');
    
    try {
      // Small delay to ensure modal is visible before initializing
      setTimeout(() => {
        updateLayoutPreview(); // Initialize the layout configuration
        console.log('Modal opened and layout preview updated');
      }, 100);
    } catch (error) {
      console.error('Error updating layout preview:', error);
    }
  }

  function closeSeatingMapModal() {
    document.getElementById('seating-map-modal').classList.add('hidden');
    document.getElementById('seating-map-form').reset();
    // Reset modal for creating new maps
    document.getElementById('seating-modal-title').textContent = 'Create Seating Map';
    document.getElementById('seating-submit-text').textContent = 'Create Seating Map';
    delete document.getElementById('seating-map-form').dataset.editingId;
  }

  // Embed Widget Modal Functions
  function openEmbedWidgetModal() {
    if (!currentEvent || !currentEvent.slug) {
      alert('Event data not loaded. Please refresh the page.');
      return;
    }
    
    const modal = document.getElementById('embed-widget-modal');
    if (!modal) {
      alert('Error: Modal not found. Please refresh the page and try again.');
      return;
    }
    
    // Update the basic embed code preview
    updateBasicEmbedPreview();
    
    modal.classList.remove('hidden');
  }

  function closeEmbedWidgetModal() {
    const modal = document.getElementById('embed-widget-modal');
    if (modal) {
      modal.classList.add('hidden');
    }
  }

  function updateBasicEmbedPreview() {
    if (!currentEvent || !currentEvent.slug) return;
    
    const embedUrl = `${window.location.protocol}//${window.location.host}/embed/${currentEvent.slug}`;
    const embedCode = `<iframe 
  src="${embedUrl}" 
  width="100%" 
  height="600" 
  frameborder="0" 
  scrolling="no"
  title="${currentEvent.title} - Ticket Widget"
  style="border: 1px solid #e2e8f0; border-radius: 8px; overflow: hidden;"
  onload="this.style.height = this.contentWindow.document.body.scrollHeight + 'px'">
</iframe>

<sc` + `ript>
  // Auto-resize iframe based on content
  window.addEventListener('message', function(event) {
    if (event.data.type === 'resize') {
      const iframe = document.querySelector('iframe[src*="' + window.location.protocol + '//' + window.location.host + '/embed/"]');
      if (iframe) {
        iframe.style.height = event.data.height + 'px';
      }
    }
  });
</sc` + `ript>`;

    const previewElement = document.getElementById('basic-embed-preview');
    if (previewElement) {
      previewElement.textContent = embedCode;
    }
  }

  function openCustomizationPage() {
    if (!currentEvent || !currentEvent.slug) {
      alert('Event data not loaded. Please refresh the page.');
      return;
    }
    
    const customizationUrl = `${window.location.protocol}//${window.location.host}/embed-code/${currentEvent.slug}`;
    window.open(customizationUrl, '_blank');
  }

  function copyDirectLink() {
    if (!currentEvent || !currentEvent.slug) {
      alert('Event data not loaded. Please refresh the page.');
      return;
    }
    
    const embedUrl = `${window.location.protocol}//${window.location.host}/embed/${currentEvent.slug}`;
    navigator.clipboard.writeText(embedUrl).then(() => {
      // Show temporary success message
      const button = event.target;
      const originalText = button.textContent;
      button.textContent = 'Copied!';
      button.classList.remove('bg-slate-600', 'hover:bg-slate-700');
      button.classList.add('bg-green-600');
      
      setTimeout(() => {
        button.textContent = originalText;
        button.classList.remove('bg-green-600');
        button.classList.add('bg-slate-600', 'hover:bg-slate-700');
      }, 2000);
    }).catch(() => {
      alert('Failed to copy to clipboard. Please try again.');
    });
  }

  function copyBasicEmbedCode() {
    const previewElement = document.getElementById('basic-embed-preview');
    if (!previewElement) {
      alert('Embed code not loaded. Please try again.');
      return;
    }
    
    navigator.clipboard.writeText(previewElement.textContent).then(() => {
      // Show temporary success message
      const button = event.target;
      const originalText = button.textContent;
      button.textContent = 'Copied!';
      button.classList.remove('bg-green-600', 'hover:bg-green-700');
      button.classList.add('bg-emerald-600');
      
      setTimeout(() => {
        button.textContent = originalText;
        button.classList.remove('bg-emerald-600');
        button.classList.add('bg-green-600', 'hover:bg-green-700');
      }, 2000);
    }).catch(() => {
      alert('Failed to copy to clipboard. Please try again.');
    });
  }

  function updateLayoutPreview() {
    const layoutTypeRadio = document.querySelector('input[name="layout_type"]:checked');
    const layoutType = layoutTypeRadio ? layoutTypeRadio.value : 'theater';
    const configContainer = document.getElementById('layout-config');
    
    let configHTML = '<h3 class="text-lg font-medium text-slate-900 mb-4">Layout Configuration</h3>';
    
    switch (layoutType) {
      case 'theater':
        configHTML += `
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-slate-700 mb-2">Number of Rows</label>
              <input type="number" id="theater-rows" min="1" max="50" value="10" class="w-full px-3 py-2 border border-slate-300 rounded-lg" onchange="updateModalPreview()">
            </div>
            <div>
              <label class="block text-sm font-medium text-slate-700 mb-2">Seats per Row</label>
              <input type="number" id="theater-seats-per-row" min="1" max="100" value="10" class="w-full px-3 py-2 border border-slate-300 rounded-lg" onchange="updateModalPreview()">
            </div>
          </div>
        `;
        break;
      case 'reception':
        configHTML += `
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-slate-700 mb-2">Number of Tables</label>
              <input type="number" id="reception-tables" min="1" max="100" value="12" class="w-full px-3 py-2 border border-slate-300 rounded-lg" onchange="updateModalPreview()">
            </div>
            <div>
              <label class="block text-sm font-medium text-slate-700 mb-2">Seats per Table</label>
              <input type="number" id="reception-seats-per-table" min="1" max="20" value="8" class="w-full px-3 py-2 border border-slate-300 rounded-lg" onchange="updateModalPreview()">
            </div>
          </div>
        `;
        break;
      case 'concert_hall':
        configHTML += `
          <div class="space-y-4">
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">General Admission Capacity</label>
                <input type="number" id="concert-ga-capacity" min="0" max="5000" value="300" class="w-full px-3 py-2 border border-slate-300 rounded-lg" onchange="updateModalPreview()">
              </div>
              <div>
                <label class="block text-sm font-medium text-slate-700 mb-2">Reserved Seating Capacity</label>
                <input type="number" id="concert-reserved-capacity" min="0" max="5000" value="200" class="w-full px-3 py-2 border border-slate-300 rounded-lg" onchange="updateModalPreview()">
              </div>
            </div>
          </div>
        `;
        break;
      default:
        configHTML += `
          <p class="text-slate-600">General admission seating - capacity will be set above.</p>
        `;
        break;
    }
    
    configContainer.innerHTML = configHTML;
    
    // Show/hide table labeling based on layout type
    const tableLabelingDiv = document.getElementById('table-labeling');
    if (tableLabelingDiv) {
      if (layoutType === 'reception') {
        tableLabelingDiv.classList.remove('hidden');
      } else {
        tableLabelingDiv.classList.add('hidden');
      }
    }
    
    // Update the live preview
    setTimeout(() => updateModalPreview(), 100); // Small delay to ensure DOM is updated
  }

  function updateModalPreview() {
    const layoutTypeRadio = document.querySelector('input[name="layout_type"]:checked');
    const layoutType = layoutTypeRadio ? layoutTypeRadio.value : 'theater';
    const venueName = document.getElementById('venue-name-input')?.value || 'Your Venue';
    const totalCapacity = document.getElementById('total-capacity-input')?.value || '100';
    
    // Build mock seating map data
    const mockSeatingMap = {
      name: document.getElementById('seating-map-name')?.value || 'New Seating Map',
      venue_name: venueName,
      total_capacity: parseInt(totalCapacity),
      layout_data: { type: layoutType, sections: [] }
    };

    // Build sections based on current form values
    switch (layoutType) {
      case 'theater':
        const rows = parseInt(document.getElementById('theater-rows')?.value || 10);
        const seatsPerRow = parseInt(document.getElementById('theater-seats-per-row')?.value || 10);
        mockSeatingMap.layout_data.sections.push({
          name: 'Orchestra',
          rows: rows,
          seatsPerRow: seatsPerRow,
          startRow: 'A',
          pricing: 'standard'
        });
        break;
        
      case 'reception':
        const tables = parseInt(document.getElementById('reception-tables')?.value || 12);
        const seatsPerTable = parseInt(document.getElementById('reception-seats-per-table')?.value || 8);
        mockSeatingMap.layout_data.sections.push({
          name: 'Main Floor',
          tables: tables,
          seatsPerTable: seatsPerTable,
          tableNumbers: Array.from({length: tables}, (_, i) => i + 1)
        });
        break;
        
      case 'concert_hall':
        const gaCapacity = parseInt(document.getElementById('concert-ga-capacity')?.value || 300);
        const reservedCapacity = parseInt(document.getElementById('concert-reserved-capacity')?.value || 200);
        if (gaCapacity > 0) {
          mockSeatingMap.layout_data.sections.push({
            name: 'Floor',
            type: 'general_admission',
            capacity: gaCapacity
          });
        }
        if (reservedCapacity > 0) {
          mockSeatingMap.layout_data.sections.push({
            name: 'Balcony',
            rows: Math.ceil(reservedCapacity / 20),
            seatsPerRow: 20,
            startRow: 'AA',
            pricing: 'premium'
          });
        }
        break;
        
      default:
        mockSeatingMap.layout_data.sections.push({
          name: 'General Admission',
          capacity: parseInt(totalCapacity),
          type: 'standard'
        });
        break;
    }

    // Initialize the layout editor instead of simple preview
    initializeLayoutEditor();
  }

  function renderSeatingPreview(seatingMap, containerId) {
    const chartContainer = document.getElementById(containerId);
    if (!chartContainer) return;

    const layoutData = seatingMap.layout_data || {};
    const sections = layoutData.sections || [];
    const layoutType = layoutData.type || 'general';
    
    let chartHTML = `
      <div class="text-center mb-4">
        <h4 class="text-base font-medium text-slate-900 mb-1">${seatingMap.name}</h4>
        <p class="text-sm text-slate-600">${seatingMap.venue_name} • ${seatingMap.total_capacity} seats</p>
        <p class="text-xs text-slate-500">Layout Type: ${layoutType}</p>
      </div>
      <div class="seating-layout bg-slate-50 rounded-lg p-4">
    `;

    if (sections.length > 0) {
      chartHTML += '<div class="space-y-4">';
      
      sections.forEach(section => {
        chartHTML += `
          <div class="bg-white border rounded-lg p-3 shadow-sm">
            <h5 class="font-medium text-slate-700 mb-2 text-sm">${section.name}</h5>
        `;
        
        // Different rendering based on section type (same logic as main preview but smaller)
        if (section.rows && section.seatsPerRow) {
          // Theater-style seating with rows
          chartHTML += `
            <div class="mb-2">
              <span class="text-xs text-slate-500">Rows ${section.startRow || 'A'} - ${String.fromCharCode((section.startRow || 'A').charCodeAt(0) + section.rows - 1)}</span>
              <span class="text-xs text-slate-500 ml-3">${section.seatsPerRow} seats per row</span>
            </div>
            <div class="space-y-1">
          `;
          
          // Limit rows shown in preview to keep it manageable
          const maxRowsToShow = Math.min(section.rows, 8);
          for (let row = 0; row < maxRowsToShow; row++) {
            const rowLetter = String.fromCharCode((section.startRow || 'A').charCodeAt(0) + row);
            chartHTML += `
              <div class="flex items-center gap-1">
                <span class="text-xs font-mono text-slate-500 w-3">${rowLetter}</span>
                <div class="flex gap-0.5">
            `;
            
            // Limit seats shown per row
            const maxSeatsToShow = Math.min(section.seatsPerRow, 20);
            for (let seat = 0; seat < maxSeatsToShow; seat++) {
              const seatClass = section.pricing === 'premium' ? 'bg-yellow-300' : 'bg-green-300';
              chartHTML += `<div class="w-3 h-3 ${seatClass} rounded-sm border border-slate-400"></div>`;
            }
            
            if (section.seatsPerRow > maxSeatsToShow) {
              chartHTML += `<span class="text-xs text-slate-400 ml-1">...</span>`;
            }
            
            chartHTML += `
                </div>
              </div>
            `;
          }
          
          if (section.rows > maxRowsToShow) {
            chartHTML += `<div class="text-xs text-slate-400 text-center">... ${section.rows - maxRowsToShow} more rows</div>`;
          }
          
          chartHTML += '</div>';
        } else if (section.tables) {
          // Reception-style with tables
          chartHTML += `
            <div class="mb-2">
              <span class="text-xs text-slate-500">${section.tables} tables • ${section.seatsPerTable || 8} seats per table</span>
            </div>
            <div class="grid grid-cols-6 gap-2">
          `;
          
          const maxTablesToShow = Math.min(section.tables, 12);
          for (let table = 0; table < maxTablesToShow; table++) {
            chartHTML += `
              <div class="bg-amber-200 rounded-full w-8 h-8 flex items-center justify-center text-xs font-medium border-2 border-amber-400">
                ${table + 1}
              </div>
            `;
          }
          
          if (section.tables > maxTablesToShow) {
            chartHTML += `<div class="text-xs text-slate-400 flex items-center justify-center">+${section.tables - maxTablesToShow}</div>`;
          }
          
          chartHTML += '</div>';
        } else {
          // General admission or simple capacity
          const capacity = section.capacity || 0;
          const gridCols = Math.min(Math.ceil(Math.sqrt(capacity)), 15);
          const maxSeatsToShow = Math.min(capacity, 100);
          
          chartHTML += `
            <div class="mb-2">
              <span class="text-xs text-slate-500">General Admission • ${capacity} capacity</span>
            </div>
            <div class="grid gap-0.5" style="grid-template-columns: repeat(${gridCols}, 1fr);">
          `;
          
          for (let i = 0; i < maxSeatsToShow; i++) {
            const seatClass = section.type === 'wheelchair' ? 'bg-blue-300' : 'bg-green-300';
            chartHTML += `<div class="w-3 h-3 ${seatClass} rounded-sm border border-slate-400"></div>`;
          }
          
          if (capacity > maxSeatsToShow) {
            chartHTML += `<div class="text-xs text-slate-400 col-span-full text-center mt-1">... ${capacity - maxSeatsToShow} more seats</div>`;
          }
          
          chartHTML += '</div>';
        }
        
        chartHTML += `
            <p class="text-xs text-slate-500 mt-2">
              ${section.capacity || (section.rows * section.seatsPerRow) || (section.tables * section.seatsPerTable) || 0} seats
            </p>
          </div>
        `;
      });
      
      chartHTML += '</div>';
    } else {
      chartHTML += `
        <div class="bg-slate-100 border-2 border-dashed border-slate-300 rounded-lg p-6 text-center">
          <p class="text-slate-500">Configure layout above to see preview</p>
        </div>
      `;
    }

    chartHTML += '</div>';
    chartContainer.innerHTML = chartHTML;
  }

  // Layout Editor Functions
  function initializeLayoutEditor() {
    const canvas = document.getElementById('layout-canvas');
    const editor = document.getElementById('layout-editor');
    
    if (!canvas || !editor) return;

    // Clear existing content
    canvas.innerHTML = '';
    layoutItems = [];

    // Add event listeners for drag and drop
    canvas.addEventListener('mousedown', handleMouseDown);
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
    
    // Generate initial layout based on configuration
    generateInitialLayout();
  }

  function generateInitialLayout() {
    const layoutType = document.getElementById('layout-type-select')?.value || 'general';
    
    layoutItems = [];
    
    switch (layoutType) {
      case 'theater':
        generateTheaterLayout();
        break;
      case 'reception':
        generateReceptionLayout();
        break;
      case 'concert_hall':
        generateConcertHallLayout();
        break;
      default:
        generateGeneralLayout();
        break;
    }
    
    renderLayoutItems();
  }

  function generateTheaterLayout() {
    const rows = parseInt(document.getElementById('theater-rows')?.value || 10);
    const seatsPerRow = parseInt(document.getElementById('theater-seats-per-row')?.value || 10);
    const rowLabelStyle = document.getElementById('row-labeling-style')?.value || 'letters';
    const rowStartValue = document.getElementById('row-start-value')?.value || 'A';
    
    const canvasWidth = 600;
    const canvasHeight = 400;
    const seatWidth = 25;
    const seatHeight = 20;
    const rowSpacing = 30;
    const seatSpacing = 28;
    
    // Calculate starting positions to center the layout
    const totalWidth = seatsPerRow * seatSpacing;
    const totalHeight = rows * rowSpacing;
    const startX = (canvasWidth - totalWidth) / 2;
    const startY = (canvasHeight - totalHeight) / 2 + 50; // Leave room for stage
    
    for (let row = 0; row < rows; row++) {
      const rowLabel = rowLabelStyle === 'letters' 
        ? String.fromCharCode(rowStartValue.charCodeAt(0) + row)
        : (parseInt(rowStartValue) + row).toString();
        
      for (let seat = 0; seat < seatsPerRow; seat++) {
        const seatNumber = seat + 1;
        const x = startX + (seat * seatSpacing);
        const y = startY + (row * rowSpacing);
        
        layoutItems.push({
          id: `seat-${row}-${seat}`,
          type: 'seat',
          x: x,
          y: y,
          width: seatWidth,
          height: seatHeight,
          label: `${rowLabel}${seatNumber}`,
          row: rowLabel,
          seatNumber: seatNumber,
          section: 'Orchestra'
        });
      }
    }
  }

  function generateReceptionLayout() {
    const tables = parseInt(document.getElementById('reception-tables')?.value || 12);
    const seatsPerTable = parseInt(document.getElementById('reception-seats-per-table')?.value || 8);
    const tableStartNumber = parseInt(document.getElementById('table-start-number')?.value || 1);
    
    const canvasWidth = 600;
    const canvasHeight = 400;
    const tableSize = 50;
    const cols = Math.ceil(Math.sqrt(tables));
    const rows = Math.ceil(tables / cols);
    
    const spacingX = (canvasWidth - tableSize) / cols;
    const spacingY = (canvasHeight - tableSize - 50) / rows; // Leave room for stage
    
    for (let i = 0; i < tables; i++) {
      const col = i % cols;
      const row = Math.floor(i / cols);
      const x = col * spacingX + spacingX / 2;
      const y = row * spacingY + spacingY / 2 + 60; // Leave room for stage
      
      layoutItems.push({
        id: `table-${i}`,
        type: 'table',
        x: x,
        y: y,
        width: tableSize,
        height: tableSize,
        label: `Table ${tableStartNumber + i}`,
        tableNumber: tableStartNumber + i,
        seatsPerTable: seatsPerTable,
        section: 'Main Floor'
      });
    }
  }

  function generateConcertHallLayout() {
    // Add general admission area
    layoutItems.push({
      id: 'ga-floor',
      type: 'area',
      x: 50,
      y: 200,
      width: 300,
      height: 150,
      label: 'General Admission Floor',
      capacity: parseInt(document.getElementById('concert-ga-capacity')?.value || 300),
      section: 'Floor'
    });
    
    // Add reserved seating area
    layoutItems.push({
      id: 'reserved-balcony',
      type: 'area',
      x: 380,
      y: 200,
      width: 200,
      height: 150,
      label: 'Reserved Balcony',
      capacity: parseInt(document.getElementById('concert-reserved-capacity')?.value || 200),
      section: 'Balcony'
    });
  }

  function generateGeneralLayout() {
    const capacity = parseInt(document.getElementById('total-capacity-input')?.value || 100);
    
    layoutItems.push({
      id: 'general-area',
      type: 'area',
      x: 100,
      y: 150,
      width: 400,
      height: 200,
      label: 'General Admission',
      capacity: capacity,
      section: 'Main Floor'
    });
  }

  function renderLayoutItems() {
    const canvas = document.getElementById('layout-canvas');
    if (!canvas) return;

    canvas.innerHTML = '';

    layoutItems.forEach(item => {
      const element = createLayoutElement(item);
      canvas.appendChild(element);
    });
  }

  function createLayoutElement(item) {
    const element = document.createElement('div');
    element.id = item.id;
    element.className = `layout-item absolute cursor-move select-none border-2 rounded flex items-center justify-center text-xs font-medium transition-all duration-200 ${getItemClasses(item)}`;
    element.style.left = item.x + 'px';
    element.style.top = item.y + 'px';
    element.style.width = item.width + 'px';
    element.style.height = item.height + 'px';
    element.textContent = item.label;
    element.dataset.itemId = item.id;
    
    // Add hover effects
    element.addEventListener('mouseenter', () => {
      element.classList.add('shadow-lg', 'scale-105');
    });
    
    element.addEventListener('mouseleave', () => {
      element.classList.remove('shadow-lg', 'scale-105');
    });

    return element;
  }

  function getItemClasses(item) {
    switch (item.type) {
      case 'seat':
        return 'bg-green-200 border-green-400 text-green-800 hover:bg-green-300';
      case 'table':
        return 'bg-amber-200 border-amber-400 text-amber-800 hover:bg-amber-300 rounded-full';
      case 'area':
        return 'bg-blue-200 border-blue-400 text-blue-800 hover:bg-blue-300';
      default:
        return 'bg-slate-200 border-slate-400 text-slate-800 hover:bg-slate-300';
    }
  }

  function handleMouseDown(e) {
    const element = e.target.closest('.layout-item');
    if (!element) return;

    e.preventDefault();
    isDragging = true;
    selectedItem = element;

    const rect = element.getBoundingClientRect();
    const canvasRect = document.getElementById('layout-canvas').getBoundingClientRect();
    
    dragOffset = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    };

    element.classList.add('z-50', 'shadow-xl');
  }

  function handleMouseMove(e) {
    if (!isDragging || !selectedItem) return;

    e.preventDefault();
    
    const canvasRect = document.getElementById('layout-canvas').getBoundingClientRect();
    const x = e.clientX - canvasRect.left - dragOffset.x;
    const y = e.clientY - canvasRect.top - dragOffset.y;

    // Constrain to canvas bounds
    const maxX = canvasRect.width - selectedItem.offsetWidth;
    const maxY = canvasRect.height - selectedItem.offsetHeight;
    
    const constrainedX = Math.max(0, Math.min(x, maxX));
    const constrainedY = Math.max(0, Math.min(y, maxY));

    selectedItem.style.left = constrainedX + 'px';
    selectedItem.style.top = constrainedY + 'px';

    // Update the item in layoutItems array
    const itemId = selectedItem.dataset.itemId;
    const item = layoutItems.find(i => i.id === itemId);
    if (item) {
      item.x = constrainedX;
      item.y = constrainedY;
    }
  }

  function handleMouseUp(e) {
    if (isDragging && selectedItem) {
      selectedItem.classList.remove('z-50', 'shadow-xl');
    }
    
    isDragging = false;
    selectedItem = null;
  }

  function addTable() {
    const canvas = document.getElementById('layout-canvas');
    if (!canvas) return;

    const tableNumber = layoutItems.filter(item => item.type === 'table').length + 1;
    const newTable = {
      id: `table-${Date.now()}`,
      type: 'table',
      x: 100,
      y: 100,
      width: 50,
      height: 50,
      label: `Table ${tableNumber}`,
      tableNumber: tableNumber,
      seatsPerTable: 8,
      section: 'Main Floor'
    };

    layoutItems.push(newTable);
    const element = createLayoutElement(newTable);
    canvas.appendChild(element);
  }

  function addSeatRow() {
    const canvas = document.getElementById('layout-canvas');
    if (!canvas) return;

    const rowNumber = layoutItems.filter(item => item.type === 'seat' && item.row === `Row ${Math.floor(layoutItems.filter(i => i.type === 'seat').length / 10) + 1}`).length + 1;
    const seatsInRow = 10;
    const startY = 100 + (Math.floor(layoutItems.filter(i => i.type === 'seat').length / 10) * 30);
    
    for (let i = 0; i < seatsInRow; i++) {
      const newSeat = {
        id: `seat-${Date.now()}-${i}`,
        type: 'seat',
        x: 50 + (i * 28),
        y: startY,
        width: 25,
        height: 20,
        label: `${String.fromCharCode(65 + Math.floor(layoutItems.filter(s => s.type === 'seat').length / 10))}${i + 1}`,
        row: String.fromCharCode(65 + Math.floor(layoutItems.filter(s => s.type === 'seat').length / 10)),
        seatNumber: i + 1,
        section: 'Orchestra'
      };

      layoutItems.push(newSeat);
      const element = createLayoutElement(newSeat);
      canvas.appendChild(element);
    }
  }

  function addGeneralArea() {
    const canvas = document.getElementById('layout-canvas');
    if (!canvas) return;

    const areaNumber = layoutItems.filter(item => item.type === 'area').length + 1;
    const newArea = {
      id: `area-${Date.now()}`,
      type: 'area',
      x: 100,
      y: 150,
      width: 200,
      height: 100,
      label: `Area ${areaNumber}`,
      capacity: 50,
      section: `Section ${areaNumber}`
    };

    layoutItems.push(newArea);
    const element = createLayoutElement(newArea);
    canvas.appendChild(element);
  }

  function resetLayout() {
    generateInitialLayout();
  }

  function autoArrangeLayout() {
    // Auto-arrange tables in a grid
    const tables = layoutItems.filter(item => item.type === 'table');
    const seats = layoutItems.filter(item => item.type === 'seat');
    
    if (tables.length > 0) {
      const cols = Math.ceil(Math.sqrt(tables.length));
      const spacingX = 500 / cols;
      const spacingY = 300 / Math.ceil(tables.length / cols);
      
      tables.forEach((table, index) => {
        const col = index % cols;
        const row = Math.floor(index / cols);
        table.x = col * spacingX + 50;
        table.y = row * spacingY + 80;
      });
    }
    
    if (seats.length > 0) {
      // Arrange seats in rows
      const seatsPerRow = 10;
      seats.forEach((seat, index) => {
        const col = index % seatsPerRow;
        const row = Math.floor(index / seatsPerRow);
        seat.x = col * 28 + 50;
        seat.y = row * 30 + 80;
      });
    }
    
    renderLayoutItems();
  }

  function clearLayout() {
    if (confirm('Are you sure you want to clear the entire layout?')) {
      layoutItems = [];
      renderLayoutItems();
    }
  }

  async function editSeatingMap(mapId) {
    try {
      // Load the seating map data
      const { data: seatingMap, error } = await supabase
        .from('seating_maps')
        .select('*')
        .eq('id', mapId)
        .single();

      if (error) throw error;

      // Populate the modal with existing data
      document.getElementById('seating-modal-title').textContent = 'Edit Seating Map';
      document.getElementById('seating-submit-text').textContent = 'Update Seating Map';
      document.getElementById('seating-map-name').value = seatingMap.name;
      document.getElementById('venue-name-input').value = seatingMap.venue_name;
      document.getElementById('total-capacity-input').value = seatingMap.total_capacity;
      document.getElementById('seating-description').value = seatingMap.description || '';

      // Set layout type
      const layoutType = seatingMap.layout_data?.type || 'general';
      document.getElementById('layout-type-select').value = layoutType;

      // Store the map ID for updating
      document.getElementById('seating-map-form').dataset.editingId = mapId;

      // Update the layout configuration
      updateLayoutPreview();

      // Populate layout-specific fields if they exist
      const sections = seatingMap.layout_data?.sections || [];
      if (sections.length > 0) {
        const section = sections[0];
        
        switch (layoutType) {
          case 'theater':
            if (document.getElementById('theater-rows')) {
              document.getElementById('theater-rows').value = section.rows || 10;
            }
            if (document.getElementById('theater-seats-per-row')) {
              document.getElementById('theater-seats-per-row').value = section.seatsPerRow || 10;
            }
            break;
          case 'reception':
            if (document.getElementById('reception-tables')) {
              document.getElementById('reception-tables').value = section.tables || 12;
            }
            if (document.getElementById('reception-seats-per-table')) {
              document.getElementById('reception-seats-per-table').value = section.seatsPerTable || 8;
            }
            break;
          case 'concert_hall':
            const gaSection = sections.find(s => s.type === 'general_admission');
            const reservedSection = sections.find(s => s.rows);
            if (document.getElementById('concert-ga-capacity')) {
              document.getElementById('concert-ga-capacity').value = gaSection?.capacity || 300;
            }
            if (document.getElementById('concert-reserved-capacity')) {
              document.getElementById('concert-reserved-capacity').value = (reservedSection?.rows || 0) * (reservedSection?.seatsPerRow || 0);
            }
            break;
        }
      }

      // Open the modal
      document.getElementById('seating-map-modal').classList.remove('hidden');

    } catch (error) {
      console.error('Error loading seating map for editing:', error);
      showToast('Error loading seating map: ' + error.message, 'error');
    }
  }

  // Helper function to show toast notifications
  function showToast(message, type = 'info') {
    // Create toast element
    const toast = document.createElement('div');
    toast.className = `fixed top-4 right-4 z-50 px-6 py-4 rounded-lg shadow-lg transition-all duration-300 transform translate-x-full ${
      type === 'success' ? 'bg-green-500 text-white' : 
      type === 'error' ? 'bg-red-500 text-white' : 
      'bg-slate-800 text-white'
    }`;
    toast.textContent = message;
    
    document.body.appendChild(toast);
    
    // Animate in
    setTimeout(() => {
      toast.classList.remove('translate-x-full');
    }, 10);
    
    // Remove after delay
    setTimeout(() => {
      toast.classList.add('translate-x-full');
      setTimeout(() => {
        document.body.removeChild(toast);
      }, 300);
    }, 3000);
  }

  async function loadPresaleCodesContent() {
    try {
      const { data: presaleCodes, error } = await supabase
        .from('presale_codes')
        .select(`
          *,
          presale_code_ticket_types (
            ticket_type_id,
            ticket_types (
              name
            )
          )
        `)
        .eq('event_id', eventId)
        .eq('discount_type', 'none') // Only show access-only codes
        .order('created_at', { ascending: false });

      if (error) throw error;

      const container = document.getElementById('presale-codes-list');
      const emptyState = document.getElementById('presale-codes-empty');

      if (presaleCodes.length === 0) {
        container.classList.add('hidden');
        emptyState.classList.remove('hidden');
        return;
      }

      container.classList.remove('hidden');
      emptyState.classList.add('hidden');

      container.innerHTML = presaleCodes.map(code => {
        const ticketTypes = code.presale_code_ticket_types?.map(pct => pct.ticket_types?.name).filter(Boolean) || [];
        const validFrom = code.valid_from ? new Date(code.valid_from).toLocaleDateString() : 'No start date';
        const validUntil = code.valid_until ? new Date(code.valid_until).toLocaleDateString() : 'No end date';
        const used = code.usage_limit ? `${code.times_used || 0}/${code.usage_limit}` : (code.times_used || 0);
        
        return `
          <div class="bg-slate-50 rounded-2xl p-6 border border-slate-200">
            <div class="flex justify-between items-start">
              <div class="flex-1">
                <div class="flex items-center space-x-3 mb-3">
                  <h3 class="text-xl font-semibold text-slate-900 font-mono">${code.code}</h3>
                  <span class="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm font-medium">
                    Early Access
                  </span>
                  ${!code.is_active ? '<span class="px-3 py-1 bg-red-100 text-red-700 rounded-full text-sm font-medium">Inactive</span>' : ''}
                </div>
                
                ${code.description ? `<p class="text-slate-600 mb-3">${code.description}</p>` : ''}
                
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                  <div>
                    <span class="block text-slate-500">Usage</span>
                    <span class="font-semibold text-slate-900">${used}</span>
                  </div>
                  <div>
                    <span class="block text-slate-500">Valid From</span>
                    <span class="font-semibold text-slate-900">${validFrom}</span>
                  </div>
                  <div>
                    <span class="block text-slate-500">Valid Until</span>
                    <span class="font-semibold text-slate-900">${validUntil}</span>
                  </div>
                  <div>
                    <span class="block text-slate-500">Ticket Types</span>
                    <span class="font-semibold text-slate-900">${ticketTypes.length > 0 ? ticketTypes.join(', ') : 'All'}</span>
                  </div>
                </div>
              </div>
              
              <div class="flex space-x-2 ml-6">
                <button
                  onclick="editPresaleCode('${code.id}')"
                  class="text-slate-600 hover:text-slate-900 font-medium transition-colors duration-200"
                >
                  Edit
                </button>
                <button
                  onclick="togglePresaleCode('${code.id}', ${!code.is_active})"
                  class="text-slate-600 hover:text-slate-900 font-medium transition-colors duration-200"
                >
                  ${code.is_active ? 'Deactivate' : 'Activate'}
                </button>
                <button
                  onclick="deletePresaleCode('${code.id}')"
                  class="text-red-600 hover:text-red-800 font-medium transition-colors duration-200"
                >
                  Delete
                </button>
              </div>
            </div>
          </div>
        `;
      }).join('');

    } catch (error) {
      console.error('Error loading presale codes:', error);
    }
  }

  async function loadDiscountCodesContent() {
    try {
      // For now, we'll use the same presale_codes table but filter by discount_type
      const { data: discountCodes, error } = await supabase
        .from('presale_codes')
        .select(`
          *,
          presale_code_ticket_types (
            ticket_type_id,
            ticket_types (
              name
            )
          )
        `)
        .eq('event_id', eventId)
        .neq('discount_type', 'none') // Only show actual discount codes
        .order('created_at', { ascending: false });

      if (error) throw error;

      const container = document.getElementById('discount-codes-list');
      const emptyState = document.getElementById('discount-codes-empty');

      if (discountCodes.length === 0) {
        container.classList.add('hidden');
        emptyState.classList.remove('hidden');
        return;
      }

      container.classList.remove('hidden');
      emptyState.classList.add('hidden');

      container.innerHTML = discountCodes.map(code => {
        const ticketTypes = code.presale_code_ticket_types?.map(pct => pct.ticket_types?.name).filter(Boolean) || [];
        const validFrom = code.valid_from ? new Date(code.valid_from).toLocaleDateString() : 'No start date';
        const validUntil = code.valid_until ? new Date(code.valid_until).toLocaleDateString() : 'No end date';
        const used = code.usage_limit ? `${code.times_used || 0}/${code.usage_limit}` : (code.times_used || 0);
        
        return `
          <div class="bg-slate-50 rounded-2xl p-6 border border-slate-200">
            <div class="flex justify-between items-start">
              <div class="flex-1">
                <div class="flex items-center space-x-3 mb-3">
                  <h3 class="text-xl font-semibold text-slate-900 font-mono">${code.code}</h3>
                  <span class="px-3 py-1 bg-green-100 text-green-700 rounded-full text-sm font-medium">
                    ${code.discount_type === 'percentage' ? code.discount_value + '%' : '$' + code.discount_value} OFF
                  </span>
                  ${!code.is_active ? '<span class="px-3 py-1 bg-red-100 text-red-700 rounded-full text-sm font-medium">Inactive</span>' : ''}
                </div>
                
                ${code.description ? `<p class="text-slate-600 mb-3">${code.description}</p>` : ''}
                
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                  <div>
                    <span class="block text-slate-500">Usage</span>
                    <span class="font-semibold text-slate-900">${used}</span>
                  </div>
                  <div>
                    <span class="block text-slate-500">Valid From</span>
                    <span class="font-semibold text-slate-900">${validFrom}</span>
                  </div>
                  <div>
                    <span class="block text-slate-500">Valid Until</span>
                    <span class="font-semibold text-slate-900">${validUntil}</span>
                  </div>
                  <div>
                    <span class="block text-slate-500">Ticket Types</span>
                    <span class="font-semibold text-slate-900">${ticketTypes.length > 0 ? ticketTypes.join(', ') : 'All'}</span>
                  </div>
                </div>
              </div>
              
              <div class="flex space-x-2 ml-6">
                <button
                  onclick="editDiscountCode('${code.id}')"
                  class="text-slate-600 hover:text-slate-900 font-medium transition-colors duration-200"
                >
                  Edit
                </button>
                <button
                  onclick="toggleDiscountCode('${code.id}', ${!code.is_active})"
                  class="text-slate-600 hover:text-slate-900 font-medium transition-colors duration-200"
                >
                  ${code.is_active ? 'Deactivate' : 'Activate'}
                </button>
                <button
                  onclick="deleteDiscountCode('${code.id}')"
                  class="text-red-600 hover:text-red-800 font-medium transition-colors duration-200"
                >
                  Delete
                </button>
              </div>
            </div>
          </div>
        `;
      }).join('');

    } catch (error) {
      console.error('Error loading discount codes:', error);
    }
  }

  async function loadSettingsContent() {
    document.getElementById('settings-content').innerHTML = '<p class="text-slate-500">Event settings coming soon...</p>';
  }

  // Ticket type management functions
  function showTicketTypeModal() {
    currentTicketTypeId = null;
    document.getElementById('ticket-modal-title').textContent = 'Create Ticket Type';
    document.getElementById('ticket-submit-text').textContent = 'Create Ticket Type';
    ticketTypeForm.reset();
    ticketTypeModal.classList.remove('hidden');
  }

  async function editTicketType(ticketTypeId) {
    try {
      currentTicketTypeId = ticketTypeId;
      
      const { data: ticketType, error } = await supabase
        .from('ticket_types')
        .select('*')
        .eq('id', ticketTypeId)
        .single();

      if (error) throw error;

      // Populate form
      document.getElementById('ticket-name').value = ticketType.name || '';
      document.getElementById('ticket-price').value = ticketType.price || '';
      document.getElementById('ticket-quantity').value = ticketType.quantity_available || '';
      document.getElementById('ticket-sort-order').value = ticketType.sort_order || 0;
      document.getElementById('ticket-description').value = ticketType.description || '';
      // Handle sale start time
      if (ticketType.sale_start_time) {
        const startDate = new Date(ticketType.sale_start_time);
        document.getElementById('ticket-sale-start-date').value = startDate.toISOString().slice(0, 10);
        document.getElementById('ticket-sale-start-time').value = startDate.toTimeString().slice(0, 5);
      }
      
      // Handle sale end time
      if (ticketType.sale_end_time) {
        const endDate = new Date(ticketType.sale_end_time);
        document.getElementById('ticket-sale-end-date').value = endDate.toISOString().slice(0, 10);
        document.getElementById('ticket-sale-end-time').value = endDate.toTimeString().slice(0, 5);
      }

      document.getElementById('ticket-modal-title').textContent = 'Edit Ticket Type';
      document.getElementById('ticket-submit-text').textContent = 'Update Ticket Type';
      ticketTypeModal.classList.remove('hidden');

    } catch (error) {
      console.error('Error loading ticket type:', error);
      alert('Error loading ticket type data');
    }
  }

  function closeTicketTypeModal() {
    ticketTypeModal.classList.add('hidden');
    currentTicketTypeId = null;
  }

  async function toggleTicketType(ticketTypeId, isActive) {
    try {
      const { error } = await supabase
        .from('ticket_types')
        .update({ is_active: isActive })
        .eq('id', ticketTypeId);

      if (error) throw error;

      await loadTicketTypes();
    } catch (error) {
      console.error('Error toggling ticket type:', error);
      alert('Error updating ticket type status');
    }
  }

  async function deleteTicketType(ticketTypeId) {
    if (!confirm('Are you sure you want to delete this ticket type? This action cannot be undone.')) {
      return;
    }

    try {
      const { error } = await supabase
        .from('ticket_types')
        .delete()
        .eq('id', ticketTypeId);

      if (error) throw error;

      await loadTicketTypes();
      await loadEventStats();
    } catch (error) {
      console.error('Error deleting ticket type:', error);
      alert('Error deleting ticket type');
    }
  }

  // Save ticket type
  ticketTypeForm.addEventListener('submit', async (e) => {
    e.preventDefault();

    try {
      const formData = new FormData(ticketTypeForm);
      
      // Handle sale start time
      let saleStartTime = null;
      const startDate = formData.get('sale_start_date');
      const startTime = formData.get('sale_start_time_select');
      if (startDate && startTime) {
        saleStartTime = `${startDate}T${startTime}:00`;
      }
      
      // Handle sale end time
      let saleEndTime = null;
      const endDate = formData.get('sale_end_date');
      const endTime = formData.get('sale_end_time_select');
      if (endDate && endTime) {
        saleEndTime = `${endDate}T${endTime}:00`;
      }
      
      const ticketTypeData = {
        event_id: eventId,
        name: formData.get('name'),
        price: parseFloat(formData.get('price')),
        quantity_available: formData.get('quantity_available') ? parseInt(formData.get('quantity_available')) : null,
        sort_order: parseInt(formData.get('sort_order')) || 0,
        description: formData.get('description') || null,
        sale_start_time: saleStartTime,
        sale_end_time: saleEndTime,
        is_active: true
      };

      let error;
      if (currentTicketTypeId) {
        ({ error } = await supabase
          .from('ticket_types')
          .update(ticketTypeData)
          .eq('id', currentTicketTypeId));
      } else {
        ({ error } = await supabase
          .from('ticket_types')
          .insert([ticketTypeData]));
      }

      if (error) throw error;

      closeTicketTypeModal();
      await loadTicketTypes();
      await loadEventStats();

    } catch (error) {
      console.error('Error saving ticket type:', error);
      alert('Error saving ticket type: ' + error.message);
    }
  });

  // Load and save availability settings
  async function loadAvailabilitySettings() {
    if (!currentEvent) return;

    // Set form values from current event
    const mode = currentEvent.availability_display_mode || 'available_only';
    document.querySelector(`input[name="availability_display_mode"][value="${mode}"]`).checked = true;
    
    document.getElementById('availability_threshold').value = currentEvent.availability_threshold || 10;
    document.getElementById('low_stock_threshold').value = currentEvent.low_stock_threshold || 5;
    document.querySelector('input[name="show_sold_out"]').checked = currentEvent.show_sold_out !== false;

    // Set custom messages
    const messages = currentEvent.availability_messages || {};
    document.getElementById('msg_available').value = messages.available || 'Available';
    document.getElementById('msg_low_stock').value = messages.low_stock || '{count} left';
    document.getElementById('msg_sold_out').value = messages.sold_out || 'Sold out';
    document.getElementById('msg_unlimited').value = messages.unlimited || 'Available';

    updatePreview();
  }

  function updatePreview() {
    const mode = document.querySelector('input[name="availability_display_mode"]:checked').value;
    const threshold = parseInt(document.getElementById('availability_threshold').value);
    const lowStockThreshold = parseInt(document.getElementById('low_stock_threshold').value);
    
    const messages = {
      available: document.getElementById('msg_available').value,
      low_stock: document.getElementById('msg_low_stock').value,
      sold_out: document.getElementById('msg_sold_out').value,
      unlimited: document.getElementById('msg_unlimited').value
    };

    // Update preview examples
    const highStockEl = document.getElementById('preview-high-stock');
    const lowStockEl = document.getElementById('preview-low-stock');
    const soldOutEl = document.getElementById('preview-sold-out');

    // High stock (50 available)
    if (mode === 'show_quantity') {
      highStockEl.textContent = '50 available';
    } else if (mode === 'smart_threshold' && threshold >= 50) {
      highStockEl.textContent = '50 available';
    } else {
      highStockEl.textContent = messages.available;
    }

    // Low stock (3 available)
    if (mode === 'show_quantity') {
      lowStockEl.textContent = '3 available';
    } else if (mode === 'smart_threshold' && threshold >= 3) {
      lowStockEl.textContent = '3 available';
    } else if (lowStockThreshold >= 3) {
      lowStockEl.textContent = messages.low_stock.replace('{count}', '3');
    } else {
      lowStockEl.textContent = messages.available;
    }

    // Sold out
    soldOutEl.textContent = messages.sold_out;
  }

  async function saveAvailabilitySettings() {
    if (!currentEvent) return;

    try {
      const mode = document.querySelector('input[name="availability_display_mode"]:checked').value;
      const availabilityThreshold = parseInt(document.getElementById('availability_threshold').value);
      const lowStockThreshold = parseInt(document.getElementById('low_stock_threshold').value);
      const showSoldOut = document.querySelector('input[name="show_sold_out"]').checked;

      const messages = {
        available: document.getElementById('msg_available').value,
        low_stock: document.getElementById('msg_low_stock').value,
        sold_out: document.getElementById('msg_sold_out').value,
        unlimited: document.getElementById('msg_unlimited').value
      };

      const { error } = await supabase
        .from('events')
        .update({
          availability_display_mode: mode,
          availability_threshold: availabilityThreshold,
          low_stock_threshold: lowStockThreshold,
          show_sold_out: showSoldOut,
          availability_messages: messages
        })
        .eq('id', eventId);

      if (error) throw error;

      // Update current event object
      currentEvent.availability_display_mode = mode;
      currentEvent.availability_threshold = availabilityThreshold;
      currentEvent.low_stock_threshold = lowStockThreshold;
      currentEvent.show_sold_out = showSoldOut;
      currentEvent.availability_messages = messages;

      alert('Availability settings saved successfully!');

    } catch (error) {
      console.error('Error saving availability settings:', error);
      alert('Error saving settings: ' + error.message);
    }
  }

  // Event listeners - wrap in DOMContentLoaded to ensure DOM is ready
  function setupTabEventListeners() {
    const tabButtons = document.querySelectorAll('.tab-button');
    console.log('Found tab buttons:', tabButtons.length);
    
    tabButtons.forEach(btn => {
      console.log('Setting up listener for:', btn.id);
      btn.addEventListener('click', (e) => {
        const tabName = e.target.id.replace('tab-', '');
        console.log('Tab clicked:', tabName);
        switchTab(tabName);
        
        // Load settings when switching to settings tab
        if (tabName === 'settings') {
          setTimeout(loadAvailabilitySettings, 100);
        }
      });
    });
  }

  // Set up event listeners when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', setupTabEventListeners);
  } else {
    setupTabEventListeners();
  }

  // Settings event listeners
  document.addEventListener('DOMContentLoaded', () => {
    // Preview updates
    document.querySelectorAll('input[name="availability_display_mode"]').forEach(radio => {
      radio.addEventListener('change', updatePreview);
    });
    
    ['availability_threshold', 'low_stock_threshold', 'msg_available', 'msg_low_stock', 'msg_sold_out', 'msg_unlimited'].forEach(id => {
      const element = document.getElementById(id);
      if (element) {
        element.addEventListener('input', updatePreview);
      }
    });

    // Save button
    const saveBtn = document.getElementById('save-availability-settings');
    if (saveBtn) {
      saveBtn.addEventListener('click', saveAvailabilitySettings);
    }
  });

  document.getElementById('add-ticket-type-btn').addEventListener('click', showTicketTypeModal);
  document.getElementById('add-presale-code-btn').addEventListener('click', showPresaleCodeModal);
  document.getElementById('add-discount-code-btn').addEventListener('click', showDiscountCodeModal);
  
  logoutBtn.addEventListener('click', async () => {
    await supabase.auth.signOut();
    window.location.href = '/login';
  });

  // Presale code management functions
  let currentPresaleCodeId = null;
  const presaleCodeModal = document.getElementById('presale-code-modal');
  const presaleCodeForm = document.getElementById('presale-code-form');

  function showPresaleCodeModal() {
    currentPresaleCodeId = null;
    document.getElementById('presale-modal-title').textContent = 'Create Presale Code';
    document.getElementById('presale-submit-text').textContent = 'Create Presale Code';
    presaleCodeForm.reset();
    loadTicketTypesForPresaleCode();
    presaleCodeModal.classList.remove('hidden');
  }

  function closePresaleCodeModal() {
    presaleCodeModal.classList.add('hidden');
    currentPresaleCodeId = null;
  }

  async function loadTicketTypesForPresaleCode() {
    try {
      const { data: ticketTypes, error } = await supabase
        .from('ticket_types')
        .select('id, name')
        .eq('event_id', eventId)
        .eq('is_active', true)
        .order('sort_order', { ascending: true });

      if (error) throw error;

      const container = document.getElementById('ticket-types-checkboxes');
      container.innerHTML = ticketTypes.map(tt => `
        <label class="flex items-center space-x-2 p-2 border border-slate-200 rounded-lg hover:bg-slate-50">
          <input type="checkbox" name="ticket_types" value="${tt.id}" class="rounded border-slate-300">
          <span class="text-sm text-slate-700">${tt.name}</span>
        </label>
      `).join('');
    } catch (error) {
      console.error('Error loading ticket types:', error);
    }
  }

  async function editPresaleCode(presaleCodeId) {
    try {
      currentPresaleCodeId = presaleCodeId;
      
      const { data: presaleCode, error } = await supabase
        .from('presale_codes')
        .select(`
          *,
          presale_code_ticket_types (
            ticket_type_id
          )
        `)
        .eq('id', presaleCodeId)
        .single();

      if (error) throw error;

      // Populate form
      document.getElementById('presale-code').value = presaleCode.code || '';
      document.getElementById('presale-usage-limit').value = presaleCode.usage_limit || '';
      document.getElementById('presale-customer-usage-limit').value = presaleCode.customer_usage_limit || '';
      document.getElementById('presale-description').value = presaleCode.description || '';
      
      // Handle valid from time
      if (presaleCode.valid_from) {
        const fromDate = new Date(presaleCode.valid_from);
        document.getElementById('presale-valid-from-date').value = fromDate.toISOString().slice(0, 10);
        document.getElementById('presale-valid-from-time').value = fromDate.toTimeString().slice(0, 5);
      }
      
      // Handle valid until time
      if (presaleCode.valid_until) {
        const untilDate = new Date(presaleCode.valid_until);
        document.getElementById('presale-valid-until-date').value = untilDate.toISOString().slice(0, 10);
        document.getElementById('presale-valid-until-time').value = untilDate.toTimeString().slice(0, 5);
      }

      // Load ticket types and check the applicable ones
      await loadTicketTypesForPresaleCode();
      const applicableTicketTypes = presaleCode.presale_code_ticket_types?.map(pct => pct.ticket_type_id) || [];
      applicableTicketTypes.forEach(ticketTypeId => {
        const checkbox = document.querySelector(`input[name="ticket_types"][value="${ticketTypeId}"]`);
        if (checkbox) checkbox.checked = true;
      });

      document.getElementById('presale-modal-title').textContent = 'Edit Presale Code';
      document.getElementById('presale-submit-text').textContent = 'Update Presale Code';
      presaleCodeModal.classList.remove('hidden');

    } catch (error) {
      console.error('Error loading presale code:', error);
      alert('Error loading presale code data');
    }
  }

  async function togglePresaleCode(presaleCodeId, isActive) {
    try {
      const { error } = await supabase
        .from('presale_codes')
        .update({ is_active: isActive })
        .eq('id', presaleCodeId);

      if (error) throw error;

      await loadPresaleCodesContent();
    } catch (error) {
      console.error('Error toggling presale code:', error);
      alert('Error updating presale code status');
    }
  }

  async function deletePresaleCode(presaleCodeId) {
    if (!confirm('Are you sure you want to delete this presale code? This action cannot be undone.')) {
      return;
    }

    try {
      // Delete associated ticket type relations first
      await supabase
        .from('presale_code_ticket_types')
        .delete()
        .eq('presale_code_id', presaleCodeId);

      // Delete the presale code
      const { error } = await supabase
        .from('presale_codes')
        .delete()
        .eq('id', presaleCodeId);

      if (error) throw error;

      await loadPresaleCodesContent();
    } catch (error) {
      console.error('Error deleting presale code:', error);
      alert('Error deleting presale code');
    }
  }

  // Discount code management functions
  let currentDiscountCodeId = null;
  const discountCodeModal = document.getElementById('discount-code-modal');
  const discountCodeForm = document.getElementById('discount-code-form');

  function showDiscountCodeModal() {
    currentDiscountCodeId = null;
    document.getElementById('discount-modal-title').textContent = 'Create Discount Code';
    document.getElementById('discount-submit-text').textContent = 'Create Discount Code';
    discountCodeForm.reset();
    loadTicketTypesForDiscountCode();
    discountCodeModal.classList.remove('hidden');
  }

  function closeDiscountCodeModal() {
    discountCodeModal.classList.add('hidden');
    currentDiscountCodeId = null;
  }

  async function loadTicketTypesForDiscountCode() {
    try {
      const { data: ticketTypes, error } = await supabase
        .from('ticket_types')
        .select('id, name')
        .eq('event_id', eventId)
        .eq('is_active', true)
        .order('sort_order', { ascending: true });

      if (error) throw error;

      const container = document.getElementById('discount-ticket-types-checkboxes');
      container.innerHTML = ticketTypes.map(tt => `
        <label class="flex items-center space-x-2 p-2 border border-slate-200 rounded-lg hover:bg-slate-50">
          <input type="checkbox" name="discount_ticket_types" value="${tt.id}" class="rounded border-slate-300">
          <span class="text-sm text-slate-700">${tt.name}</span>
        </label>
      `).join('');
    } catch (error) {
      console.error('Error loading ticket types:', error);
    }
  }

  async function editDiscountCode(discountCodeId) {
    try {
      currentDiscountCodeId = discountCodeId;
      
      const { data: discountCode, error } = await supabase
        .from('presale_codes')
        .select(`
          *,
          presale_code_ticket_types (
            ticket_type_id
          )
        `)
        .eq('id', discountCodeId)
        .single();

      if (error) throw error;

      // Populate form
      document.getElementById('discount-code').value = discountCode.code || '';
      document.getElementById('discount-usage-limit').value = discountCode.usage_limit || '';
      document.getElementById('discount-customer-usage-limit').value = discountCode.customer_usage_limit || '';
      document.getElementById('discount-discount-type').value = discountCode.discount_type || '';
      document.getElementById('discount-discount-value').value = discountCode.discount_value || '';
      document.getElementById('discount-description').value = discountCode.description || '';
      
      // Handle valid from time
      if (discountCode.valid_from) {
        const fromDate = new Date(discountCode.valid_from);
        document.getElementById('discount-valid-from-date').value = fromDate.toISOString().slice(0, 10);
        document.getElementById('discount-valid-from-time').value = fromDate.toTimeString().slice(0, 5);
      }
      
      // Handle valid until time
      if (discountCode.valid_until) {
        const untilDate = new Date(discountCode.valid_until);
        document.getElementById('discount-valid-until-date').value = untilDate.toISOString().slice(0, 10);
        document.getElementById('discount-valid-until-time').value = untilDate.toTimeString().slice(0, 5);
      }

      // Load ticket types and check the applicable ones
      await loadTicketTypesForDiscountCode();
      const applicableTicketTypes = discountCode.presale_code_ticket_types?.map(pct => pct.ticket_type_id) || [];
      applicableTicketTypes.forEach(ticketTypeId => {
        const checkbox = document.querySelector(`input[name="discount_ticket_types"][value="${ticketTypeId}"]`);
        if (checkbox) checkbox.checked = true;
      });

      document.getElementById('discount-modal-title').textContent = 'Edit Discount Code';
      document.getElementById('discount-submit-text').textContent = 'Update Discount Code';
      discountCodeModal.classList.remove('hidden');

    } catch (error) {
      console.error('Error loading discount code:', error);
      alert('Error loading discount code data');
    }
  }

  async function toggleDiscountCode(discountCodeId, isActive) {
    try {
      const { error } = await supabase
        .from('presale_codes')
        .update({ is_active: isActive })
        .eq('id', discountCodeId);

      if (error) throw error;

      await loadDiscountCodesContent();
    } catch (error) {
      console.error('Error toggling discount code:', error);
      alert('Error updating discount code status');
    }
  }

  async function deleteDiscountCode(discountCodeId) {
    if (!confirm('Are you sure you want to delete this discount code? This action cannot be undone.')) {
      return;
    }

    try {
      // Delete associated ticket type relations first
      await supabase
        .from('presale_code_ticket_types')
        .delete()
        .eq('presale_code_id', discountCodeId);

      // Delete the discount code
      const { error } = await supabase
        .from('presale_codes')
        .delete()
        .eq('id', discountCodeId);

      if (error) throw error;

      await loadDiscountCodesContent();
    } catch (error) {
      console.error('Error deleting discount code:', error);
      alert('Error deleting discount code');
    }
  }

  // Form submission handlers
  presaleCodeForm.addEventListener('submit', async (e) => {
    e.preventDefault();

    try {
      const formData = new FormData(presaleCodeForm);
      
      // Handle valid from time
      let validFrom = null;
      const fromDate = formData.get('valid_from_date');
      const fromTime = formData.get('valid_from_time');
      if (fromDate && fromTime) {
        validFrom = `${fromDate}T${fromTime}:00`;
      }
      
      // Handle valid until time
      let validUntil = null;
      const untilDate = formData.get('valid_until_date');
      const untilTime = formData.get('valid_until_time');
      if (untilDate && untilTime) {
        validUntil = `${untilDate}T${untilTime}:00`;
      }
      
      const presaleCodeData = {
        event_id: eventId,
        code: formData.get('code').toUpperCase(),
        usage_limit: formData.get('usage_limit') ? parseInt(formData.get('usage_limit')) : null,
        customer_usage_limit: formData.get('customer_usage_limit') ? parseInt(formData.get('customer_usage_limit')) : null,
        discount_type: 'none', // Presale codes are access-only
        discount_value: null,
        valid_from: validFrom,
        valid_until: validUntil,
        description: formData.get('description') || null,
        is_active: true
      };

      let presaleCodeResult;
      if (currentPresaleCodeId) {
        const { data, error } = await supabase
          .from('presale_codes')
          .update(presaleCodeData)
          .eq('id', currentPresaleCodeId)
          .select()
          .single();
        if (error) throw error;
        presaleCodeResult = data;
      } else {
        const { data, error } = await supabase
          .from('presale_codes')
          .insert([presaleCodeData])
          .select()
          .single();
        if (error) throw error;
        presaleCodeResult = data;
      }

      // Handle ticket type associations
      const selectedTicketTypes = Array.from(document.querySelectorAll('input[name="ticket_types"]:checked'))
        .map(cb => cb.value);

      if (selectedTicketTypes.length > 0) {
        // Delete existing associations
        await supabase
          .from('presale_code_ticket_types')
          .delete()
          .eq('presale_code_id', presaleCodeResult.id);

        // Insert new associations
        const associations = selectedTicketTypes.map(ticketTypeId => ({
          presale_code_id: presaleCodeResult.id,
          ticket_type_id: ticketTypeId
        }));

        const { error: associationError } = await supabase
          .from('presale_code_ticket_types')
          .insert(associations);

        if (associationError) throw associationError;
      }

      closePresaleCodeModal();
      await loadPresaleCodesContent();

    } catch (error) {
      console.error('Error saving presale code:', error);
      alert('Error saving presale code: ' + error.message);
    }
  });

  discountCodeForm.addEventListener('submit', async (e) => {
    e.preventDefault();

    try {
      const formData = new FormData(discountCodeForm);
      
      // Handle valid from time
      let validFrom = null;
      const fromDate = formData.get('valid_from_date');
      const fromTime = formData.get('valid_from_time');
      if (fromDate && fromTime) {
        validFrom = `${fromDate}T${fromTime}:00`;
      }
      
      // Handle valid until time
      let validUntil = null;
      const untilDate = formData.get('valid_until_date');
      const untilTime = formData.get('valid_until_time');
      if (untilDate && untilTime) {
        validUntil = `${untilDate}T${untilTime}:00`;
      }
      
      const discountCodeData = {
        event_id: eventId,
        code: formData.get('code').toUpperCase(),
        usage_limit: formData.get('usage_limit') ? parseInt(formData.get('usage_limit')) : null,
        customer_usage_limit: formData.get('customer_usage_limit') ? parseInt(formData.get('customer_usage_limit')) : null,
        discount_type: formData.get('discount_type'),
        discount_value: parseFloat(formData.get('discount_value')),
        valid_from: validFrom,
        valid_until: validUntil,
        description: formData.get('description') || null,
        is_active: true
      };

      let discountCodeResult;
      if (currentDiscountCodeId) {
        const { data, error } = await supabase
          .from('presale_codes')
          .update(discountCodeData)
          .eq('id', currentDiscountCodeId)
          .select()
          .single();
        if (error) throw error;
        discountCodeResult = data;
      } else {
        const { data, error } = await supabase
          .from('presale_codes')
          .insert([discountCodeData])
          .select()
          .single();
        if (error) throw error;
        discountCodeResult = data;
      }

      // Handle ticket type associations
      const selectedTicketTypes = Array.from(document.querySelectorAll('input[name="discount_ticket_types"]:checked'))
        .map(cb => cb.value);

      if (selectedTicketTypes.length > 0) {
        // Delete existing associations
        await supabase
          .from('presale_code_ticket_types')
          .delete()
          .eq('presale_code_id', discountCodeResult.id);

        // Insert new associations
        const associations = selectedTicketTypes.map(ticketTypeId => ({
          presale_code_id: discountCodeResult.id,
          ticket_type_id: ticketTypeId
        }));

        const { error: associationError } = await supabase
          .from('presale_code_ticket_types')
          .insert(associations);

        if (associationError) throw associationError;
      }

      closeDiscountCodeModal();
      await loadDiscountCodesContent();

    } catch (error) {
      console.error('Error saving discount code:', error);
      alert('Error saving discount code: ' + error.message);
    }
  });

  // Seating Map Form Handler
  document.getElementById('seating-map-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    console.log('Seating map form submitted');
    
    try {
      const formData = new FormData(e.target);
      const layoutTypeRadio = document.querySelector('input[name="layout_type"]:checked');
      const layoutType = layoutTypeRadio ? layoutTypeRadio.value : 'theater';
      const name = formData.get('name');
      const venueName = formData.get('venue_name');
      const description = formData.get('description');
      const totalCapacity = parseInt(formData.get('total_capacity'));
      
      // Build layout data based on type
      let layoutData = { type: layoutType };
      let sections = [];
      
      switch (layoutType) {
        case 'theater':
          const rows = parseInt(document.getElementById('theater-rows')?.value || 10);
          const seatsPerRow = parseInt(document.getElementById('theater-seats-per-row')?.value || 10);
          sections.push({
            name: 'Orchestra',
            rows: rows,
            seatsPerRow: seatsPerRow,
            startRow: 'A',
            pricing: 'standard'
          });
          layoutData.dimensions = { width: seatsPerRow * 30 + 100, height: rows * 30 + 100 };
          break;
          
        case 'reception':
          const tables = parseInt(document.getElementById('reception-tables')?.value || 12);
          const seatsPerTable = parseInt(document.getElementById('reception-seats-per-table')?.value || 8);
          sections.push({
            name: 'Main Floor',
            tables: tables,
            seatsPerTable: seatsPerTable,
            tableNumbers: Array.from({length: tables}, (_, i) => i + 1)
          });
          layoutData.dimensions = { width: 600, height: 500 };
          break;
          
        case 'concert_hall':
          const gaCapacity = parseInt(document.getElementById('concert-ga-capacity')?.value || 300);
          const reservedCapacity = parseInt(document.getElementById('concert-reserved-capacity')?.value || 200);
          if (gaCapacity > 0) {
            sections.push({
              name: 'Floor',
              type: 'general_admission',
              capacity: gaCapacity
            });
          }
          if (reservedCapacity > 0) {
            sections.push({
              name: 'Balcony',
              rows: Math.ceil(reservedCapacity / 20),
              seatsPerRow: 20,
              startRow: 'AA',
              pricing: 'premium'
            });
          }
          layoutData.dimensions = { width: 800, height: 600 };
          break;
          
        default:
          sections.push({
            name: 'General Admission',
            capacity: totalCapacity,
            type: 'standard'
          });
          layoutData.dimensions = { width: 400, height: 300 };
          break;
      }
      
      layoutData.sections = sections;
      
      // Include custom layout positions from the editor
      if (layoutItems && layoutItems.length > 0) {
        layoutData.customPositions = layoutItems.map(item => ({
          id: item.id,
          type: item.type,
          x: item.x,
          y: item.y,
          width: item.width,
          height: item.height,
          label: item.label,
          tableNumber: item.tableNumber,
          row: item.row,
          seatNumber: item.seatNumber,
          section: item.section,
          capacity: item.capacity,
          seatsPerTable: item.seatsPerTable
        }));
      }
      
      // Add labeling scheme
      layoutData.labeling = {
        rowStyle: document.getElementById('row-labeling-style')?.value || 'letters',
        seatStyle: document.getElementById('seat-labeling-style')?.value || '1-n',
        rowStartValue: document.getElementById('row-start-value')?.value || 'A',
        seatStartNumber: parseInt(document.getElementById('seat-start-number')?.value || 1),
        tableNumberingStyle: document.getElementById('table-numbering-style')?.value || 'sequential',
        tableStartNumber: parseInt(document.getElementById('table-start-number')?.value || 1)
      };
      
      const isEditing = e.target.dataset.editingId;
      let error;

      if (isEditing) {
        // Update existing seating map
        const { error: updateError } = await supabase
          .from('seating_maps')
          .update({
            name: name,
            venue_name: venueName,
            description: description,
            total_capacity: totalCapacity,
            layout_data: layoutData
          })
          .eq('id', isEditing);
        error = updateError;
      } else {
        // Create new seating map
        const { error: insertError } = await supabase
          .from('seating_maps')
          .insert({
            name: name,
            venue_name: venueName,
            description: description,
            total_capacity: totalCapacity,
            organization_id: organizationId,
            layout_data: layoutData
          });
        error = insertError;
      }

      if (error) throw error;

      closeSeatingMapModal();
      await loadVenueContent();
      showToast(`Seating map ${isEditing ? 'updated' : 'created'} successfully!`, 'success');
      
    } catch (error) {
      console.error('Error creating seating map:', error);
      showToast('Error creating seating map: ' + error.message, 'error');
    }
  });

  // Add-ons Management Functions
  async function loadAddonsContent() {
    try {
      console.log('Loading add-ons content for event:', eventId, 'organization:', organizationId);
      
      // Ensure user is loaded and organizationId is available
      if (!organizationId) {
        console.log('Organization ID not available, loading user first...');
        await loadUserData();
        
        if (!organizationId) {
          throw new Error('Unable to load organization information. Please refresh the page and try again.');
        }
      }

      // Load available add-ons and current event add-ons
      const [availableAddons, currentAddons] = await Promise.all([
        supabase.rpc('get_available_addons', {
          p_organization_id: organizationId,
          p_event_id: eventId
        }),
        supabase
          .from('event_add_ons')
          .select(`
            *,
            add_on_types (
              slug,
              name,
              description,
              price_cents,
              category
            )
          `)
          .eq('event_id', eventId)
          .eq('status', 'active')
      ]);

      if (availableAddons.error) throw availableAddons.error;
      if (currentAddons.error) throw currentAddons.error;

      renderCurrentAddons(currentAddons.data || []);
      renderAvailableAddons(availableAddons.data || []);

    } catch (error) {
      console.error('Error loading add-ons:', error);
      document.getElementById('current-addons-list').innerHTML = 
        '<p class="text-red-600">Error loading add-ons. Please try again.</p>';
    }
  }

  function renderCurrentAddons(addons) {
    const container = document.getElementById('current-addons-list');
    
    // Always include the Embed Widget as an active feature
    const embedWidgetHtml = `
      <div class="flex items-center justify-between p-4 bg-blue-50 rounded-xl border border-blue-200">
        <div class="flex items-center space-x-4">
          <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
            <span class="text-2xl">🎫</span>
          </div>
          <div>
            <h4 class="font-semibold text-gray-900">Embed Widget</h4>
            <p class="text-sm text-gray-600">Add a customizable ticket widget to any website</p>
            <p class="text-sm text-blue-700 font-medium">Built-in feature</p>
          </div>
        </div>
        <div class="flex items-center space-x-3">
          <div class="text-right">
            <div class="text-lg font-bold text-green-600">FREE</div>
            <div class="text-sm text-gray-600">Active</div>
          </div>
          <button
            onclick="openEmbedWidgetModal()"
            class="px-4 py-2 bg-blue-100 hover:bg-blue-200 text-blue-700 rounded-lg text-sm font-medium transition-colors"
          >
            Get Code
          </button>
        </div>
      </div>
    `;

    const paidAddons = addons.map(addon => `
      <div class="flex items-center justify-between p-4 bg-green-50 rounded-xl border border-green-200">
        <div class="flex items-center space-x-4">
          <div class="w-12 h-12 bg-green-100 rounded-xl flex items-center justify-center">
            <span class="text-2xl">${getCategoryIcon(addon.add_on_types.category)}</span>
          </div>
          <div>
            <h4 class="font-semibold text-gray-900">${addon.add_on_types.name}</h4>
            <p class="text-sm text-gray-600">${addon.add_on_types.description}</p>
            <p class="text-sm text-green-700 font-medium">
              Purchased on ${new Date(addon.purchased_at).toLocaleDateString()}
            </p>
          </div>
        </div>
        <div class="flex items-center space-x-3">
          <div class="text-right">
            <div class="text-lg font-bold text-gray-900">$${(addon.purchase_price_cents / 100).toFixed(2)}</div>
            <div class="text-sm text-gray-600">Paid</div>
          </div>
          <button
            onclick="removeAddon('${addon.id}')"
            class="px-4 py-2 bg-red-100 hover:bg-red-200 text-red-700 rounded-lg text-sm font-medium transition-colors"
          >
            Remove
          </button>
        </div>
      </div>
    `).join('');

    container.innerHTML = embedWidgetHtml + paidAddons;
  }

  function renderAvailableAddons(addons) {
    const container = document.getElementById('available-addons-list');
    
    // Filter out add-ons that are already active
    const availableAddons = addons.filter(addon => !addon.has_access);
    
    // Separate available add-ons: only show Custom Event Branding, hide the rest in "Coming Soon"
    // Exclude Premium Analytics since it's now built-in/free
    const visibleAddons = availableAddons.filter(addon => addon.slug === 'custom-event-branding');
    const comingSoonAddons = availableAddons.filter(addon => 
      addon.slug !== 'custom-event-branding' && 
      addon.slug !== 'premium-analytics'
    );
    
    // Available add-ons (currently just Custom Event Branding)
    const visibleAddonCards = visibleAddons.map(addon => `
      <div class="border border-gray-200 rounded-xl p-6 hover:border-gray-300 transition-colors">
        <div class="flex items-start justify-between mb-4">
          <div class="flex items-center space-x-3">
            <div class="w-12 h-12 bg-gray-100 rounded-xl flex items-center justify-center">
              <span class="text-2xl">${getCategoryIcon(addon.category)}</span>
            </div>
            <div>
              <h4 class="font-semibold text-gray-900">${addon.name}</h4>
              <p class="text-sm text-gray-600">${addon.description}</p>
            </div>
          </div>
        </div>
        <div class="flex items-center justify-between">
          <div class="text-2xl font-bold text-gray-900">$${(addon.price_cents / 100).toFixed(2)}</div>
          <button
            onclick="purchaseAddon('${addon.addon_id}', '${addon.name}', ${addon.price_cents})"
            class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-sm font-medium transition-colors"
          >
            Add to Event
          </button>
        </div>
      </div>
    `).join('');

    // Coming Soon section
    const comingSoonSection = comingSoonAddons.length > 0 ? `
      <div class="col-span-full mt-12">
        <div class="border-t border-gray-200 pt-8">
          <div class="flex items-center mb-6">
            <h3 class="text-xl font-light text-slate-900 tracking-wide">Coming Soon</h3>
            <span class="ml-3 inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-gradient-to-r from-amber-100 to-orange-100 text-amber-700">
              📅 In Development
            </span>
          </div>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            ${comingSoonAddons.map(addon => `
              <div class="border border-gray-200 rounded-xl p-6 bg-gray-50 opacity-75">
                <div class="flex items-start justify-between mb-4">
                  <div class="flex items-center space-x-3">
                    <div class="w-12 h-12 bg-gray-200 rounded-xl flex items-center justify-center">
                      <span class="text-2xl opacity-50">${getCategoryIcon(addon.category)}</span>
                    </div>
                    <div>
                      <h4 class="font-semibold text-gray-700">${addon.name}</h4>
                      <p class="text-sm text-gray-500">${addon.description}</p>
                    </div>
                  </div>
                </div>
                <div class="flex items-center justify-between">
                  <div class="text-lg font-bold text-gray-500">$${(addon.price_cents / 100).toFixed(2)}</div>
                  <div class="px-4 py-2 bg-gray-200 text-gray-500 rounded-lg text-sm font-medium cursor-not-allowed">
                    Coming Soon
                  </div>
                </div>
              </div>
            `).join('')}
          </div>
          <div class="mt-6 text-center">
            <p class="text-sm text-gray-600">
              💡 These features are currently in development. 
              <a href="mailto:support@blackcanyontickets.com" class="text-indigo-600 hover:text-indigo-700 font-medium">Contact us</a> 
              to be notified when they're available.
            </p>
          </div>
        </div>
      </div>
    ` : '';

    container.innerHTML = visibleAddonCards + comingSoonSection;
  }

  function getCategoryIcon(category) {
    const icons = {
      feature: '⚡',
      service: '🎯',
      analytics: '📊',
      marketing: '📢',
      subscription: '⭐'
    };
    return icons[category] || '🔧';
  }

  async function purchaseAddon(addonId, addonName, priceCents) {
    try {
      const confirmed = confirm(`Add ${addonName} to your event for $${(priceCents / 100).toFixed(2)}?`);
      if (!confirmed) return;

      const { error } = await supabase
        .from('event_add_ons')
        .insert([{
          event_id: eventId,
          add_on_type_id: addonId,
          organization_id: organizationId,
          purchase_price_cents: priceCents,
          status: 'active'
        }]);

      if (error) throw error;

      // Reload the add-ons content
      await loadAddonsContent();
      
      alert(`${addonName} has been added to your event!`);
    } catch (error) {
      console.error('Error purchasing add-on:', error);
      alert('Error adding add-on. Please try again.');
    }
  }

  async function removeAddon(addonId) {
    try {
      const confirmed = confirm('Are you sure you want to remove this add-on from your event?');
      if (!confirmed) return;

      const { error } = await supabase
        .from('event_add_ons')
        .update({ status: 'cancelled' })
        .eq('id', addonId);

      if (error) throw error;

      // Reload the add-ons content
      await loadAddonsContent();
      
      alert('Add-on has been removed from your event.');
    } catch (error) {
      console.error('Error removing add-on:', error);
      alert('Error removing add-on. Please try again.');
    }
  }


  // Make functions globally available
  window.showTicketTypeModal = showTicketTypeModal;
  window.editTicketType = editTicketType;
  window.deleteTicketType = deleteTicketType;
  window.toggleTicketType = toggleTicketType;
  window.closeTicketTypeModal = closeTicketTypeModal;
  window.showPresaleCodeModal = showPresaleCodeModal;
  window.editPresaleCode = editPresaleCode;
  window.deletePresaleCode = deletePresaleCode;
  window.togglePresaleCode = togglePresaleCode;
  window.closePresaleCodeModal = closePresaleCodeModal;
  window.showDiscountCodeModal = showDiscountCodeModal;
  window.editDiscountCode = editDiscountCode;
  window.deleteDiscountCode = deleteDiscountCode;
  window.toggleDiscountCode = toggleDiscountCode;
  window.closeDiscountCodeModal = closeDiscountCodeModal;
  window.openSeatingMapModal = openSeatingMapModal;
  window.closeSeatingMapModal = closeSeatingMapModal;
  window.updateLayoutPreview = updateLayoutPreview;
  window.updateModalPreview = updateModalPreview;
  window.previewSeatingMap = previewSeatingMap;
  window.useSeatingMap = useSeatingMap;
  window.deleteSeatingMap = deleteSeatingMap;
  window.openEmbedWidgetModal = openEmbedWidgetModal;
  window.closeEmbedWidgetModal = closeEmbedWidgetModal;
  window.openCustomizationPage = openCustomizationPage;
  window.copyDirectLink = copyDirectLink;
  window.copyBasicEmbedCode = copyBasicEmbedCode;
  window.editSeatingMap = editSeatingMap;
  window.updateEventSeating = updateEventSeating;
  window.initializeLayoutEditor = initializeLayoutEditor;
  window.addTable = addTable;
  window.addSeatRow = addSeatRow;
  window.addGeneralArea = addGeneralArea;
  window.resetLayout = resetLayout;
  // Ticket management functions
  async function viewTicket(ticketUuid) {
    try {
      const { data: ticket, error } = await supabase
        .from('tickets')
        .select(`
          *,
          ticket_types (name),
          events (title, venue, start_time)
        `)
        .eq('uuid', ticketUuid)
        .single();

      if (error) throw error;

      const modalHtml = `
        <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" onclick="closeModal()">
          <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4" onclick="event.stopPropagation()">
            <div class="flex justify-between items-center mb-4">
              <h3 class="text-lg font-semibold text-slate-900">Ticket Details</h3>
              <button onclick="closeModal()" class="text-slate-400 hover:text-slate-600">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
              </button>
            </div>
            <div class="space-y-3">
              <div>
                <label class="text-sm font-medium text-slate-700">Ticket ID</label>
                <p class="font-mono text-sm text-slate-600">${ticket.uuid}</p>
              </div>
              <div>
                <label class="text-sm font-medium text-slate-700">Customer</label>
                <p class="text-sm text-slate-900">${ticket.purchaser_name || 'Not provided'}</p>
                <p class="text-sm text-slate-600">${ticket.purchaser_email}</p>
              </div>
              <div>
                <label class="text-sm font-medium text-slate-700">Event</label>
                <p class="text-sm text-slate-900">${ticket.events.title}</p>
              </div>
              <div>
                <label class="text-sm font-medium text-slate-700">Type & Price</label>
                <p class="text-sm text-slate-900">${ticket.ticket_types?.name || 'General'} - $${ticket.price}</p>
              </div>
              <div>
                <label class="text-sm font-medium text-slate-700">Seat</label>
                <p class="text-sm text-slate-900">${ticket.seat_number || 'General Admission'}</p>
              </div>
              <div>
                <label class="text-sm font-medium text-slate-700">Status</label>
                <p class="text-sm ${ticket.checked_in ? 'text-green-600' : 'text-yellow-600'}">${ticket.checked_in ? 'Checked In' : 'Not Checked In'}</p>
                ${ticket.scanned_at ? `<p class="text-xs text-slate-500">Scanned at: ${new Date(ticket.scanned_at).toLocaleString()}</p>` : ''}
              </div>
              <div>
                <label class="text-sm font-medium text-slate-700">Purchase Date</label>
                <p class="text-sm text-slate-900">${new Date(ticket.created_at).toLocaleString()}</p>
              </div>
            </div>
            <div class="mt-6 flex space-x-3">
              <button onclick="closeModal()" class="flex-1 bg-slate-200 hover:bg-slate-300 text-slate-800 py-2 px-4 rounded-lg font-medium">
                Close
              </button>
              ${!ticket.checked_in ? `
                <button onclick="checkInTicket('${ticket.id}'); closeModal()" class="flex-1 bg-green-600 hover:bg-green-700 text-white py-2 px-4 rounded-lg font-medium">
                  Check In
                </button>
              ` : ''}
            </div>
          </div>
        </div>
      `;

      document.body.insertAdjacentHTML('beforeend', modalHtml);
    } catch (error) {
      console.error('Error viewing ticket:', error);
      alert('Error loading ticket details');
    }
  }

  async function checkInTicket(ticketId) {
    try {
      const { error } = await supabase
        .from('tickets')
        .update({ 
          checked_in: true, 
          scanned_at: new Date().toISOString() 
        })
        .eq('id', ticketId);

      if (error) throw error;

      // Refresh the tickets table
      loadSalesContent();
      alert('Ticket checked in successfully!');
    } catch (error) {
      console.error('Error checking in ticket:', error);
      alert('Error checking in ticket');
    }
  }

  // Dropdown toggle function
  function toggleRefundDropdown(ticketId) {
    // Close all other dropdowns first
    document.querySelectorAll('[id^="refund-dropdown-"]').forEach(dropdown => {
      if (dropdown.id !== `refund-dropdown-${ticketId}`) {
        dropdown.classList.add('hidden');
      }
    });
    
    // Toggle the clicked dropdown
    const dropdown = document.getElementById(`refund-dropdown-${ticketId}`);
    dropdown.classList.toggle('hidden');
  }

  // Close dropdowns when clicking outside
  document.addEventListener('click', function(event) {
    if (!event.target.closest('[id^="refund-dropdown-"]') && !event.target.matches('[onclick*="toggleRefundDropdown"]')) {
      document.querySelectorAll('[id^="refund-dropdown-"]').forEach(dropdown => {
        dropdown.classList.add('hidden');
      });
    }
  });

  // Refund functions - safer version with multiple confirmations
  async function initiateRefund(ticketId, ticketPrice, customerName) {
    // Close the dropdown
    document.getElementById(`refund-dropdown-${ticketId}`).classList.add('hidden');
    
    // First confirmation with warning
    if (!confirm(`⚠️ WARNING: You are about to process a refund\n\nCustomer: ${customerName}\nTicket Price: $${ticketPrice}\n\nThis action cannot be undone and will immediately charge fees.\n\nAre you sure you want to continue?`)) {
      return;
    }

    const reason = prompt(`Enter refund reason for ${customerName}:`);
    if (!reason || reason.trim() === '') {
      alert('Refund reason is required');
      return;
    }

    const amount = prompt(`Enter refund amount (max: $${ticketPrice}):`, ticketPrice);
    if (!amount || isNaN(amount) || parseFloat(amount) <= 0 || parseFloat(amount) > parseFloat(ticketPrice)) {
      alert('Invalid refund amount');
      return;
    }

    // Final confirmation
    if (!confirm(`FINAL CONFIRMATION:\n\nRefund $${amount} to ${customerName}\nReason: ${reason}\n\nThis will immediately process the refund through Stripe.\n\nClick OK to proceed or Cancel to abort.`)) {
      return;
    }

    try {
      const response = await fetch('/api/refunds/process', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ticket_id: ticketId,
          refund_amount: parseFloat(amount),
          reason: reason
        })
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || 'Failed to process refund');
      }

      alert(`Refund processed successfully! Amount: $${amount}`);
      
      // Refresh both sales and attendees content
      await loadSalesContent();
      await loadAttendeesContent();
      
    } catch (error) {
      console.error('Error processing refund:', error);
      alert('Error processing refund: ' + error.message);
    }
  }

  async function refundAttendee(email) {
    if (!confirm(`Refund all tickets for ${email}?`)) {
      return;
    }

    const reason = prompt('Enter refund reason:');
    if (!reason) return;

    try {
      // Get all tickets for this attendee
      const { data: tickets, error } = await supabase
        .from('tickets')
        .select('*')
        .eq('event_id', eventId)
        .eq('purchaser_email', email)
        .eq('refund_status', 'none');

      if (error) throw error;

      if (tickets.length === 0) {
        alert('No tickets found to refund for this attendee');
        return;
      }

      // Process refunds for all tickets
      const refundPromises = tickets.map(ticket => 
        fetch('/api/refunds/process', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            ticket_id: ticket.id,
            refund_amount: parseFloat(ticket.price),
            reason: reason
          })
        })
      );

      const results = await Promise.all(refundPromises);
      const successCount = results.filter(r => r.ok).length;

      alert(`Processed ${successCount} of ${tickets.length} refunds successfully`);
      
      // Refresh content
      await loadSalesContent();
      await loadAttendeesContent();
      
    } catch (error) {
      console.error('Error processing refunds:', error);
      alert('Error processing refunds: ' + error.message);
    }
  }

  async function viewAttendeeDetails(email) {
    try {
      const { data: tickets, error } = await supabase
        .from('tickets')
        .select(`
          *,
          ticket_types (
            name,
            price
          )
        `)
        .eq('event_id', eventId)
        .eq('purchaser_email', email)
        .order('created_at', { ascending: false });

      if (error) throw error;

      const attendee = tickets[0];
      const totalSpent = tickets.reduce((sum, ticket) => sum + parseFloat(ticket.price), 0);
      const checkedInCount = tickets.filter(t => t.checked_in).length;
      const refundedCount = tickets.filter(t => t.refund_status !== 'none').length;

      const modalHtml = `
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div class="bg-white rounded-2xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
            <div class="p-6 border-b border-slate-200">
              <div class="flex justify-between items-start">
                <div>
                  <h2 class="text-2xl font-light text-slate-900">${attendee.purchaser_name || 'Not provided'}</h2>
                  <p class="text-slate-600">${email}</p>
                  <div class="flex items-center space-x-6 mt-2 text-sm text-slate-500">
                    <span>${tickets.length} tickets</span>
                    <span>$${totalSpent.toFixed(2)} total</span>
                    <span>${checkedInCount} checked in</span>
                    ${refundedCount > 0 ? `<span class="text-red-600">${refundedCount} refunded</span>` : ''}
                  </div>
                </div>
                <button onclick="closeModal()" class="text-slate-400 hover:text-slate-600">
                  <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                  </svg>
                </button>
              </div>
            </div>
            <div class="p-6">
              <h3 class="text-lg font-medium text-slate-900 mb-4">Tickets</h3>
              <div class="overflow-x-auto">
                <table class="w-full">
                  <thead class="bg-slate-50 border-b border-slate-200">
                    <tr>
                      <th class="text-left py-3 px-4 font-medium text-slate-700">Ticket ID</th>
                      <th class="text-left py-3 px-4 font-medium text-slate-700">Type</th>
                      <th class="text-left py-3 px-4 font-medium text-slate-700">Price</th>
                      <th class="text-left py-3 px-4 font-medium text-slate-700">Status</th>
                      <th class="text-left py-3 px-4 font-medium text-slate-700">Actions</th>
                    </tr>
                  </thead>
                  <tbody class="divide-y divide-slate-200">
                    ${tickets.map(ticket => `
                      <tr>
                        <td class="py-3 px-4 font-mono text-sm">${ticket.uuid.substring(0, 8)}...</td>
                        <td class="py-3 px-4">${ticket.ticket_types?.name || 'General'}</td>
                        <td class="py-3 px-4">$${ticket.price}</td>
                        <td class="py-3 px-4">
                          <div class="flex items-center space-x-2">
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${ticket.checked_in ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}">
                              ${ticket.checked_in ? 'Checked In' : 'Not Checked In'}
                            </span>
                            ${ticket.refund_status !== 'none' ? `
                              <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                ${ticket.refund_status.replace('_', ' ')}
                              </span>
                            ` : ''}
                          </div>
                        </td>
                        <td class="py-3 px-4 w-32">
                          <div class="flex items-center justify-start space-x-2 min-h-[32px]">
                            <div class="w-20 flex justify-center">
                              ${!ticket.checked_in ? `
                                <button 
                                  onclick="checkInTicket('${ticket.id}')"
                                  class="text-green-600 hover:text-green-900 text-sm font-medium whitespace-nowrap"
                                >
                                  Check In
                                </button>
                              ` : `
                                <span class="text-xs text-green-600 font-medium">✓ Checked</span>
                              `}
                            </div>
                            <div class="w-16 flex justify-end">
                              ${ticket.refund_status === 'none' ? `
                                <div class="relative inline-block text-left">
                                  <button 
                                    onclick="toggleRefundDropdown('attendee-${ticket.id}')"
                                    class="text-slate-500 hover:text-slate-700 text-xs border border-slate-300 hover:border-slate-400 rounded px-2 py-1 transition-colors whitespace-nowrap"
                                  >
                                    ⋯ More
                                  </button>
                                  <div id="refund-dropdown-attendee-${ticket.id}" class="hidden absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg z-10 border border-slate-200">
                                    <div class="py-1">
                                      <button 
                                        onclick="initiateRefund('${ticket.id}', '${ticket.price}', '${attendee.purchaser_name || email}')"
                                        class="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors"
                                      >
                                        🔄 Process Refund
                                      </button>
                                    </div>
                                  </div>
                                </div>
                              ` : `
                                <span class="text-xs text-slate-500 capitalize whitespace-nowrap">${ticket.refund_status.replace('_', ' ')}</span>
                              `}
                            </div>
                          </div>
                        </td>
                      </tr>
                    `).join('')}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      `;

      document.body.insertAdjacentHTML('beforeend', modalHtml);
    } catch (error) {
      console.error('Error viewing attendee details:', error);
      alert('Error loading attendee details');
    }
  }

  async function exportGuestList() {
    try {
      const { data: tickets, error } = await supabase
        .from('tickets')
        .select(`
          *,
          ticket_types (
            name,
            price
          )
        `)
        .eq('event_id', eventId)
        .order('created_at', { ascending: false });

      if (error) throw error;

      // Create CSV content
      const csvHeaders = ['Name', 'Email', 'Ticket Type', 'Price', 'Checked In', 'Refund Status', 'Purchase Date'];
      const csvRows = tickets.map(ticket => [
        ticket.purchaser_name || '',
        ticket.purchaser_email,
        ticket.ticket_types?.name || 'General',
        `$${ticket.price}`,
        ticket.checked_in ? 'Yes' : 'No',
        ticket.refund_status || 'none',
        new Date(ticket.created_at).toLocaleDateString()
      ]);

      const csvContent = [csvHeaders, ...csvRows]
        .map(row => row.map(cell => `"${cell}"`).join(','))
        .join('\n');

      // Download CSV
      const blob = new Blob([csvContent], { type: 'text/csv' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `guest-list-${eventId}.csv`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('Error exporting guest list:', error);
      alert('Error exporting guest list');
    }
  }

  function closeModal() {
    const modal = document.querySelector('.fixed.inset-0');
    if (modal) {
      modal.remove();
    }
  }

  window.autoArrangeLayout = autoArrangeLayout;
  window.clearLayout = clearLayout;
  window.purchaseAddon = purchaseAddon;
  window.removeAddon = removeAddon;
  window.viewTicket = viewTicket;
  window.checkInTicket = checkInTicket;
  window.initiateRefund = initiateRefund;
  window.toggleRefundDropdown = toggleRefundDropdown;
  window.refundAttendee = refundAttendee;
  window.viewAttendeeDetails = viewAttendeeDetails;
  window.exportGuestList = exportGuestList;
  window.searchSales = searchSales;
  window.clearSalesFilters = clearSalesFilters;
  window.switchTab = switchTab;
  window.closeModal = closeModal;

  // Initialize
  checkAuth().then(session => {
    if (session) {
      console.log('Session found, loading event...');
      loadEvent();
      
      // Initialize first tab as active after a short delay to ensure DOM is ready
      setTimeout(() => {
        switchTab('tickets');
      }, 100);
    } else {
      console.log('No session in initialization');
    }
  }).catch(error => {
    console.error('Error during initialization:', error);
  });
</script>

<style>
  .line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
</style>