{% load static %}

<!-- Advanced Ride Filters Sidebar -->
<div class="filter-sidebar bg-white dark:bg-gray-900 border-r border-gray-200 dark:border-gray-700 h-full overflow-y-auto">
  <!-- Filter Header -->
  <div class="sticky top-0 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 p-4 z-10">
    <div class="flex items-center justify-between">
      <h2 class="text-lg font-semibold text-gray-900 dark:text-white">
        <i class="fas fa-filter mr-2 text-blue-600 dark:text-blue-400"></i>
        Filters
      </h2>
      <div class="flex items-center space-x-2">
        <!-- Filter Count Badge -->
        {% if has_filters %}
        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
          {{ active_filters|length }} active
        </span>
        {% endif %}
        
        <!-- Clear All Filters -->
        {% if has_filters %}
        <button type="button" 
                hx-get="{% url 'rides:global_ride_list' %}"
                hx-target="#filter-results"
                hx-swap="outerHTML"
                hx-push-url="true"
                class="text-sm text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 font-medium">
          Clear All
        </button>
        {% endif %}
      </div>
    </div>
    
    <!-- Active Filters Summary -->
    {% if has_filters %}
    <div class="mt-3 space-y-1">
      {% for category, filters in active_filters.items %}
        {% if filters %}
        <div class="flex flex-wrap gap-1">
          {% for filter_name, filter_value in filters.items %}
          <span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200">
            {{ filter_name }}: {{ filter_value }}
            <button type="button" 
                    class="ml-1 h-3 w-3 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    onclick="removeFilter('{{ category }}', '{{ filter_name }}')">
              <i class="fas fa-times text-xs"></i>
            </button>
          </span>
          {% endfor %}
        </div>
        {% endif %}
      {% endfor %}
    </div>
    {% endif %}
  </div>

  <!-- Filter Form -->
  <form id="filter-form" 
        hx-get="{% url 'rides:global_ride_list' %}"
        hx-target="#filter-results"
        hx-swap="outerHTML"
        hx-trigger="change, input delay:500ms"
        hx-push-url="true"
        class="space-y-1">
    
    <!-- Search Text Filter -->
    <div class="filter-section border-b border-gray-200 dark:border-gray-700">
      <button type="button" 
              class="filter-toggle w-full px-4 py-3 text-left font-medium text-gray-900 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none"
              data-target="search-section">
        <div class="flex items-center justify-between">
          <span class="flex items-center">
            <i class="fas fa-search mr-2 text-gray-500"></i>
            Search
          </span>
          <i class="fas fa-chevron-down transform transition-transform duration-200"></i>
        </div>
      </button>
      <div id="search-section" class="filter-content p-4 space-y-3">
        {{ filter_form.search_text.label_tag }}
        {{ filter_form.search_text }}
        
        <div class="mt-2">
          <label class="flex items-center text-sm">
            {{ filter_form.search_exact }}
            <span class="ml-2 text-gray-600 dark:text-gray-400">Exact match</span>
          </label>
        </div>
      </div>
    </div>

    <!-- Basic Info Filter -->
    <div class="filter-section border-b border-gray-200 dark:border-gray-700">
      <button type="button" 
              class="filter-toggle w-full px-4 py-3 text-left font-medium text-gray-900 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none"
              data-target="basic-section">
        <div class="flex items-center justify-between">
          <span class="flex items-center">
            <i class="fas fa-info-circle mr-2 text-gray-500"></i>
            Basic Info
          </span>
          <i class="fas fa-chevron-down transform transition-transform duration-200"></i>
        </div>
      </button>
      <div id="basic-section" class="filter-content p-4 space-y-4">
        <!-- Categories -->
        <div>
          {{ filter_form.categories.label_tag }}
          {{ filter_form.categories }}
        </div>
        
        <!-- Status -->
        <div>
          {{ filter_form.status.label_tag }}
          {{ filter_form.status }}
        </div>
        
        <!-- Parks -->
        <div>
          {{ filter_form.parks.label_tag }}
          {{ filter_form.parks }}
        </div>
      </div>
    </div>

    <!-- Date Filters -->
    <div class="filter-section border-b border-gray-200 dark:border-gray-700">
      <button type="button" 
              class="filter-toggle w-full px-4 py-3 text-left font-medium text-gray-900 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none"
              data-target="date-section">
        <div class="flex items-center justify-between">
          <span class="flex items-center">
            <i class="fas fa-calendar mr-2 text-gray-500"></i>
            Date Ranges
          </span>
          <i class="fas fa-chevron-down transform transition-transform duration-200"></i>
        </div>
      </button>
      <div id="date-section" class="filter-content p-4 space-y-4">
        <!-- Opening Date Range -->
        <div>
          {{ filter_form.opening_date_range.label_tag }}
          {{ filter_form.opening_date_range }}
        </div>
        
        <!-- Closing Date Range -->
        <div>
          {{ filter_form.closing_date_range.label_tag }}
          {{ filter_form.closing_date_range }}
        </div>
      </div>
    </div>

    <!-- Height & Safety -->
    <div class="filter-section border-b border-gray-200 dark:border-gray-700">
      <button type="button" 
              class="filter-toggle w-full px-4 py-3 text-left font-medium text-gray-900 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none"
              data-target="height-section">
        <div class="flex items-center justify-between">
          <span class="flex items-center">
            <i class="fas fa-ruler-vertical mr-2 text-gray-500"></i>
            Height & Safety
          </span>
          <i class="fas fa-chevron-down transform transition-transform duration-200"></i>
        </div>
      </button>
      <div id="height-section" class="filter-content p-4 space-y-4">
        <!-- Height Requirements -->
        <div>
          {{ filter_form.height_requirements.label_tag }}
          {{ filter_form.height_requirements }}
        </div>
        
        <!-- Height Range -->
        <div>
          {{ filter_form.height_range.label_tag }}
          {{ filter_form.height_range }}
        </div>
        
        <!-- Accessibility -->
        <div>
          {{ filter_form.accessibility_features.label_tag }}
          {{ filter_form.accessibility_features }}
        </div>
      </div>
    </div>

    <!-- Performance -->
    <div class="filter-section border-b border-gray-200 dark:border-gray-700">
      <button type="button" 
              class="filter-toggle w-full px-4 py-3 text-left font-medium text-gray-900 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none"
              data-target="performance-section">
        <div class="flex items-center justify-between">
          <span class="flex items-center">
            <i class="fas fa-tachometer-alt mr-2 text-gray-500"></i>
            Performance
          </span>
          <i class="fas fa-chevron-down transform transition-transform duration-200"></i>
        </div>
      </button>
      <div id="performance-section" class="filter-content p-4 space-y-4">
        <!-- Speed Range -->
        <div>
          {{ filter_form.speed_range.label_tag }}
          {{ filter_form.speed_range }}
        </div>
        
        <!-- Duration Range -->
        <div>
          {{ filter_form.duration_range.label_tag }}
          {{ filter_form.duration_range }}
        </div>
        
        <!-- Capacity Range -->
        <div>
          {{ filter_form.capacity_range.label_tag }}
          {{ filter_form.capacity_range }}
        </div>
        
        <!-- Intensity -->
        <div>
          {{ filter_form.intensity_levels.label_tag }}
          {{ filter_form.intensity_levels }}
        </div>
      </div>
    </div>

    <!-- Relationships -->
    <div class="filter-section border-b border-gray-200 dark:border-gray-700">
      <button type="button" 
              class="filter-toggle w-full px-4 py-3 text-left font-medium text-gray-900 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none"
              data-target="relationships-section">
        <div class="flex items-center justify-between">
          <span class="flex items-center">
            <i class="fas fa-sitemap mr-2 text-gray-500"></i>
            Companies & Models
          </span>
          <i class="fas fa-chevron-down transform transition-transform duration-200"></i>
        </div>
      </button>
      <div id="relationships-section" class="filter-content p-4 space-y-4">
        <!-- Manufacturers -->
        <div>
          {{ filter_form.manufacturers.label_tag }}
          {{ filter_form.manufacturers }}
        </div>
        
        <!-- Designers -->
        <div>
          {{ filter_form.designers.label_tag }}
          {{ filter_form.designers }}
        </div>
        
        <!-- Ride Models -->
        <div>
          {{ filter_form.ride_models.label_tag }}
          {{ filter_form.ride_models }}
        </div>
      </div>
    </div>

    <!-- Roller Coaster Specific -->
    <div class="filter-section border-b border-gray-200 dark:border-gray-700">
      <button type="button" 
              class="filter-toggle w-full px-4 py-3 text-left font-medium text-gray-900 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none"
              data-target="coaster-section">
        <div class="flex items-center justify-between">
          <span class="flex items-center">
            <i class="fas fa-mountain mr-2 text-gray-500"></i>
            Roller Coaster Details
          </span>
          <i class="fas fa-chevron-down transform transition-transform duration-200"></i>
        </div>
      </button>
      <div id="coaster-section" class="filter-content p-4 space-y-4">
        <!-- Track Type -->
        <div>
          {{ filter_form.track_types.label_tag }}
          {{ filter_form.track_types }}
        </div>
        
        <!-- Launch Types -->
        <div>
          {{ filter_form.launch_types.label_tag }}
          {{ filter_form.launch_types }}
        </div>
        
        <!-- Inversions Range -->
        <div>
          {{ filter_form.inversions_range.label_tag }}
          {{ filter_form.inversions_range }}
        </div>
        
        <!-- Drop Range -->
        <div>
          {{ filter_form.drop_range.label_tag }}
          {{ filter_form.drop_range }}
        </div>
        
        <!-- Length Range -->
        <div>
          {{ filter_form.length_range.label_tag }}
          {{ filter_form.length_range }}
        </div>
        
        <!-- Has Features -->
        <div class="space-y-2">
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Features</label>
          <div class="space-y-1">
            <label class="flex items-center text-sm">
              {{ filter_form.has_inversions }}
              <span class="ml-2 text-gray-600 dark:text-gray-400">Has Inversions</span>
            </label>
            <label class="flex items-center text-sm">
              {{ filter_form.has_launch }}
              <span class="ml-2 text-gray-600 dark:text-gray-400">Has Launch System</span>
            </label>
          </div>
        </div>
      </div>
    </div>

    <!-- Sorting -->
    <div class="filter-section">
      <button type="button" 
              class="filter-toggle w-full px-4 py-3 text-left font-medium text-gray-900 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none"
              data-target="sorting-section">
        <div class="flex items-center justify-between">
          <span class="flex items-center">
            <i class="fas fa-sort mr-2 text-gray-500"></i>
            Sorting
          </span>
          <i class="fas fa-chevron-down transform transition-transform duration-200"></i>
        </div>
      </button>
      <div id="sorting-section" class="filter-content p-4 space-y-4">
        <!-- Sort By -->
        <div>
          {{ filter_form.sort_by.label_tag }}
          {{ filter_form.sort_by }}
        </div>
        
        <!-- Sort Order -->
        <div>
          {{ filter_form.sort_order.label_tag }}
          {{ filter_form.sort_order }}
        </div>
      </div>
    </div>
  </form>
