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

// Get query parameters for filtering
const url = new URL(Astro.request.url);
const featured = url.searchParams.get('featured');
const category = url.searchParams.get('category');
const search = url.searchParams.get('search');
---

<Layout title="Event Calendar - Black Canyon Tickets">
  <div class="min-h-screen">
    <!-- Hero Section with Dynamic Background -->
    <section class="relative overflow-hidden bg-gradient-to-br from-indigo-900 via-purple-900 to-slate-900">
      <PublicHeader showCalendarNav={true} />
      <!-- Animated Background Elements -->
      <div class="absolute inset-0 opacity-20">
        <div class="absolute top-20 left-20 w-64 h-64 bg-gradient-to-br from-blue-400 to-purple-500 rounded-full blur-3xl animate-pulse"></div>
        <div class="absolute bottom-20 right-20 w-96 h-96 bg-gradient-to-br from-purple-400 to-pink-500 rounded-full blur-3xl animate-pulse delay-1000"></div>
        <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-80 h-80 bg-gradient-to-br from-cyan-400 to-blue-500 rounded-full blur-3xl animate-pulse delay-500"></div>
      </div>
      
      <!-- Geometric Patterns -->
      <div class="absolute inset-0 opacity-10">
        <svg class="w-full h-full" viewBox="0 0 100 100" preserveAspectRatio="none">
          <defs>
            <pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse">
              <path d="M 10 0 L 0 0 0 10" fill="none" stroke="white" stroke-width="0.5"/>
            </pattern>
          </defs>
          <rect width="100" height="100" fill="url(#grid)" />
        </svg>
      </div>
      
      <div class="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-32 pb-24 lg:pt-40 lg:pb-32">
        <div class="text-center">
          <!-- Badge -->
          <div class="inline-flex items-center px-4 py-2 rounded-full bg-white/10 backdrop-blur-lg border border-white/20 mb-8">
            <span class="text-sm font-medium text-white/90">✨ Discover Extraordinary Events</span>
          </div>
          
          <!-- Main Heading -->
          <h1 class="text-5xl lg:text-7xl font-light text-white mb-6 tracking-tight">
            Event
            <span class="font-bold bg-gradient-to-r from-blue-400 via-purple-400 to-pink-400 bg-clip-text text-transparent">
              Calendar
            </span>
          </h1>
          
          <!-- Subheading -->
          <p class="text-xl lg:text-2xl text-white/80 mb-12 max-w-3xl mx-auto leading-relaxed">
            Curated experiences in Colorado's most prestigious venues. From intimate galas to grand celebrations.
          </p>
          
          <!-- Advanced Search Bar -->
          <div class="max-w-2xl mx-auto">
            <div class="relative group">
              <div class="absolute inset-0 bg-gradient-to-r from-blue-600 to-purple-600 rounded-2xl blur opacity-20 group-hover:opacity-30 transition-opacity"></div>
              <div class="relative bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl p-2 flex items-center space-x-2">
                <div class="flex-1 flex items-center space-x-3 px-4">
                  <svg class="w-5 h-5 text-white/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                  </svg>
                  <input 
                    type="text" 
                    id="search-input"
                    placeholder="Search events, venues, or organizers..." 
                    class="bg-transparent text-white placeholder-white/60 focus:outline-none flex-1 text-lg"
                    value={search || ''}
                  />
                </div>
                <button 
                  id="search-btn"
                  class="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white px-8 py-3 rounded-xl font-semibold transition-all duration-200 shadow-lg hover:shadow-xl"
                >
                  Search
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- Filter Controls -->
    <section class="sticky top-0 z-50 bg-white/95 backdrop-blur-xl border-b border-gray-200/50 shadow-lg">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        <div class="flex flex-wrap items-center justify-between gap-4">
          <!-- View Toggle -->
          <div class="flex items-center space-x-2">
            <span class="text-sm font-medium text-gray-700">View:</span>
            <div class="bg-gray-100 rounded-lg p-1 flex border border-gray-200">
              <button 
                id="calendar-view-btn" 
                class="px-4 py-2 rounded-md text-sm font-medium transition-all duration-200 bg-white shadow-sm text-gray-900"
              >
                <svg class="w-4 h-4 inline mr-2" 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>
                Calendar
              </button>
              <button 
                id="list-view-btn" 
                class="px-4 py-2 rounded-md text-sm font-medium transition-all duration-200 text-gray-600 hover:text-gray-900 hover:bg-gray-50"
              >
                <svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"></path>
                </svg>
                List
              </button>
            </div>
          </div>

          <!-- Advanced Filters -->
          <div class="flex flex-wrap items-center space-x-4">
            <!-- Category Filter -->
            <div class="relative">
              <select 
                id="category-filter" 
                class="appearance-none bg-white border border-gray-300 rounded-lg px-4 py-2 pr-8 text-sm font-medium text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="">All Categories</option>
                <option value="music" {category === 'music' ? 'selected' : ''}>Music & Concerts</option>
                <option value="arts" {category === 'arts' ? 'selected' : ''}>Arts & Culture</option>
                <option value="community" {category === 'community' ? 'selected' : ''}>Community Events</option>
                <option value="business" {category === 'business' ? 'selected' : ''}>Business & Networking</option>
                <option value="food" {category === 'food' ? 'selected' : ''}>Food & Wine</option>
                <option value="sports" {category === 'sports' ? 'selected' : ''}>Sports & Recreation</option>
              </select>
              <div class="absolute inset-y-0 right-0 flex items-center px-2 pointer-events-none">
                <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                </svg>
              </div>
            </div>

            <!-- Date Range Filter -->
            <div class="relative">
              <select 
                id="date-filter" 
                class="appearance-none bg-white border border-gray-300 rounded-lg px-4 py-2 pr-8 text-sm font-medium text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="">All Dates</option>
                <option value="today">Today</option>
                <option value="tomorrow">Tomorrow</option>
                <option value="this-week">This Week</option>
                <option value="this-weekend">This Weekend</option>
                <option value="next-week">Next Week</option>
                <option value="this-month">This Month</option>
                <option value="next-month">Next Month</option>
              </select>
              <div class="absolute inset-y-0 right-0 flex items-center px-2 pointer-events-none">
                <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                </svg>
              </div>
            </div>

            <!-- Featured Toggle -->
            <label class="flex items-center space-x-2 cursor-pointer">
              <input 
                type="checkbox" 
                id="featured-filter" 
                class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                {featured ? 'checked' : ''}
              />
              <span class="text-sm font-medium text-gray-700">Featured Only</span>
            </label>

            <!-- Clear Filters -->
            <button 
              id="clear-filters" 
              class="text-sm font-medium text-gray-500 hover:text-gray-700 transition-colors"
            >
              Clear All
            </button>
          </div>
        </div>
      </div>
    </section>

    <!-- Main Content -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- Loading State -->
      <div id="loading-state" class="text-center py-16">
        <div class="inline-flex items-center space-x-2">
          <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
          <span class="text-lg font-medium text-gray-600">Loading events...</span>
        </div>
      </div>

      <!-- Calendar View -->
      <div id="calendar-view" class="hidden">
        <!-- Calendar Header -->
        <div class="flex items-center justify-between mb-8">
          <div class="flex items-center space-x-4">
            <button 
              id="prev-month" 
              class="p-2 rounded-lg hover:bg-gray-100 transition-colors"
            >
              <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
              </svg>
            </button>
            <h2 id="calendar-month" class="text-2xl font-bold text-gray-900"></h2>
            <button 
              id="next-month" 
              class="p-2 rounded-lg hover:bg-gray-100 transition-colors"
            >
              <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
              </svg>
            </button>
          </div>
          <button 
            id="today-btn" 
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium"
          >
            Today
          </button>
        </div>

        <!-- Calendar Grid -->
        <div class="bg-white rounded-2xl shadow-xl border border-gray-200/50 overflow-hidden">
          <!-- Day Headers -->
          <div class="grid grid-cols-7 bg-gradient-to-r from-gray-50 to-gray-100 border-b border-gray-200">
            <div class="p-4 text-center text-sm font-semibold text-gray-700">Sunday</div>
            <div class="p-4 text-center text-sm font-semibold text-gray-700">Monday</div>
            <div class="p-4 text-center text-sm font-semibold text-gray-700">Tuesday</div>
            <div class="p-4 text-center text-sm font-semibold text-gray-700">Wednesday</div>
            <div class="p-4 text-center text-sm font-semibold text-gray-700">Thursday</div>
            <div class="p-4 text-center text-sm font-semibold text-gray-700">Friday</div>
            <div class="p-4 text-center text-sm font-semibold text-gray-700">Saturday</div>
          </div>
          
          <!-- Calendar Days -->
          <div id="calendar-grid" class="grid grid-cols-7 divide-x divide-gray-200">
            <!-- Days will be populated by JavaScript -->
          </div>
        </div>
      </div>

      <!-- List View -->
      <div id="list-view" class="hidden">
        <div id="events-list" class="space-y-6">
          <!-- Events will be populated by JavaScript -->
        </div>
      </div>

      <!-- Empty State -->
      <div id="empty-state" class="hidden text-center py-16">
        <div class="max-w-md mx-auto">
          <div class="w-24 h-24 mx-auto mb-6 bg-gradient-to-br from-gray-100 to-gray-200 rounded-full flex items-center justify-center">
            <svg class="w-12 h-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" 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>
          </div>
          <h3 class="text-xl font-semibold text-gray-900 mb-2">No Events Found</h3>
          <p class="text-gray-600 mb-6">Try adjusting your filters or search terms to find events.</p>
          <button 
            id="clear-filters-empty" 
            class="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium"
          >
            Clear All Filters
          </button>
        </div>
      </div>
    </main>

    <!-- Event Detail Modal -->
    <div id="event-modal" class="fixed inset-0 z-50 hidden">
      <div class="absolute inset-0 bg-black/60 backdrop-blur-sm" id="modal-backdrop"></div>
      <div class="relative min-h-screen flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-hidden">
          <div id="modal-content" class="p-8">
            <!-- Modal content will be populated by JavaScript -->
          </div>
        </div>
      </div>
    </div>
  </div>
