<style>
    input[type=range]::-webkit-slider-thumb {
      pointer-events: all;
      width: 24px;
      height: 24px;
      -webkit-appearance: none;
    /* @apply w-6 h-6 appearance-none pointer-events-auto; */
    }
    #filter-panel::-webkit-scrollbar {
        display: none;
    }
</style>

{% set euro = '&euro;' %}

<section id="filter-panel" class="bg-white lg:w-[280px] w-full min-h-screen h-screen overflow-y-auto p-4 pb-24 lg:pb-4 lg:p-0 select-none" x-data="filterData()">

    <div id="filters_actions" class="grid grid-cols-2 gap-2 mb-4" x-cloak x-show="activeFilters.length >= 1">
        <button class="bg-slate-100 hover:bg-slate-200 text-slate-600 lg:text-sm text-base font-medium px-4 py-2 rounded-md w-full relative" @click="resetFilters">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="size-4 absolute left-2 top-4 -my-2">
                <path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />
            </svg>
            Reset
        </button>
        <button class="bg-primary-dark hover:bg-primary text-white lg:text-sm text-base font-medium px-4 py-2 rounded-md w-full relative" @click="applyFilters">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="size-4 absolute left-2 top-2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M12 3c2.755 0 5.455.232 8.083.678.533.09.917.556.917 1.096v1.044a2.25 2.25 0 0 1-.659 1.591l-5.432 5.432a2.25 2.25 0 0 0-.659 1.591v2.927a2.25 2.25 0 0 1-1.244 2.013L9.75 21v-6.568a2.25 2.25 0 0 0-.659-1.591L3.659 7.409A2.25 2.25 0 0 1 3 5.818V4.774c0-.54.384-1.006.917-1.096A48.32 48.32 0 0 1 12 3Z" />
            </svg>
            Applica
        </button>
    </div>

    <div id="active_filters" class="flex flex-wrap gap-2">
        <template x-for="filter in activeFilters" :key="filter">
            <div class="chip bg-slate-100 border text-slate-600 px-2 py-1 rounded-full text-xs flex items-center">
                <span x-text="filter"></span>
                <button @click="removeFilter(filter)" class="ml-2 text-slate-600">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-4">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
                    </svg>                      
                </button>
            </div>
        </template>
    </div>

    {# prezzo  #}
    <div x-data="{ open: true }" class="border-b">
        <button
            x-on:click="open = ! open"
            class="text-slate-900 rounded-md py-2 lg:text-sm text-base font-medium flex items-center justify-between w-full"
            >
            Prezzo
            <div class="h-3 w-3 ml-2 fill-primary-dark block" :class="open?'rotate-180':''">
                {% include "templates/components/icons/angle-down.twig" %}
            </div>
        </button>

        <div x-show="open" x-transition class="mb-6">
            {% include "templates/components/prodotti/finder/filters/slider.twig" with { 
                id: 'price',
                min: productFilters.price.priceMin,
                max: productFilters.price.priceMax,
                unit: euro|raw,
                step: 1
            }%}
        </div>

    </div>

    {# BRAND #}
    <div x-data="{ open: false }" class="border-b">
        <button
            x-on:click="open = ! open"
            class="text-slate-900 rounded-md py-2 lg:text-sm text-base font-medium flex items-center justify-between w-full"
            >
            Brand
            <div class="h-3 w-3 ml-2 fill-primary-dark block" :class="open?'rotate-180':''">
                {% include "templates/components/icons/angle-down.twig" %}
            </div>
        </button>

        <div x-cloak x-show="open" x-transition class="mb-6">
            {% include "templates/components/prodotti/finder/filters/checkbox.twig" with { 
                id: 'brand',
                loop: productFilters.brand
            }%}
        </div>
    </div>
    

    {# os  #}
    <div x-data="{ open: false }" class="border-b">
        <button
            x-on:click="open = ! open"
            class="text-slate-900 rounded-md py-2 lg:text-sm text-base font-medium flex items-center justify-between w-full"
            >
            Sistema Operativo
            <div class="h-3 w-3 ml-2 fill-primary-dark block" :class="open?'rotate-180':''">
                {% include "templates/components/icons/angle-down.twig" %}
            </div>
        </button>

        <div x-cloak x-show="open" x-transition class="mb-6">
            {% include "templates/components/prodotti/finder/filters/checkbox.twig" with { 
                id: 'os',
                cols: 1,
                loop: productFilters.os
            }%}
        </div>
    </div>

    {# display_size  #}
    <div x-data="{ open: false }" class="border-b">
        <button
            x-on:click="open = ! open"
            class="text-slate-900 rounded-md py-2 lg:text-sm text-base font-medium flex items-center justify-between w-full"
            >
            Dimensione schermo
            <div class="h-3 w-3 ml-2 fill-primary-dark block" :class="open?'rotate-180':''">
                {% include "templates/components/icons/angle-down.twig" %}
            </div>
        </button>

        <div x-cloak x-show="open" x-transition class="mb-6">
            {% include "templates/components/prodotti/finder/filters/slider.twig" with { 
                id: 'display_size',
                min: productFilters.display_size.displaySizeMin,
                max: productFilters.display_size.displaySizeMax,
                unit: 'pollici',
                step: 0.1,
                useFloat: true
            }%}
        </div>
    </div>

    {# storage  #}
    <div x-data="{ open: false }" class="border-b">
        <button
            x-on:click="open = ! open"
            class="text-slate-900 rounded-md py-2 lg:text-sm text-base font-medium flex items-center justify-between w-full"
            >
            Storage
            <div class="h-3 w-3 ml-2 fill-primary-dark block" :class="open?'rotate-180':''">
                {% include "templates/components/icons/angle-down.twig" %}
            </div>
        </button>

        <div x-cloak x-show="open" x-transition class="mb-6">
            {% include "templates/components/prodotti/finder/filters/slider.twig" with { 
                id: 'storage',
                min: productFilters.storage.storageMin,
                max: productFilters.storage.storageMax,
                unit: 'GB',
                step: 1
            }%}
        </div>
    </div>

    {# ram  #}
    <div x-data="{ open: false }" class="border-b">
        <button
            x-on:click="open = ! open"
            class="text-slate-900 rounded-md py-2 lg:text-sm text-base font-medium flex items-center justify-between w-full"
            >
            RAM
            <div class="h-3 w-3 ml-2 fill-primary-dark block" :class="open?'rotate-180':''">
                {% include "templates/components/icons/angle-down.twig" %}
            </div>
        </button>

        <div x-cloak x-show="open" x-transition class="mb-6">
            {% include "templates/components/prodotti/finder/filters/slider.twig" with { 
                id: 'ram',
                min: productFilters.ram.ramMin,
                max: productFilters.ram.ramMax,
                unit: 'GB',
                step: 1
            }%}
        </div>
    </div>


</section>


<script>
function filterData() {
    const euro = '&euro;';
    const config = {
        filters: {
            price: {
                type: 'range',
                label: 'Prezzo',
                unit: '\u20AC',
                min: parseInt('{{productFilters.price.priceMin}}'),
                max: parseInt('{{productFilters.price.priceMax}}'),
                dataType: 'price'
            },
            ram: {
                type: 'range',
                label: 'RAM',
                unit: 'GB',
                min: parseInt('{{productFilters.ram.ramMin}}'),
                max: parseInt('{{productFilters.ram.ramMax}}'),
                dataType: 'ram'
            },
            storage: {
                type: 'range',
                label: 'Memoria',
                unit: 'GB',
                min: parseInt('{{productFilters.storage.storageMin}}'),
                max: parseInt('{{productFilters.storage.storageMax}}'),
                dataType: 'storage'
            },
            display_size: {
                type: 'range',
                label: 'Dimensione schermo',
                unit: 'pollici',
                min: parseFloat('{{productFilters.display_size.displaySizeMin}}'),
                max: parseFloat('{{productFilters.display_size.displaySizeMax}}'),
                dataType: 'display_size'
            },
            os: {
                type: 'checkbox',
                label: 'Sistema Operativo',
                dataType: 'os'
            },
            brand: {
                type: 'checkbox',
                label: 'Brand',
                dataType: 'brand'
            }
        }
    };
    
    // Leggi i filtri decodificati dal JSON
    const filtersDecoded = {{ filters_decoded|default({})|json_encode|raw }};

    return {
        activeFilters: [],
        selectedValues: {
            price: { min: config.filters.price.min, max: config.filters.price.max },
            ram: { min: config.filters.ram.min, max: config.filters.ram.max },
            storage: { min: config.filters.storage.min, max: config.filters.storage.max },
            display_size: { min: config.filters.display_size.min, max: config.filters.display_size.max },
            os: [],
            brand: []
        },
        isDirty: false,

        init() {
            this.initializeCheckboxes();
            this.initializeSliders();
            
            // Usa $nextTick per assicurarsi che tutti i componenti Alpine.js siano inizializzati
            this.$nextTick(() => {
                this.applyDecodedFilters(filtersDecoded);
            });
        },
        
        applyDecodedFilters(decoded) {
            if (!decoded || Object.keys(decoded).length === 0) return;
            
            console.log('Applying decoded filters:', decoded);
            
            // Applica filtri range (price, ram, storage, display_size)
            Object.entries(decoded).forEach(([filterKey, filterValue]) => {
                const filter = config.filters[filterKey];
                if (!filter) return;
                
                if (filter.type === 'range' && filterValue.min !== undefined && filterValue.max !== undefined) {
                    // Imposta i valori degli slider
                    const minInput = document.querySelector(`input[data-filter-type="${filterKey}_min"]`);
                    const maxInput = document.querySelector(`input[data-filter-type="${filterKey}_max"]`);
                    
                    if (minInput && maxInput) {
                        const parseFunc = filterKey === 'display_size' ? parseFloat : parseInt;
                        const min = parseFunc(filterValue.min);
                        const max = parseFunc(filterValue.max);
                        
                        // Aggiorna i valori selezionati
                        this.selectedValues[filterKey] = { min, max };
                        
                        // Aggiorna il componente Alpine.js dello slider
                        const sliderContainer = minInput.closest('[x-data]');
                        if (sliderContainer && sliderContainer._x_dataStack) {
                            const sliderComponent = sliderContainer._x_dataStack[0];
                            if (sliderComponent && typeof sliderComponent.minval !== 'undefined') {
                                sliderComponent.minval = min;
                                sliderComponent.maxval = max;
                                console.log(`Updated ${filterKey} slider: min=${min}, max=${max}`);
                            }
                        }
                        
                        // Aggiorna gli activeFilters
                        if (min > filter.min || max < filter.max) {
                            const minFormatted = filterKey === 'display_size' ? parseFloat(min).toFixed(1) : min;
                            const maxFormatted = filterKey === 'display_size' ? parseFloat(max).toFixed(1) : max;
                            const filterText = `${filter.label}: ${minFormatted}${filter.unit} - ${maxFormatted}${filter.unit}`;
                            this.activeFilters.push(filterText);
                        }
                    }
                }
                
                // Applica filtri checkbox (os, brand)
                if (filter.type === 'checkbox' && Array.isArray(filterValue)) {
                    filterValue.forEach(value => {
                        const checkbox = document.querySelector(`input[data-filter-type="${filterKey}"][value="${value}"]`);
                        if (checkbox) {
                            checkbox.checked = true;
                            if (!this.selectedValues[filterKey].includes(value)) {
                                this.selectedValues[filterKey].push(value);
                            }
                            if (!this.activeFilters.includes(value)) {
                                this.activeFilters.push(value);
                            }
                        }
                    });
                }
            });
            
            this.updateFiltersCount();
            console.log('Filters applied. Active filters:', this.activeFilters);
            console.log('Selected values:', this.selectedValues);
        },

        initializeCheckboxes() {
            document.querySelectorAll('input[type="checkbox"]:checked').forEach(checkbox => {
                const filterType = this.getFilterType(checkbox);
                if (filterType) {
                    this.activeFilters.push(checkbox.value);
                    this.selectedValues[filterType].push(checkbox.value);
                }
            });
        },

        initializeSliders() {
            Object.entries(config.filters).forEach(([key, filter]) => {
                if (filter.type === 'range') {
                    const minInput = document.querySelector(`input[data-filter-type="${key}_min"]`);
                    const maxInput = document.querySelector(`input[data-filter-type="${key}_max"]`);
                    if (minInput && maxInput) {
                        minInput.value = filter.min;
                        maxInput.value = filter.max;
                    }
                }
            });
        },

        getFilterType(element) {
            const filterType = element.getAttribute('data-filter-type');
            return filterType || null;
        },

        updateRangeFilter(filterKey, min, max) {
            const filter = config.filters[filterKey];
            if (!filter) return;

            // Remove existing filter
            this.activeFilters = this.activeFilters.filter(f => !f.startsWith(`${filter.label}:`));
            
            // Add new filter if values are different from default
            if (min > filter.min || max < filter.max) {
                // Formatta i valori decimali per display_size
                const minFormatted = filterKey === 'display_size' ? parseFloat(min).toFixed(1) : min;
                const maxFormatted = filterKey === 'display_size' ? parseFloat(max).toFixed(1) : max;
                const filterText = `${filter.label}: ${minFormatted}${filter.unit} - ${maxFormatted}${filter.unit}`;
                this.activeFilters.push(filterText);
                this.selectedValues[filterKey] = { min, max };
            } else {
                this.selectedValues[filterKey] = { min: filter.min, max: filter.max };
            }
        },

        updateToggleFilter(filterKey, value, checked) {
            console.log('updateToggleFilter called:', { filterKey, value, checked });
            const filter = config.filters[filterKey];
            if (!filter) return;

            if (checked) {
                this.activeFilters.push(filter.label);
                if (!this.selectedValues[filterKey].includes(value)) {
                    this.selectedValues[filterKey].push(value);
                }
            } else {
                this.activeFilters = this.activeFilters.filter(f => f !== filter.label);
                this.selectedValues[filterKey] = this.selectedValues[filterKey].filter(v => v !== value);
            }
            
            console.log('selectedValues after toggle:', this.selectedValues);
            
            this.isDirty = true;
            this.updateFiltersCount();
        },

        updateCheckboxFilter(filterKey, value, checked) {
            const filter = config.filters[filterKey];
            if (!filter) return;

            if (checked) {
                if (!this.activeFilters.includes(value)) {
                    this.activeFilters.push(value);
                }
                if (!this.selectedValues[filterKey].includes(value)) {
                    this.selectedValues[filterKey].push(value);
                }
            } else {
                this.activeFilters = this.activeFilters.filter(f => f !== value);
                this.selectedValues[filterKey] = this.selectedValues[filterKey].filter(v => v !== value);
            }
        },

        updateFilters(event) {
            const element = event.target;
            const filterType = this.getFilterType(element);
            
            if (!filterType) return;

            if (element.type === 'range') {
                // Estrai il baseType rimuovendo _min o _max dalla fine
                const baseType = filterType.replace(/_min$|_max$/, '');
                const minInput = document.querySelector(`input[data-filter-type="${baseType}_min"]`);
                const maxInput = document.querySelector(`input[data-filter-type="${baseType}_max"]`);
                
                if (minInput && maxInput) {
                    // Usa parseFloat per filtri con valori decimali
                    const parseFunc = baseType === 'display_size' ? parseFloat : parseInt;
                    const min = parseFunc(minInput.value);
                    const max = parseFunc(maxInput.value);
                    this.updateRangeFilter(baseType, min, max);
                }
            } else if (element.type === 'checkbox') {
                this.updateCheckboxFilter(filterType, element.value, element.checked);
            }

            this.isDirty = true;
            this.updateFiltersCount();
        },

        removeFilter(filter) {
            this.activeFilters = this.activeFilters.filter(f => f !== filter);
            
            // Handle range filters
            Object.entries(config.filters).forEach(([key, filterConfig]) => {
                if (filterConfig.type === 'range' && filter.startsWith(filterConfig.label)) {
                    const minInput = document.querySelector(`input[data-filter-type="${key}_min"]`);
                    const maxInput = document.querySelector(`input[data-filter-type="${key}_max"]`);
                    if (minInput && maxInput) {
                        minInput.value = filterConfig.min;
                        maxInput.value = filterConfig.max;
                        this.selectedValues[key] = { min: filterConfig.min, max: filterConfig.max };
                    }
                }
            });

            // Handle toggle filters (by label)
            Object.entries(config.filters).forEach(([key, filterConfig]) => {
                if (filter === filterConfig.label) {
                    const toggleInput = document.querySelector(`input[data-filter-type="${key}"]`);
                    if (toggleInput && toggleInput.type === 'checkbox') {
                        toggleInput.checked = false;
                        this.selectedValues[key] = [];
                    }
                }
            });

            // Handle checkbox filters (by value)
            const checkbox = document.querySelector(`input[value="${filter}"]`);
            if (checkbox) {
                checkbox.checked = false;
                const filterType = this.getFilterType(checkbox);
                if (filterType) {
                    this.selectedValues[filterType] = this.selectedValues[filterType].filter(v => v !== checkbox.value);
                }
            }

            this.isDirty = true;
            this.updateFiltersCount();
        },

        resetFilters() {
            this.activeFilters = [];
            this.selectedValues = {
                price: { min: config.filters.price.min, max: config.filters.price.max },
                ram: { min: config.filters.ram.min, max: config.filters.ram.max },
                storage: { min: config.filters.storage.min, max: config.filters.storage.max },
                display_size: { min: config.filters.display_size.min, max: config.filters.display_size.max },
                os: [],
                brand: []
            };
            
            // Reset all inputs
            document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
                checkbox.checked = false;
            });

            Object.entries(config.filters).forEach(([key, filter]) => {
                if (filter.type === 'range') {
                    const minInput = document.querySelector(`input[data-filter-type="${key}_min"]`);
                    const maxInput = document.querySelector(`input[data-filter-type="${key}_max"]`);
                    if (minInput && maxInput) {
                        minInput.value = filter.min;
                        maxInput.value = filter.max;
                        this.selectedValues[key] = { min: filter.min, max: filter.max };
                        
                        // Reinizializza i componenti Alpine.js degli slider
                        const sliderContainer = minInput.closest('[x-data]');
                        if (sliderContainer && sliderContainer._x_dataStack) {
                            const sliderComponent = sliderContainer._x_dataStack[0];
                            if (sliderComponent && typeof sliderComponent.minval !== 'undefined') {
                                sliderComponent.minval = filter.min;
                                sliderComponent.maxval = filter.max;
                            }
                        }
                    }
                }
            });

            this.isDirty = false;
            this.updateFiltersCount();
            this.emitFilterUpdate();
            
            // Naviga alla URL base senza filtri
            window.location.href = '/schede-tecniche/tablet/';
        },

        updateFiltersCount() {
            const filtersCountElement = document.getElementById('filters_count');
            if (filtersCountElement) {
                const count = this.activeFilters.length;
                filtersCountElement.textContent = count;
                filtersCountElement.style.display = count >= 1 ? 'flex' : 'none';
            }
        },

        applyFilters() {
            if (this.isDirty) {
                this.emitFilterUpdate();
                this.isDirty = false;
            }
            
            // Costruisci la stringa dei filtri
            let filterString = this.buildFilterString();
            
            
            // Costruisci e naviga verso la nuova URL
            if (filterString) {
                const newUrl = `/schede-tecniche/tablet/${filterString}`;
                window.location.href = newUrl;
            }
        },
        
        buildFilterString() {
            const parts = [];
            
            console.log('Building filter string with selectedValues:', this.selectedValues);
            
            // Aggiungi filtro prezzo se diverso dal default
            if (!Number.isNaN(this.selectedValues.price.min) && !Number.isNaN(this.selectedValues.price.max)) {
                if (typeof this.selectedValues.price.min === 'number' && typeof this.selectedValues.price.max === 'number') {
                    if (this.selectedValues.price.min !== config.filters.price.min || 
                        this.selectedValues.price.max !== config.filters.price.max) {
                        parts.push(`price${this.selectedValues.price.min}-${this.selectedValues.price.max}`);
                    }
                }
            }
            
            
            // Aggiungi filtro ram
            if (this.selectedValues.ram.min !== config.filters.ram.min || 
                this.selectedValues.ram.max !== config.filters.ram.max) {
                parts.push(`ram${this.selectedValues.ram.min}-${this.selectedValues.ram.max}`);
            }
            
            // Aggiungi filtro storage
            if (this.selectedValues.storage.min !== config.filters.storage.min || 
                this.selectedValues.storage.max !== config.filters.storage.max) {
                parts.push(`storage${this.selectedValues.storage.min}-${this.selectedValues.storage.max}`);
            }
            
            // Aggiungi filtro display_size
            if (this.selectedValues.display_size.min !== config.filters.display_size.min || 
                this.selectedValues.display_size.max !== config.filters.display_size.max) {
                const minSize = parseFloat(this.selectedValues.display_size.min).toFixed(1);
                const maxSize = parseFloat(this.selectedValues.display_size.max).toFixed(1);
                parts.push(`display_size${minSize}-${maxSize}`);
            }
            
            // Aggiungi filtro OS
            if (this.selectedValues.os.length > 0) {
                parts.push(`os${this.selectedValues.os.join('-')}`);
            }
            
            // Aggiungi filtro brand
            if (this.selectedValues.brand.length > 0) {
                parts.push(`brands${this.selectedValues.brand.join('-')}`);
            }
            
            // Costruisci la stringa finale
            console.log('Filter parts:', parts);
            if (parts.length > 0) {
                const filterString = '_filter_' + parts.join('_');
                console.log('Final filter string:', filterString);
                return filterString;
            }
            
            return '';
        },

        emitFilterUpdate() {
            const event = new CustomEvent('filter-updated', {
                detail: {
                    os: this.selectedValues.os,
                    brand: this.selectedValues.brand,
                    price: this.selectedValues.price,
                    ram: this.selectedValues.ram,
                    storage: this.selectedValues.storage,
                    display_size: this.selectedValues.display_size
                }
            });
            window.dispatchEvent(event);
        }
    };
}

function activeFilters(formElement) {
    // formElement: a DOM element containing filter inputs
    // Returns an object with active filters
    const filters = {};
    // Checkbox filters
    formElement.querySelectorAll('input[type="checkbox"][data-filter-type]').forEach(input => {
        const type = input.getAttribute('data-filter-type');
        if (!filters[type]) filters[type] = [];
        if (input.checked) filters[type].push(input.value);
    });
    // Range filters (slider)
    formElement.querySelectorAll('input[type="range"][data-filter-type]').forEach(input => {
        const type = input.getAttribute('data-filter-type');
        const value = parseFloat(input.value);
        if (type.endsWith('_min')) {
            const key = type.replace('_min', '');
            if (!filters[key]) filters[key] = {};
            filters[key].min = value;
        } else if (type.endsWith('_max')) {
            const key = type.replace('_max', '');
            if (!filters[key]) filters[key] = {};
            filters[key].max = value;
        }
    });
    return filters;
}
</script>