</div>

<!-- Filter JavaScript -->
<script>
document.addEventListener('DOMContentLoaded', function() {
  // Initialize collapsible sections
  initializeFilterSections();
  
  // Initialize filter form handlers
  initializeFilterForm();
});

function initializeFilterSections() {
  const toggles = document.querySelectorAll('.filter-toggle');
  
  toggles.forEach(toggle => {
    toggle.addEventListener('click', function() {
      const targetId = this.getAttribute('data-target');
      const content = document.getElementById(targetId);
      const chevron = this.querySelector('.fa-chevron-down');
      
      if (content.style.display === 'none' || content.style.display === '') {
        content.style.display = 'block';
        chevron.style.transform = 'rotate(180deg)';
        localStorage.setItem(`filter-${targetId}`, 'open');
      } else {
        content.style.display = 'none';
        chevron.style.transform = 'rotate(0deg)';
        localStorage.setItem(`filter-${targetId}`, 'closed');
      }
    });
    
    // Restore section state from localStorage
    const targetId = toggle.getAttribute('data-target');
    const content = document.getElementById(targetId);
    const chevron = toggle.querySelector('.fa-chevron-down');
    const state = localStorage.getItem(`filter-${targetId}`);
    
    if (state === 'closed') {
      content.style.display = 'none';
      chevron.style.transform = 'rotate(0deg)';
    } else {
      content.style.display = 'block';
      chevron.style.transform = 'rotate(180deg)';
    }
  });
}