</Layout>

<style>
  /* Custom animations */
  @keyframes float {
    0%, 100% { transform: translateY(0px); }
    50% { transform: translateY(-10px); }
  }
  
  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(30px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  @keyframes shimmer {
    0% { background-position: -1000px 0; }
    100% { background-position: 1000px 0; }
  }
  
  .animate-float {
    animation: float 6s ease-in-out infinite;
  }
  
  .animate-fade-in-up {
    animation: fadeInUp 0.6s ease-out;
  }
  
  .shimmer {
    background: linear-gradient(
      90deg,
      transparent,
      rgba(255,255,255,0.4),
      transparent
    );
    background-size: 1000px 100%;
    animation: shimmer 2s infinite;
  }
  
  /* Custom scrollbar */
  ::-webkit-scrollbar {
    width: 8px;
  }
  
  ::-webkit-scrollbar-track {
    background: #f1f5f9;
  }
  
  ::-webkit-scrollbar-thumb {
    background: linear-gradient(45deg, #3b82f6, #8b5cf6);
    border-radius: 4px;
  }
  
  ::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(45deg, #2563eb, #7c3aed);
  }
  
  /* Calendar day hover effects */
  .calendar-day {
    transition: all 0.3s ease;
  }
  
  .calendar-day:hover {
    background: linear-gradient(135deg, #f8fafc, #e2e8f0);
    transform: scale(1.02);
  }
  
  /* Event card animations */
  .event-card {
    transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  }
  
  .event-card:hover {
    transform: translateY(-8px);
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
  }
  
  /* Glassmorphism effects */
  .glass {
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
  }
</style>

<script>
  // Calendar state
  let currentDate = new Date();
  let currentView = 'calendar';
  let events = [];
  let filteredEvents = [];
  
  // DOM elements
  const loadingState = document.getElementById('loading-state');
  const calendarView = document.getElementById('calendar-view');
  const listView = document.getElementById('list-view');
  const emptyState = document.getElementById('empty-state');
  const calendarGrid = document.getElementById('calendar-grid');
  const eventsList = document.getElementById('events-list');
  const calendarMonth = document.getElementById('calendar-month');
  const eventModal = document.getElementById('event-modal');
  const modalContent = document.getElementById('modal-content');
  const modalBackdrop = document.getElementById('modal-backdrop');
  
  // Filter elements
  const searchInput = document.getElementById('search-input');
  const searchBtn = document.getElementById('search-btn');
  const categoryFilter = document.getElementById('category-filter');
  const dateFilter = document.getElementById('date-filter');
  const featuredFilter = document.getElementById('featured-filter');
  const clearFiltersBtn = document.getElementById('clear-filters');
  const clearFiltersEmptyBtn = document.getElementById('clear-filters-empty');
  
  // View toggle elements
  const calendarViewBtn = document.getElementById('calendar-view-btn');
  const listViewBtn = document.getElementById('list-view-btn');
  
  // Calendar navigation
  const prevMonthBtn = document.getElementById('prev-month');
  const nextMonthBtn = document.getElementById('next-month');
  const todayBtn = document.getElementById('today-btn');
  
  // Utility functions
  function formatDate(date) {
    return new Intl.DateTimeFormat('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    }).format(date);
  }
  
  function formatTime(date) {
    return new Intl.DateTimeFormat('en-US', {
      hour: 'numeric',
      minute: '2-digit',
      hour12: true
    }).format(date);
  }
  
  function formatDateTime(dateString) {
    const date = new Date(dateString);
    return {
      date: formatDate(date),
      time: formatTime(date),
      dayOfWeek: date.toLocaleDateString('en-US', { weekday: 'long' })
    };
  }
  
  function getCategoryColor(category) {
    const colors = {
      music: 'from-purple-500 to-pink-500',
      arts: 'from-blue-500 to-cyan-500',
      community: 'from-green-500 to-emerald-500',
      business: 'from-gray-500 to-slate-500',
      food: 'from-orange-500 to-red-500',
      sports: 'from-indigo-500 to-purple-500',
      default: 'from-gray-400 to-gray-500'
    };
    return colors[category] || colors.default;
  }
  
  function getCategoryIcon(category) {
    const icons = {
      music: '🎵',
      arts: '🎨',
      community: '🤝',
      business: '💼',
      food: '🍷',
      sports: '⚽',
      default: '📅'
    };
    return icons[category] || icons.default;
  }
  
  // API functions
  async function fetchEvents(params = {}) {
    try {
      const url = new URL('/api/public/events', window.location.origin);
      Object.entries(params).forEach(([key, value]) => {
        if (value) url.searchParams.append(key, value);
      });
      
      const response = await fetch(url);
      if (!response.ok) throw new Error('Failed to fetch events');
      
      const data = await response.json();
      return data.events || [];
    } catch (error) {
      // Silently handle errors in production
      return [];
    }
  }
  
  // Filter functions
  function getFilterParams() {
    const params = {};
    
    if (searchInput.value.trim()) {
      params.search = searchInput.value.trim();
    }
    
    if (categoryFilter.value) {
      params.category = categoryFilter.value;
    }
    
    if (featuredFilter.checked) {
      params.featured = 'true';
    }
    
    // Handle date filter
    const dateFilterValue = dateFilter.value;
    if (dateFilterValue) {
      const now = new Date();
      let startDate, endDate;
      
      switch (dateFilterValue) {
        case 'today':
          startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
          endDate = new Date(startDate);
          endDate.setDate(endDate.getDate() + 1);
          break;
        case 'tomorrow':
          startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
          endDate = new Date(startDate);
          endDate.setDate(endDate.getDate() + 1);
          break;
        case 'this-week':
          const dayOfWeek = now.getDay();
          startDate = new Date(now);
          startDate.setDate(now.getDate() - dayOfWeek);
          endDate = new Date(startDate);
          endDate.setDate(endDate.getDate() + 7);
          break;
        case 'this-weekend':
          const daysUntilSaturday = 6 - now.getDay();
          startDate = new Date(now);
          startDate.setDate(now.getDate() + daysUntilSaturday);
          endDate = new Date(startDate);
          endDate.setDate(endDate.getDate() + 2);
          break;
        case 'next-week':
          const daysUntilNextWeek = 7 - now.getDay();
          startDate = new Date(now);
          startDate.setDate(now.getDate() + daysUntilNextWeek);
          endDate = new Date(startDate);
          endDate.setDate(endDate.getDate() + 7);
          break;
        case 'this-month':
          startDate = new Date(now.getFullYear(), now.getMonth(), 1);
          endDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);
          break;
        case 'next-month':
          startDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);
          endDate = new Date(now.getFullYear(), now.getMonth() + 2, 1);
          break;
      }
      
      if (startDate && endDate) {
        params.start_date = startDate.toISOString().split('T')[0];
        params.end_date = endDate.toISOString().split('T')[0];
      }
    }
    
    return params;
  }
  
  function clearAllFilters() {
    searchInput.value = '';
    categoryFilter.value = '';
    dateFilter.value = '';
    featuredFilter.checked = false;
    updateURL();
    loadEvents();
  }
  
  function updateURL() {
    const params = getFilterParams();
    const url = new URL(window.location);
    
    // Clear existing params
    url.search = '';
    
    // Add new params
    Object.entries(params).forEach(([key, value]) => {
      if (value) url.searchParams.set(key, value);
    });
    
    // Update URL without reloading
    window.history.replaceState({}, '', url);
  }
  
  // Event loading and filtering
  async function loadEvents() {
    showLoading();
    
    const params = getFilterParams();
    events = await fetchEvents(params);
    filteredEvents = events;
    
    hideLoading();
    renderCurrentView();
  }
  
  function showLoading() {
    loadingState.classList.remove('hidden');
    calendarView.classList.add('hidden');
    listView.classList.add('hidden');
    emptyState.classList.add('hidden');
  }
  
  function hideLoading() {
    loadingState.classList.add('hidden');
  }
  
  function showEmptyState() {
    emptyState.classList.remove('hidden');
    calendarView.classList.add('hidden');
    listView.classList.add('hidden');
  }
  
  function renderCurrentView() {
    if (filteredEvents.length === 0) {
      showEmptyState();
      return;
    }
    
    emptyState.classList.add('hidden');
    
    if (currentView === 'calendar') {
      renderCalendarView();
    } else {
      renderListView();
    }
  }
  
  // Calendar rendering
  function renderCalendarView() {
    calendarView.classList.remove('hidden');
    listView.classList.add('hidden');
    
    updateCalendarHeader();
    renderCalendarGrid();
  }
  
  function updateCalendarHeader() {
    const monthName = currentDate.toLocaleDateString('en-US', { 
      month: 'long', 
      year: 'numeric' 
    });
    calendarMonth.textContent = monthName;
  }
  
  function renderCalendarGrid() {
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();
    
    // Get first day of month and number of days
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const daysInMonth = lastDay.getDate();
    const startingDayOfWeek = firstDay.getDay();
    
    // Calculate previous month days to show
    const prevMonth = new Date(year, month - 1, 0);
    const daysInPrevMonth = prevMonth.getDate();
    
    calendarGrid.innerHTML = '';
    
    // Generate calendar days
    const totalCells = Math.ceil((daysInMonth + startingDayOfWeek) / 7) * 7;
    
    for (let i = 0; i < totalCells; i++) {
      const dayElement = createCalendarDay(i, startingDayOfWeek, daysInMonth, daysInPrevMonth, year, month);
      calendarGrid.appendChild(dayElement);
    }
  }
  
  function createCalendarDay(index, startingDayOfWeek, daysInMonth, daysInPrevMonth, year, month) {
    const dayDiv = document.createElement('div');
    dayDiv.className = 'calendar-day min-h-[120px] p-3 border-b border-gray-200 hover:bg-gradient-to-br hover:from-blue-50 hover:to-purple-50 transition-all duration-300 cursor-pointer group';
    
    let dayNumber, isCurrentMonth, currentDayDate;
    
    if (index < startingDayOfWeek) {
      // Previous month days
      dayNumber = daysInPrevMonth - (startingDayOfWeek - index - 1);
      isCurrentMonth = false;
      currentDayDate = new Date(year, month - 1, dayNumber);
    } else if (index >= startingDayOfWeek + daysInMonth) {
      // Next month days
      dayNumber = index - startingDayOfWeek - daysInMonth + 1;
      isCurrentMonth = false;
      currentDayDate = new Date(year, month + 1, dayNumber);
    } else {
      // Current month days
      dayNumber = index - startingDayOfWeek + 1;
      isCurrentMonth = true;
      currentDayDate = new Date(year, month, dayNumber);
    }
    
    // Check if it's today
    const today = new Date();
    const isToday = currentDayDate.toDateString() === today.toDateString();
    
    // Get events for this day
    const dayEvents = filteredEvents.filter(event => {
      const eventDate = new Date(event.start_time);
      return eventDate.toDateString() === currentDayDate.toDateString();
    });
    
    // Create day number
    const dayNumberSpan = document.createElement('span');
    dayNumberSpan.className = `text-sm font-medium ${
      isCurrentMonth 
        ? isToday 
          ? 'bg-gradient-to-r from-blue-600 to-purple-600 text-white px-2 py-1 rounded-full'
          : 'text-gray-900'
        : 'text-gray-400'
    }`;
    dayNumberSpan.textContent = dayNumber;
    
    dayDiv.appendChild(dayNumberSpan);
    
    // Add events
    if (dayEvents.length > 0 && isCurrentMonth) {
      const eventsContainer = document.createElement('div');
      eventsContainer.className = 'mt-2 space-y-1';
      
      // Show up to 3 events, then a "more" indicator
      const visibleEvents = dayEvents.slice(0, 3);
      const remainingCount = dayEvents.length - visibleEvents.length;
      
      visibleEvents.forEach(event => {
        const eventDiv = document.createElement('div');
        const categoryColor = getCategoryColor(event.category);
        eventDiv.className = `text-xs px-2 py-1 rounded-md bg-gradient-to-r ${categoryColor} text-white font-medium cursor-pointer transform hover:scale-105 transition-all duration-200 shadow-sm hover:shadow-md`;
        eventDiv.textContent = event.title.length > 20 ? event.title.substring(0, 20) + '...' : event.title;
        eventDiv.addEventListener('click', (e) => {
          e.stopPropagation();
          showEventModal(event);
        });
        eventsContainer.appendChild(eventDiv);
      });
      
      if (remainingCount > 0) {
        const moreDiv = document.createElement('div');
        moreDiv.className = 'text-xs text-gray-600 font-medium px-2 py-1 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors cursor-pointer';
        moreDiv.textContent = `+${remainingCount} more`;
        moreDiv.addEventListener('click', (e) => {
          e.stopPropagation();
          // Could show a day view modal here
          showDayViewModal(currentDayDate, dayEvents);
        });
        eventsContainer.appendChild(moreDiv);
      }
      
      dayDiv.appendChild(eventsContainer);
    }
    
    return dayDiv;
  }
  
  // List view rendering
  function renderListView() {
    listView.classList.remove('hidden');
    calendarView.classList.add('hidden');
    
    eventsList.innerHTML = '';
    
    // Group events by date
    const eventsByDate = {};
    filteredEvents.forEach(event => {
      const dateKey = new Date(event.start_time).toDateString();
      if (!eventsByDate[dateKey]) {
        eventsByDate[dateKey] = [];
      }
      eventsByDate[dateKey].push(event);
    });
    
    // Sort dates
    const sortedDates = Object.keys(eventsByDate).sort((a, b) => new Date(a) - new Date(b));
    
    sortedDates.forEach(dateKey => {
      const dateGroup = createDateGroup(dateKey, eventsByDate[dateKey]);
      eventsList.appendChild(dateGroup);
    });
  }
  
  function createDateGroup(dateKey, events) {
    const groupDiv = document.createElement('div');
    groupDiv.className = 'animate-fade-in-up';
    
    // Date header
    const dateHeader = document.createElement('div');
    dateHeader.className = 'mb-4';
    
    const date = new Date(dateKey);
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    let dateText;
    if (date.toDateString() === today.toDateString()) {
      dateText = 'Today';
    } else if (date.toDateString() === tomorrow.toDateString()) {
      dateText = 'Tomorrow';
    } else {
      dateText = date.toLocaleDateString('en-US', { 
        weekday: 'long', 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric' 
      });
    }
    
    dateHeader.innerHTML = `
      <h3 class="text-lg font-semibold text-gray-900 mb-1">${dateText}</h3>
      <div class="w-16 h-1 bg-gradient-to-r from-blue-600 to-purple-600 rounded-full"></div>
    `;
    
    groupDiv.appendChild(dateHeader);
    
    // Events for this date
    const eventsContainer = document.createElement('div');
    eventsContainer.className = 'grid gap-4 sm:grid-cols-2 lg:grid-cols-3';
    
    events.forEach(event => {
      const eventCard = createEventCard(event);
      eventsContainer.appendChild(eventCard);
    });
    
    groupDiv.appendChild(eventsContainer);
    
    return groupDiv;
  }
  
  function createEventCard(event) {
    const card = document.createElement('div');
    card.className = 'event-card bg-white rounded-xl shadow-lg border border-gray-200/50 overflow-hidden hover:shadow-2xl transform hover:-translate-y-2 transition-all duration-500 cursor-pointer group';
    
    const { date, time, dayOfWeek } = formatDateTime(event.start_time);
    const categoryColor = getCategoryColor(event.category);
    const categoryIcon = getCategoryIcon(event.category);
    
    card.innerHTML = `
      <div class="relative">
        <div class="h-48 bg-gradient-to-br ${categoryColor} relative overflow-hidden">
          <div class="absolute inset-0 bg-black/20"></div>
          <div class="absolute top-4 left-4">
            <span class="text-3xl">${categoryIcon}</span>
          </div>
          <div class="absolute top-4 right-4">
            <span class="bg-white/20 backdrop-blur-sm px-2 py-1 rounded-full text-white text-xs font-medium">
              ${event.category?.charAt(0).toUpperCase() + event.category?.slice(1) || 'Event'}
            </span>
          </div>
          <div class="absolute bottom-4 left-4 right-4">
            <h3 class="text-xl font-bold text-white mb-2 line-clamp-2 group-hover:text-yellow-200 transition-colors">
              ${event.title}
            </h3>
          </div>
          <div class="absolute inset-0 bg-gradient-to-t from-black/50 via-transparent to-transparent"></div>
        </div>
        
        <div class="p-6">
          <div class="flex items-center space-x-2 text-sm text-gray-600 mb-3">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
            </svg>
            <span>${time}</span>
          </div>
          
          <div class="flex items-start space-x-2 text-sm text-gray-600 mb-4">
            <svg class="w-4 h-4 mt-0.5 flex-shrink-0" 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="line-clamp-2">${event.venue || 'Venue TBA'}</span>
          </div>
          
          ${event.description ? `
          <p class="text-gray-600 text-sm mb-4 line-clamp-3">${event.description}</p>
          ` : ''}
          
          <div class="flex items-center justify-between">
            <div class="flex items-center space-x-2">
              ${event.featured ? `
              <span class="bg-yellow-100 text-yellow-800 px-2 py-1 rounded-full text-xs font-medium">
                ⭐ Featured
              </span>
              ` : ''}
            </div>
            
            <button class="bg-gradient-to-r ${categoryColor} text-white px-4 py-2 rounded-lg font-medium text-sm hover:shadow-lg transform hover:scale-105 transition-all duration-200">
              View Details
            </button>
          </div>
        </div>
      </div>
    `;
    
    card.addEventListener('click', () => showEventModal(event));
    
    return card;
  }
  
  // Modal functions
  function showEventModal(event) {
    const { date, time, dayOfWeek } = formatDateTime(event.start_time);
    const categoryColor = getCategoryColor(event.category);
    const categoryIcon = getCategoryIcon(event.category);
    
    modalContent.innerHTML = `
      <div class="relative">
        <div class="flex items-start justify-between mb-6">
          <div class="flex items-center space-x-3">
            <span class="text-3xl">${categoryIcon}</span>
            <div>
              <h2 class="text-2xl font-bold text-gray-900 mb-1">${event.title}</h2>
              <span class="bg-gradient-to-r ${categoryColor} text-white px-3 py-1 rounded-full text-sm font-medium">
                ${event.category?.charAt(0).toUpperCase() + event.category?.slice(1) || 'Event'}
              </span>
            </div>
          </div>
          <button id="close-modal" class="text-gray-400 hover:text-gray-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 class="space-y-6">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="space-y-4">
              <div class="flex items-start space-x-3">
                <div class="flex-shrink-0">
                  <svg class="w-5 h-5 text-gray-400 mt-1" 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>
                </div>
                <div>
                  <h4 class="font-semibold text-gray-900">Date & Time</h4>
                  <p class="text-gray-600">${dayOfWeek}, ${date}</p>
                  <p class="text-gray-600">${time}</p>
                </div>
              </div>
              
              <div class="flex items-start space-x-3">
                <div class="flex-shrink-0">
                  <svg class="w-5 h-5 text-gray-400 mt-1" 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>
                </div>
                <div>
                  <h4 class="font-semibold text-gray-900">Venue</h4>
                  <p class="text-gray-600">${event.venue || 'Venue information coming soon'}</p>
                </div>
              </div>
            </div>
            
            <div class="space-y-4">
              ${event.featured ? `
              <div class="bg-gradient-to-r from-yellow-50 to-orange-50 border border-yellow-200 rounded-lg p-4">
                <div class="flex items-center space-x-2">
                  <span class="text-xl">⭐</span>
                  <span class="font-semibold text-yellow-800">Featured Event</span>
                </div>
                <p class="text-yellow-700 text-sm mt-1">This is a specially curated featured event.</p>
              </div>
              ` : ''}
              
              <div class="bg-gradient-to-r from-blue-50 to-purple-50 border border-blue-200 rounded-lg p-4">
                <h4 class="font-semibold text-gray-900 mb-2">Event Details</h4>
                <p class="text-gray-600 text-sm">Click the button below to view full event details and purchase tickets.</p>
              </div>
            </div>
          </div>
          
          ${event.description ? `
          <div>
            <h4 class="font-semibold text-gray-900 mb-2">Description</h4>
            <p class="text-gray-600 leading-relaxed">${event.description}</p>
          </div>
          ` : ''}
          
          <div class="flex space-x-4 pt-6 border-t border-gray-200">
            <a 
              href="/e/${event.slug || event.id}" 
              class="flex-1 bg-gradient-to-r ${categoryColor} text-white py-3 px-6 rounded-lg font-semibold text-center hover:shadow-lg transform hover:scale-105 transition-all duration-200"
            >
              View Event & Get Tickets
            </a>
            <button 
              id="share-event" 
              class="px-6 py-3 border border-gray-300 rounded-lg font-semibold text-gray-700 hover:bg-gray-50 transition-colors 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.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.367 2.684 3 3 0 00-5.367-2.684z"></path>
              </svg>
              <span>Share</span>
            </button>
          </div>
        </div>
      </div>
    `;
    
    eventModal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
    
    // Add event listeners for modal
    document.getElementById('close-modal').addEventListener('click', hideEventModal);
    document.getElementById('share-event').addEventListener('click', () => shareEvent(event));
  }
  
  function hideEventModal() {
    eventModal.classList.add('hidden');
    document.body.style.overflow = 'auto';
  }
  
  function shareEvent(event) {
    const eventUrl = `${window.location.origin}/e/${event.slug || event.id}`;
    
    if (navigator.share) {
      navigator.share({
        title: event.title,
        text: event.description || `Check out this event: ${event.title}`,
        url: eventUrl
      });
    } else {
      // Fallback: copy to clipboard
      navigator.clipboard.writeText(eventUrl).then(() => {
        // Show success feedback
        showToast('Event link copied to clipboard!');
      }).catch(() => {
        // Fallback for older browsers
        showToast('Please copy the link manually');
      });
    }
  }
  
  function showDayViewModal(date, events) {
    // Simple implementation - could be enhanced
    const eventTitles = events.map(e => e.title).join('\n• ');
    const dateStr = date.toLocaleDateString('en-US', { 
      weekday: 'long', 
      year: 'numeric', 
      month: 'long', 
      day: 'numeric' 
    });
    showToast(`Events on ${dateStr}:\n• ${eventTitles}`);
  }
  
  function showToast(message) {
    // Simple toast notification
    const toast = document.createElement('div');
    toast.className = 'fixed top-4 right-4 bg-gray-900 text-white px-6 py-3 rounded-lg shadow-lg z-50 transform translate-x-full transition-transform duration-300';
    toast.textContent = message;
    document.body.appendChild(toast);
    
    // Animate in
    setTimeout(() => {
      toast.classList.remove('translate-x-full');
    }, 100);
    
    // Animate out and remove
    setTimeout(() => {
      toast.classList.add('translate-x-full');
      setTimeout(() => {
        document.body.removeChild(toast);
      }, 300);
    }, 3000);
  }
  
  // View toggle functions
  function switchToCalendarView() {
    currentView = 'calendar';
    calendarViewBtn.className = 'px-4 py-2 rounded-md text-sm font-medium transition-all duration-200 bg-white shadow-sm text-gray-900';
    listViewBtn.className = 'px-4 py-2 rounded-md text-sm font-medium transition-all duration-200 text-gray-600 hover:text-gray-900 hover:bg-gray-50';
    renderCurrentView();
  }
  
  function switchToListView() {
    currentView = 'list';
    listViewBtn.className = 'px-4 py-2 rounded-md text-sm font-medium transition-all duration-200 bg-white shadow-sm text-gray-900';
    calendarViewBtn.className = 'px-4 py-2 rounded-md text-sm font-medium transition-all duration-200 text-gray-600 hover:text-gray-900 hover:bg-gray-50';
    renderCurrentView();
  }
  
  // Calendar navigation functions
  function goToPreviousMonth() {
    currentDate.setMonth(currentDate.getMonth() - 1);
    renderCalendarView();
  }
  
  function goToNextMonth() {
    currentDate.setMonth(currentDate.getMonth() + 1);
    renderCalendarView();
  }
  
  function goToToday() {
    currentDate = new Date();
    renderCalendarView();
  }
  
  // Event listeners
  searchBtn.addEventListener('click', () => {
    updateURL();
    loadEvents();
  });
  
  searchInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
      updateURL();
      loadEvents();
    }
  });
  
  categoryFilter.addEventListener('change', () => {
    updateURL();
    loadEvents();
  });
  
  dateFilter.addEventListener('change', () => {
    updateURL();
    loadEvents();
  });
  
  featuredFilter.addEventListener('change', () => {
    updateURL();
    loadEvents();
  });
  
  clearFiltersBtn.addEventListener('click', clearAllFilters);
  clearFiltersEmptyBtn.addEventListener('click', clearAllFilters);
  
  calendarViewBtn.addEventListener('click', switchToCalendarView);
  listViewBtn.addEventListener('click', switchToListView);
  
  prevMonthBtn.addEventListener('click', goToPreviousMonth);
  nextMonthBtn.addEventListener('click', goToNextMonth);
  todayBtn.addEventListener('click', goToToday);
  
  modalBackdrop.addEventListener('click', hideEventModal);
  
  // Keyboard shortcuts
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && !eventModal.classList.contains('hidden')) {
      hideEventModal();
    }
  });
  
  // Initialize
  loadEvents();
</script>