{#
  Filter Sidebar Components
  =========================
  Product filtering panel for category and search pages.

  Usage:
    {% from 'shared/macros/storefront/filter-sidebar.html' import filter_sidebar, filter_group, price_filter, rating_filter %}
#}


{#
  Filter Sidebar
  ==============
  Complete filter sidebar with multiple filter types.

  Parameters:
    - filters_var: Alpine.js expression for filter configuration (default: 'filters')
    - active_filters_var: Alpine.js expression for active filters (default: 'activeFilters')
    - on_change: JavaScript callback when filters change (default: 'filterProducts()')
    - show_clear: Show clear all button (default: true)
    - collapsible: Make filter groups collapsible (default: true)

  Expected filters structure:
    {
      categories: [{ id, name, count }],
      brands: [{ id, name, count }],
      priceRange: { min: 0, max: 1000 },
      attributes: {
        color: [{ value, label, count, hex }],
        size: [{ value, label, count }]
      },
      ratings: [{ value: 5, count: 10 }, ...]
    }

  Usage:
    {{ filter_sidebar(filters_var='filters', on_change='applyFilters()') }}
#}
{% macro filter_sidebar(
    filters_var='filters',
    active_filters_var='activeFilters',
    on_change='filterProducts()',
    show_clear=true,
    collapsible=true
) %}
<aside
    x-data="{
        expandedGroups: new Set(['categories', 'price', 'brands']),
        toggleGroup(name) {
            if (this.expandedGroups.has(name)) {
                this.expandedGroups.delete(name);
            } else {
                this.expandedGroups.add(name);
            }
        },
        isExpanded(name) {
            return this.expandedGroups.has(name);
        },
        hasActiveFilters() {
            const af = {{ active_filters_var }};
            return af.categories?.length > 0 ||
                   af.brands?.length > 0 ||
                   af.priceMin !== undefined ||
                   af.priceMax !== undefined ||
                   af.rating !== undefined ||
                   Object.keys(af.attributes || {}).some(k => af.attributes[k]?.length > 0);
        },
        clearAll() {
            {{ active_filters_var }} = {
                categories: [],
                brands: [],
                priceMin: undefined,
                priceMax: undefined,
                rating: undefined,
                attributes: {},
                inStock: false
            };
            {{ on_change }};
        }
    }"
    class="space-y-6"
>
    {# Header with Clear All #}
    {% if show_clear %}
    <div class="flex items-center justify-between">
        <h2 class="text-lg font-semibold text-gray-900 dark:text-white">Filters</h2>
        <button
            type="button"
            x-show="hasActiveFilters()"
            @click="clearAll()"
            class="text-sm text-purple-600 dark:text-purple-400 hover:underline"
        >
            Clear all
        </button>
    </div>
    {% endif %}

    {# Active Filters Tags #}
    <div x-show="hasActiveFilters()" class="flex flex-wrap gap-2">
        <template x-for="(cat, index) in {{ active_filters_var }}.categories || []" :key="'cat-' + cat">
            <span class="inline-flex items-center gap-1 px-2 py-1 bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 text-xs rounded-full">
                <span x-text="{{ filters_var }}.categories?.find(c => c.id === cat)?.name || cat"></span>
                <button type="button" @click="{{ active_filters_var }}.categories = {{ active_filters_var }}.categories.filter(c => c !== cat); {{ on_change }}" class="hover:text-purple-900 dark:hover:text-purple-100">
                    <span x-html="$icon('x', 'w-3 h-3')"></span>
                </button>
            </span>
        </template>
        <template x-for="(brand, index) in {{ active_filters_var }}.brands || []" :key="'brand-' + brand">
            <span class="inline-flex items-center gap-1 px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 text-xs rounded-full">
                <span x-text="{{ filters_var }}.brands?.find(b => b.id === brand)?.name || brand"></span>
                <button type="button" @click="{{ active_filters_var }}.brands = {{ active_filters_var }}.brands.filter(b => b !== brand); {{ on_change }}" class="hover:text-blue-900 dark:hover:text-blue-100">
                    <span x-html="$icon('x', 'w-3 h-3')"></span>
                </button>
            </span>
        </template>
        <template x-if="{{ active_filters_var }}.priceMin !== undefined || {{ active_filters_var }}.priceMax !== undefined">
            <span class="inline-flex items-center gap-1 px-2 py-1 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 text-xs rounded-full">
                <span x-text="'$' + ({{ active_filters_var }}.priceMin || 0) + ' - $' + ({{ active_filters_var }}.priceMax || {{ filters_var }}.priceRange?.max || 1000)"></span>
                <button type="button" @click="{{ active_filters_var }}.priceMin = undefined; {{ active_filters_var }}.priceMax = undefined; {{ on_change }}" class="hover:text-green-900 dark:hover:text-green-100">
                    <span x-html="$icon('x', 'w-3 h-3')"></span>
                </button>
            </span>
        </template>
    </div>

    {# Categories Filter #}
    <template x-if="{{ filters_var }}.categories?.length > 0">
        {{ _filter_group('Categories', 'categories', collapsible) }}
    </template>

    {# Price Range Filter #}
    <template x-if="{{ filters_var }}.priceRange">
        {{ _price_range_group(filters_var, active_filters_var, on_change, collapsible) }}
    </template>

    {# Brands Filter #}
    <template x-if="{{ filters_var }}.brands?.length > 0">
        {{ _filter_group('Brands', 'brands', collapsible) }}
    </template>

    {# Rating Filter #}
    <template x-if="{{ filters_var }}.ratings?.length > 0">
        {{ _rating_group(filters_var, active_filters_var, on_change, collapsible) }}
    </template>

    {# Dynamic Attribute Filters #}
    <template x-for="(options, attrName) in {{ filters_var }}.attributes || {}" :key="attrName">
        {{ _attribute_group(filters_var, active_filters_var, on_change, collapsible) }}
    </template>

    {# Availability Filter #}
    <div class="pt-4 border-t border-gray-200 dark:border-gray-700">
        <label class="flex items-center gap-3 cursor-pointer">
            <input
                type="checkbox"
                x-model="{{ active_filters_var }}.inStock"
                @change="{{ on_change }}"
                class="w-4 h-4 rounded border-gray-300 dark:border-gray-600 text-purple-600 focus:ring-purple-500"
            >
            <span class="text-sm text-gray-700 dark:text-gray-300">In Stock Only</span>
        </label>
    </div>
</aside>
{% endmacro %}


{#
  Internal: Filter Group for Categories/Brands
#}
{% macro _filter_group(title, type, collapsible) %}
<div class="border-t border-gray-200 dark:border-gray-700 pt-4">
    {% if collapsible %}
    <button
        type="button"
        @click="toggleGroup('{{ type }}')"
        class="flex items-center justify-between w-full text-left"
    >
        <h3 class="text-sm font-medium text-gray-900 dark:text-white">{{ title }}</h3>
        <span x-html="$icon('chevron-down', 'w-4 h-4 text-gray-400 transition-transform')" :class="isExpanded('{{ type }}') && 'rotate-180'"></span>
    </button>
    {% else %}
    <h3 class="text-sm font-medium text-gray-900 dark:text-white mb-3">{{ title }}</h3>
    {% endif %}

    <div
        {% if collapsible %}
        x-show="isExpanded('{{ type }}')"
        x-transition
        {% endif %}
        class="mt-3 space-y-2"
    >
        <template x-for="item in filters.{{ type }}" :key="item.id">
            <label class="flex items-center gap-3 cursor-pointer group">
                <input
                    type="checkbox"
                    :value="item.id"
                    :checked="activeFilters.{{ type }}?.includes(item.id)"
                    @change="
                        if ($event.target.checked) {
                            activeFilters.{{ type }} = [...(activeFilters.{{ type }} || []), item.id];
                        } else {
                            activeFilters.{{ type }} = activeFilters.{{ type }}.filter(i => i !== item.id);
                        }
                        filterProducts();
                    "
                    class="w-4 h-4 rounded border-gray-300 dark:border-gray-600 text-purple-600 focus:ring-purple-500"
                >
                <span class="flex-1 text-sm text-gray-700 dark:text-gray-300 group-hover:text-gray-900 dark:group-hover:text-white" x-text="item.name"></span>
                <span x-show="item.count !== undefined" class="text-xs text-gray-400" x-text="'(' + item.count + ')'"></span>
            </label>
        </template>
    </div>
</div>
{% endmacro %}


{#
  Internal: Price Range Group
#}
{% macro _price_range_group(filters_var, active_filters_var, on_change, collapsible) %}
<div class="border-t border-gray-200 dark:border-gray-700 pt-4">
    {% if collapsible %}
    <button
        type="button"
        @click="toggleGroup('price')"
        class="flex items-center justify-between w-full text-left"
    >
        <h3 class="text-sm font-medium text-gray-900 dark:text-white">Price Range</h3>
        <span x-html="$icon('chevron-down', 'w-4 h-4 text-gray-400 transition-transform')" :class="isExpanded('price') && 'rotate-180'"></span>
    </button>
    {% else %}
    <h3 class="text-sm font-medium text-gray-900 dark:text-white mb-3">Price Range</h3>
    {% endif %}

    <div
        {% if collapsible %}
        x-show="isExpanded('price')"
        x-transition
        {% endif %}
        class="mt-3 space-y-4"
        x-data="{
            minPrice: {{ active_filters_var }}.priceMin ?? {{ filters_var }}.priceRange?.min ?? 0,
            maxPrice: {{ active_filters_var }}.priceMax ?? {{ filters_var }}.priceRange?.max ?? 1000,
            updatePrice() {
                {{ active_filters_var }}.priceMin = this.minPrice;
                {{ active_filters_var }}.priceMax = this.maxPrice;
                {{ on_change }};
            }
        }"
    >
        {# Dual Range Slider #}
        <div class="relative pt-1">
            <div class="h-2 bg-gray-200 dark:bg-gray-700 rounded-full">
                <div
                    class="absolute h-2 bg-purple-500 rounded-full"
                    :style="'left: ' + ((minPrice - ({{ filters_var }}.priceRange?.min || 0)) / (({{ filters_var }}.priceRange?.max || 1000) - ({{ filters_var }}.priceRange?.min || 0)) * 100) + '%; right: ' + (100 - (maxPrice - ({{ filters_var }}.priceRange?.min || 0)) / (({{ filters_var }}.priceRange?.max || 1000) - ({{ filters_var }}.priceRange?.min || 0)) * 100) + '%'"
                ></div>
            </div>
            <input
                type="range"
                :min="{{ filters_var }}.priceRange?.min || 0"
                :max="{{ filters_var }}.priceRange?.max || 1000"
                x-model.number="minPrice"
                @change="if (minPrice > maxPrice) minPrice = maxPrice; updatePrice()"
                class="absolute w-full h-2 opacity-0 cursor-pointer -top-1"
            >
            <input
                type="range"
                :min="{{ filters_var }}.priceRange?.min || 0"
                :max="{{ filters_var }}.priceRange?.max || 1000"
                x-model.number="maxPrice"
                @change="if (maxPrice < minPrice) maxPrice = minPrice; updatePrice()"
                class="absolute w-full h-2 opacity-0 cursor-pointer -top-1"
            >
        </div>

        {# Price Inputs #}
        <div class="flex items-center gap-3">
            <div class="flex-1">
                <label class="sr-only">Min price</label>
                <div class="relative">
                    <span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm">$</span>
                    <input
                        type="number"
                        x-model.number="minPrice"
                        :min="{{ filters_var }}.priceRange?.min || 0"
                        :max="maxPrice"
                        @change="updatePrice()"
                        class="w-full pl-7 pr-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                        placeholder="Min"
                    >
                </div>
            </div>
            <span class="text-gray-400">-</span>
            <div class="flex-1">
                <label class="sr-only">Max price</label>
                <div class="relative">
                    <span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm">$</span>
                    <input
                        type="number"
                        x-model.number="maxPrice"
                        :min="minPrice"
                        :max="{{ filters_var }}.priceRange?.max || 1000"
                        @change="updatePrice()"
                        class="w-full pl-7 pr-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                        placeholder="Max"
                    >
                </div>
            </div>
        </div>
    </div>
</div>
{% endmacro %}


{#
  Internal: Rating Group
#}
{% macro _rating_group(filters_var, active_filters_var, on_change, collapsible) %}
<div class="border-t border-gray-200 dark:border-gray-700 pt-4">
    {% if collapsible %}
    <button
        type="button"
        @click="toggleGroup('rating')"
        class="flex items-center justify-between w-full text-left"
    >
        <h3 class="text-sm font-medium text-gray-900 dark:text-white">Rating</h3>
        <span x-html="$icon('chevron-down', 'w-4 h-4 text-gray-400 transition-transform')" :class="isExpanded('rating') && 'rotate-180'"></span>
    </button>
    {% else %}
    <h3 class="text-sm font-medium text-gray-900 dark:text-white mb-3">Rating</h3>
    {% endif %}

    <div
        {% if collapsible %}
        x-show="isExpanded('rating')"
        x-transition
        {% endif %}
        class="mt-3 space-y-2"
    >
        <template x-for="rating in {{ filters_var }}.ratings" :key="rating.value">
            <label class="flex items-center gap-3 cursor-pointer group">
                <input
                    type="radio"
                    name="rating-filter"
                    :value="rating.value"
                    :checked="{{ active_filters_var }}.rating === rating.value"
                    @change="{{ active_filters_var }}.rating = rating.value; {{ on_change }}"
                    class="w-4 h-4 border-gray-300 dark:border-gray-600 text-purple-600 focus:ring-purple-500"
                >
                <span class="flex items-center gap-1">
                    <template x-for="i in 5" :key="i">
                        <span
                            x-html="$icon('star', 'w-4 h-4')"
                            :class="i <= rating.value ? 'text-yellow-400' : 'text-gray-300 dark:text-gray-600'"
                        ></span>
                    </template>
                    <span class="text-sm text-gray-500 dark:text-gray-400 ml-1">& up</span>
                </span>
                <span x-show="rating.count !== undefined" class="text-xs text-gray-400 ml-auto" x-text="'(' + rating.count + ')'"></span>
            </label>
        </template>
        <button
            type="button"
            x-show="{{ active_filters_var }}.rating !== undefined"
            @click="{{ active_filters_var }}.rating = undefined; {{ on_change }}"
            class="text-xs text-purple-600 dark:text-purple-400 hover:underline"
        >
            Clear rating filter
        </button>
    </div>
</div>
{% endmacro %}


{#
  Internal: Dynamic Attribute Group (color, size, etc.)
#}
{% macro _attribute_group(filters_var, active_filters_var, on_change, collapsible) %}
<div class="border-t border-gray-200 dark:border-gray-700 pt-4">
    {% if collapsible %}
    <button
        type="button"
        @click="toggleGroup(attrName)"
        class="flex items-center justify-between w-full text-left"
    >
        <h3 class="text-sm font-medium text-gray-900 dark:text-white capitalize" x-text="attrName"></h3>
        <span x-html="$icon('chevron-down', 'w-4 h-4 text-gray-400 transition-transform')" :class="isExpanded(attrName) && 'rotate-180'"></span>
    </button>
    {% else %}
    <h3 class="text-sm font-medium text-gray-900 dark:text-white capitalize mb-3" x-text="attrName"></h3>
    {% endif %}

    <div
        {% if collapsible %}
        x-show="isExpanded(attrName)"
        x-transition
        {% endif %}
        class="mt-3"
    >
        {# Color Swatches #}
        <template x-if="attrName === 'color'">
            <div class="flex flex-wrap gap-2">
                <template x-for="option in options" :key="option.value">
                    <button
                        type="button"
                        @click="
                            if (!{{ active_filters_var }}.attributes) {{ active_filters_var }}.attributes = {};
                            if (!{{ active_filters_var }}.attributes[attrName]) {{ active_filters_var }}.attributes[attrName] = [];
                            const idx = {{ active_filters_var }}.attributes[attrName].indexOf(option.value);
                            if (idx === -1) {
                                {{ active_filters_var }}.attributes[attrName].push(option.value);
                            } else {
                                {{ active_filters_var }}.attributes[attrName].splice(idx, 1);
                            }
                            {{ on_change }};
                        "
                        class="w-8 h-8 rounded-full border-2 transition-all"
                        :class="({{ active_filters_var }}.attributes?.[attrName]?.includes(option.value)) ? 'border-purple-500 ring-2 ring-purple-500/30' : 'border-gray-300 dark:border-gray-600 hover:border-gray-400'"
                        :style="'background-color: ' + (option.hex || option.value)"
                        :title="option.label"
                    >
                        <span class="sr-only" x-text="option.label"></span>
                        <span
                            x-show="{{ active_filters_var }}.attributes?.[attrName]?.includes(option.value)"
                            x-html="$icon('check', 'w-4 h-4 mx-auto')"
                            :class="['#FFFFFF', '#FFF', 'white', '#FFFFF0'].includes(option.hex || option.value) ? 'text-gray-800' : 'text-white'"
                        ></span>
                    </button>
                </template>
            </div>
        </template>

        {# Size/Other Buttons #}
        <template x-if="attrName === 'size'">
            <div class="flex flex-wrap gap-2">
                <template x-for="option in options" :key="option.value">
                    <button
                        type="button"
                        @click="
                            if (!{{ active_filters_var }}.attributes) {{ active_filters_var }}.attributes = {};
                            if (!{{ active_filters_var }}.attributes[attrName]) {{ active_filters_var }}.attributes[attrName] = [];
                            const idx = {{ active_filters_var }}.attributes[attrName].indexOf(option.value);
                            if (idx === -1) {
                                {{ active_filters_var }}.attributes[attrName].push(option.value);
                            } else {
                                {{ active_filters_var }}.attributes[attrName].splice(idx, 1);
                            }
                            {{ on_change }};
                        "
                        class="px-3 py-1.5 text-sm border rounded-lg transition-colors"
                        :class="({{ active_filters_var }}.attributes?.[attrName]?.includes(option.value)) ? 'bg-purple-600 text-white border-purple-600' : 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:border-purple-500'"
                        :disabled="option.count === 0"
                        :title="option.count === 0 ? 'Not available' : ''"
                    >
                        <span x-text="option.label"></span>
                    </button>
                </template>
            </div>
        </template>

        {# Checkbox List for other attributes #}
        <template x-if="attrName !== 'color' && attrName !== 'size'">
            <div class="space-y-2">
                <template x-for="option in options" :key="option.value">
                    <label class="flex items-center gap-3 cursor-pointer group">
                        <input
                            type="checkbox"
                            :checked="{{ active_filters_var }}.attributes?.[attrName]?.includes(option.value)"
                            @change="
                                if (!{{ active_filters_var }}.attributes) {{ active_filters_var }}.attributes = {};
                                if (!{{ active_filters_var }}.attributes[attrName]) {{ active_filters_var }}.attributes[attrName] = [];
                                if ($event.target.checked) {
                                    {{ active_filters_var }}.attributes[attrName].push(option.value);
                                } else {
                                    {{ active_filters_var }}.attributes[attrName] = {{ active_filters_var }}.attributes[attrName].filter(v => v !== option.value);
                                }
                                {{ on_change }};
                            "
                            class="w-4 h-4 rounded border-gray-300 dark:border-gray-600 text-purple-600 focus:ring-purple-500"
                        >
                        <span class="flex-1 text-sm text-gray-700 dark:text-gray-300" x-text="option.label"></span>
                        <span x-show="option.count !== undefined" class="text-xs text-gray-400" x-text="'(' + option.count + ')'"></span>
                    </label>
                </template>
            </div>
        </template>
    </div>
</div>
{% endmacro %}


{#
  Price Filter (Standalone)
  =========================
  Standalone price range filter component.

  Parameters:
    - min: Minimum price (default: 0)
    - max: Maximum price (default: 1000)
    - value_min_var: Alpine.js var for min value (default: 'priceMin')
    - value_max_var: Alpine.js var for max value (default: 'priceMax')
    - on_change: Callback on change (default: 'updateFilters()')
    - currency: Currency symbol (default: '$')

  Usage:
    {{ price_filter(min=0, max=500, on_change='filterByPrice()') }}
#}
{% macro price_filter(
    min=0,
    max=1000,
    value_min_var='priceMin',
    value_max_var='priceMax',
    on_change='updateFilters()',
    currency='$'
) %}
<div
    x-data="{
        minVal: {{ value_min_var }} ?? {{ min }},
        maxVal: {{ value_max_var }} ?? {{ max }},
        apply() {
            {{ value_min_var }} = this.minVal;
            {{ value_max_var }} = this.maxVal;
            {{ on_change }};
        }
    }"
    class="space-y-4"
>
    <div class="flex items-center gap-3">
        <div class="flex-1">
            <div class="relative">
                <span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm">{{ currency }}</span>
                <input
                    type="number"
                    x-model.number="minVal"
                    min="{{ min }}"
                    :max="maxVal"
                    @change="apply()"
                    class="w-full pl-7 pr-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                    placeholder="Min"
                >
            </div>
        </div>
        <span class="text-gray-400">to</span>
        <div class="flex-1">
            <div class="relative">
                <span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm">{{ currency }}</span>
                <input
                    type="number"
                    x-model.number="maxVal"
                    :min="minVal"
                    max="{{ max }}"
                    @change="apply()"
                    class="w-full pl-7 pr-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                    placeholder="Max"
                >
            </div>
        </div>
    </div>
</div>
{% endmacro %}


{#
  Rating Filter (Standalone)
  ==========================
  Standalone star rating filter.

  Parameters:
    - value_var: Alpine.js var for selected rating (default: 'minRating')
    - on_change: Callback on change (default: 'updateFilters()')
    - show_count: Show product counts (default: false)
    - counts: List of counts per rating level

  Usage:
    {{ rating_filter(value_var='minRating', on_change='filterByRating()') }}
#}
{% macro rating_filter(
    value_var='minRating',
    on_change='updateFilters()',
    show_count=false,
    counts=none
) %}
<div class="space-y-2">
    {% for i in range(5, 0, -1) %}
    <label class="flex items-center gap-3 cursor-pointer group">
        <input
            type="radio"
            name="rating"
            value="{{ i }}"
            :checked="{{ value_var }} === {{ i }}"
            @change="{{ value_var }} = {{ i }}; {{ on_change }}"
            class="w-4 h-4 border-gray-300 dark:border-gray-600 text-purple-600 focus:ring-purple-500"
        >
        <span class="flex items-center gap-0.5">
            {% for j in range(1, 6) %}
            <span x-html="$icon('star', 'w-4 h-4 {{ 'text-yellow-400' if j <= i else 'text-gray-300 dark:text-gray-600' }}')" class="{{ 'text-yellow-400' if j <= i else 'text-gray-300 dark:text-gray-600' }}"></span>
            {% endfor %}
            <span class="text-sm text-gray-500 dark:text-gray-400 ml-1">& up</span>
        </span>
        {% if show_count and counts %}
        <span class="text-xs text-gray-400 ml-auto">({{ counts[i-1] if counts|length >= i else '0' }})</span>
        {% endif %}
    </label>
    {% endfor %}
</div>
{% endmacro %}


{#
  Mobile Filter Drawer
  ====================
  Full-screen filter panel for mobile devices.

  Parameters:
    - show_var: Alpine.js variable for visibility (default: 'showFilters')
    - filters_var: Alpine.js expression for filters (default: 'filters')
    - active_filters_var: Alpine.js expression for active filters (default: 'activeFilters')
    - on_apply: Callback on apply (default: 'applyFilters()')
    - result_count_var: Alpine.js var showing result count (default: 'productCount')

  Usage:
    {{ mobile_filter_drawer(show_var='showMobileFilters') }}
#}
{% macro mobile_filter_drawer(
    show_var='showFilters',
    filters_var='filters',
    active_filters_var='activeFilters',
    on_apply='applyFilters()',
    result_count_var='productCount'
) %}
<div
    x-show="{{ show_var }}"
    x-transition:enter="transition ease-out duration-300"
    x-transition:enter-start="opacity-0"
    x-transition:enter-end="opacity-100"
    x-transition:leave="transition ease-in duration-200"
    x-transition:leave-start="opacity-100"
    x-transition:leave-end="opacity-0"
    class="fixed inset-0 z-50 lg:hidden"
    style="display: none;"
>
    {# Backdrop #}
    <div
        @click="{{ show_var }} = false"
        class="absolute inset-0 bg-black/50"
    ></div>

    {# Drawer Panel #}
    <div
        x-show="{{ show_var }}"
        x-transition:enter="transition ease-out duration-300"
        x-transition:enter-start="translate-x-full"
        x-transition:enter-end="translate-x-0"
        x-transition:leave="transition ease-in duration-200"
        x-transition:leave-start="translate-x-0"
        x-transition:leave-end="translate-x-full"
        class="absolute right-0 top-0 bottom-0 w-80 max-w-[85vw] bg-white dark:bg-gray-800 shadow-xl flex flex-col"
    >
        {# Header #}
        <div class="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700">
            <h2 class="text-lg font-semibold text-gray-900 dark:text-white">Filters</h2>
            <button
                type="button"
                @click="{{ show_var }} = false"
                class="p-2 -mr-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300"
            >
                <span x-html="$icon('x', 'w-5 h-5')"></span>
            </button>
        </div>

        {# Filter Content #}
        <div class="flex-1 overflow-y-auto px-4 py-4">
            {{ filter_sidebar(filters_var=filters_var, active_filters_var=active_filters_var, on_change=on_apply, show_clear=false, collapsible=true) }}
        </div>

        {# Footer with Apply Button #}
        <div class="px-4 py-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900">
            <button
                type="button"
                @click="{{ show_var }} = false"
                class="w-full py-3 bg-purple-600 hover:bg-purple-700 text-white font-medium rounded-lg transition-colors"
            >
                Show Results <span x-show="{{ result_count_var }}" x-text="'(' + {{ result_count_var }} + ')'"></span>
            </button>
        </div>
    </div>
</div>
{% endmacro %}


{#
  Filter Trigger Button
  ====================
  Button to open mobile filter drawer.

  Parameters:
    - show_var: Alpine.js variable to toggle (default: 'showFilters')
    - active_count_var: Alpine.js var for active filter count (default: none)

  Usage:
    {{ filter_trigger(show_var='showMobileFilters') }}
#}
{% macro filter_trigger(
    show_var='showFilters',
    active_count_var=none
) %}
<button
    type="button"
    @click="{{ show_var }} = true"
    class="flex items-center gap-2 px-4 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors lg:hidden"
>
    <span x-html="$icon('adjustments', 'w-5 h-5')"></span>
    <span>Filters</span>
    {% if active_count_var %}
    <span
        x-show="{{ active_count_var }} > 0"
        x-text="{{ active_count_var }}"
        class="w-5 h-5 flex items-center justify-center bg-purple-600 text-white text-xs rounded-full"
    ></span>
    {% endif %}
</button>
{% endmacro %}


{#
  Sort Dropdown
  =============
  Product sorting dropdown.

  Parameters:
    - value_var: Alpine.js var for sort value (default: 'sortBy')
    - options: Sort options list (default: common options)
    - on_change: Callback on change (default: 'sortProducts()')

  Usage:
    {{ sort_dropdown(value_var='currentSort') }}
#}
{% macro sort_dropdown(
    value_var='sortBy',
    options=none,
    on_change='sortProducts()'
) %}
{% set default_options = [
    {'value': 'relevance', 'label': 'Relevance'},
    {'value': 'price_asc', 'label': 'Price: Low to High'},
    {'value': 'price_desc', 'label': 'Price: High to Low'},
    {'value': 'newest', 'label': 'Newest First'},
    {'value': 'rating', 'label': 'Highest Rated'},
    {'value': 'popular', 'label': 'Most Popular'}
] %}
{% set sort_options = options if options else default_options %}
<div x-data="{ open: false }" class="relative" @click.away="open = false">
    <button
        type="button"
        @click="open = !open"
        class="flex items-center gap-2 px-4 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
    >
        <span>Sort by:</span>
        <span class="text-gray-900 dark:text-white" x-text="[{% for opt in sort_options %}{ value: '{{ opt.value }}', label: '{{ opt.label }}' }{{ ', ' if not loop.last }}{% endfor %}].find(o => o.value === {{ value_var }})?.label || 'Relevance'"></span>
        <span x-html="$icon('chevron-down', 'w-4 h-4 text-gray-400')"></span>
    </button>

    <div
        x-show="open"
        x-transition:enter="transition ease-out duration-100"
        x-transition:enter-start="opacity-0 transform -translate-y-2"
        x-transition:enter-end="opacity-100 transform translate-y-0"
        x-transition:leave="transition ease-in duration-75"
        x-transition:leave-start="opacity-100"
        x-transition:leave-end="opacity-0"
        class="absolute right-0 mt-2 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 py-1 z-50"
        style="display: none;"
    >
        {% for opt in sort_options %}
        <button
            type="button"
            @click="{{ value_var }} = '{{ opt.value }}'; {{ on_change }}; open = false"
            class="w-full px-4 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
            :class="{{ value_var }} === '{{ opt.value }}' ? 'text-purple-600 dark:text-purple-400 font-medium' : 'text-gray-700 dark:text-gray-300'"
        >
            {{ opt.label }}
        </button>
        {% endfor %}
    </div>
</div>
{% endmacro %}