function initializeFilterForm() {
  const form = document.getElementById('filter-form');
  if (!form) return;
  
  // Handle multi-select changes
  const selects = form.querySelectorAll('select[multiple]');
  selects.forEach(select => {
    select.addEventListener('change', function() {
      // Trigger HTMX update
      htmx.trigger(form, 'change');
    });
  });
  
  // Handle range inputs
  const rangeInputs = form.querySelectorAll('input[type="range"], input[type="number"]');
  rangeInputs.forEach(input => {
    input.addEventListener('input', function() {
      // Debounced update
      clearTimeout(this.updateTimeout);
      this.updateTimeout = setTimeout(() => {
        htmx.trigger(form, 'input');
      }, 500);
    });
  });
}

function removeFilter(category, filterName) {
  const form = document.getElementById('filter-form');
  const input = form.querySelector(`[name*="${filterName}"]`);
  
  if (input) {
    if (input.type === 'checkbox') {
      input.checked = false;
    } else if (input.tagName === 'SELECT') {
      if (input.multiple) {
        Array.from(input.options).forEach(option => option.selected = false);
      } else {
        input.value = '';
      }
    } else {
      input.value = '';
    }
    
    // Trigger form update
    htmx.trigger(form, 'change');
  }
}

// Update filter counts
function updateFilterCounts() {
  const form = document.getElementById('filter-form');
  const formData = new FormData(form);
  let activeCount = 0;
  
  for (let [key, value] of formData.entries()) {
    if (value && value.trim() !== '') {
      activeCount++;
    }
  }
  
  const badge = document.querySelector('.filter-count-badge');
  if (badge) {
    badge.textContent = activeCount;
    badge.style.display = activeCount > 0 ? 'inline-flex' : 'none';
  }
}
</script>
