<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;' %}
{% set ramSteps = productFilters.ram.ramSteps|default([]) %}
{% set ramFallbackMin = productFilters.ram.ramMin|default(0) %}
{% set ramFallbackMax = productFilters.ram.ramMax|default(ramFallbackMin) %}
{% set ramSliderMin = ramSteps|length ? ramSteps|first : ramFallbackMin %}
{% set ramSliderMax = ramSteps|length ? ramSteps|last : ramFallbackMax %}
{% set storageSteps = productFilters.storage.storageSteps|default([]) %}
{% set storageFallbackMin = productFilters.storage.storageMin|default(0) %}
{% set storageFallbackMax = productFilters.storage.storageMax|default(storageFallbackMin) %}
{% set storageSliderMin = storageSteps|length ? storageSteps|first : storageFallbackMin %}
{% set storageSliderMax = storageSteps|length ? storageSteps|last : storageFallbackMax %}
{% set pesoMin = productFilters.weight.weightMin|default(0) %}
{% set pesoMax = productFilters.weight.weightMax|default(pesoMin) %}

<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>

    {# 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: ramSliderMin,
            max: ramSliderMax,
            unit: 'GB',
            step: 1
            }%}
        </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: storageSliderMin,
            max: storageSliderMax,
            unit: 'GB',
            step: 1
            }%}
        </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>

    {# cpu #}
    <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">
            CPU
            <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: 'cpu',
            cols: 1,
            loop: productFilters.cpu
            }%}
        </div>
    </div>

    {# gpu #}
    <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">
            GPU
            <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: 'gpu',
            cols: 1,
            loop: productFilters.gpu
            }%}
        </div>
    </div>




    {# peso #}
    <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">
            Peso
            <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: 'peso',
            min: pesoMin,
            max: pesoMax,
            unit: 'kg',
            step: 0.1,
            useFloat: true
            }%}
        </div>
    </div>




</section>


<script>
    const RAM_STEP_VALUES = JSON.parse("{{ ramSteps|json_encode|e('js') }}");
    const RAM_SLIDER_MIN = parseInt("{{ ramSliderMin }}", 10);
    const RAM_SLIDER_MAX = parseInt("{{ ramSliderMax }}", 10);
    const STORAGE_STEP_VALUES = JSON.parse("{{ storageSteps|json_encode|e('js') }}");
    const STORAGE_SLIDER_MIN = parseInt("{{ storageSliderMin }}", 10);
    const STORAGE_SLIDER_MAX = parseInt("{{ storageSliderMax }}", 10);

    function createDiscreteRangeSupport({ steps, sliderMin, sliderMax, componentName }) {
        const numericSteps = Array.isArray(steps)
            ? steps
                .map(value => (typeof value === 'number' ? value : parseInt(value, 10)))
                .filter(value => Number.isFinite(value))
            : [];
        const uniqueSteps = [...new Set(numericSteps)].sort((a, b) => a - b);
        const hasSteps = uniqueSteps.length > 0;

        const fallbackMin = Number.isFinite(sliderMin) ? sliderMin : 0;
        const fallbackMax = Number.isFinite(sliderMax) ? sliderMax : fallbackMin;

        const defaultMin = hasSteps ? uniqueSteps[0] : fallbackMin;
        const defaultMax = hasSteps ? uniqueSteps[uniqueSteps.length - 1] : fallbackMax;

        const snapValue = (value, direction = 'nearest') => {
            const numericValue = typeof value === 'number' ? value : parseInt(value, 10);

            if (!Number.isFinite(numericValue) || !hasSteps) {
                return numericValue;
            }

            if (direction === 'down') {
                for (let i = uniqueSteps.length - 1; i >= 0; i--) {
                    if (uniqueSteps[i] <= numericValue) {
                        return uniqueSteps[i];
                    }
                }
                return uniqueSteps[0];
            }

            if (direction === 'up') {
                for (let i = 0; i < uniqueSteps.length; i++) {
                    if (uniqueSteps[i] >= numericValue) {
                        return uniqueSteps[i];
                    }
                }
                return uniqueSteps[uniqueSteps.length - 1];
            }

            return uniqueSteps.reduce((closest, current) => {
                return Math.abs(current - numericValue) < Math.abs(closest - numericValue) ? current : closest;
            }, uniqueSteps[0]);
        };

        const normalizeRange = (minValue, maxValue) => {
            const parsedMin = typeof minValue === 'number' ? minValue : parseInt(minValue, 10);
            const parsedMax = typeof maxValue === 'number' ? maxValue : parseInt(maxValue, 10);
            const safeMin = Number.isFinite(parsedMin) ? parsedMin : defaultMin;
            const safeMax = Number.isFinite(parsedMax) ? parsedMax : defaultMax;

            if (!hasSteps) {
                return {
                    min: Math.min(safeMin, safeMax),
                    max: Math.max(safeMin, safeMax)
                };
            }

            const snappedMin = snapValue(safeMin, 'down');
            const snappedMax = snapValue(safeMax, 'up');

            return {
                min: Math.min(snappedMin, snappedMax),
                max: Math.max(snappedMin, snappedMax)
            };
        };

        if (hasSteps && typeof window !== 'undefined') {
            const fnName = `range${componentName}`;
            window[fnName] = (params = {}) => {
                const bounds = normalizeRange(
                    params.min ?? defaultMin,
                    params.max ?? defaultMax
                );
                const componentSteps = uniqueSteps.length ? uniqueSteps : [bounds.min, bounds.max];

                return {
                    min: bounds.min,
                    max: bounds.max,
                    steps: componentSteps,
                    minval: bounds.min,
                    maxval: bounds.max,
                    get minthumb() {
                        return ((this.minval - this.min) / (this.max - this.min)) * 100;
                    },
                    get maxthumb() {
                        return 100 - ((this.maxval - this.min) / (this.max - this.min)) * 100;
                    },
                    mintrigger(e) {
                        let snapped = snapValue(e.target.value, 'down');
                        if (snapped > this.maxval) {
                            snapped = this.maxval;
                        }

                        this.minval = snapped;
                        e.target.value = this.minval;
                    },
                    maxtrigger(e) {
                        let snapped = snapValue(e.target.value, 'up');
                        if (snapped < this.minval) {
                            snapped = this.minval;
                        }

                        this.maxval = snapped;
                        e.target.value = this.maxval;
                    }
                };
            };
        }

        return {
            steps: uniqueSteps,
            hasSteps,
            defaultMin,
            defaultMax,
            normalizeRange
        };
    }

    const ramRangeSupport = createDiscreteRangeSupport({
        steps: RAM_STEP_VALUES,
        sliderMin: RAM_SLIDER_MIN,
        sliderMax: RAM_SLIDER_MAX,
        componentName: 'Ram'
    });

    const storageRangeSupport = createDiscreteRangeSupport({
        steps: STORAGE_STEP_VALUES,
        sliderMin: STORAGE_SLIDER_MIN,
        sliderMax: STORAGE_SLIDER_MAX,
        componentName: 'Storage'
    });

    function filterData() {
        const euro = '&euro;';
        const ramRangeDefaults = ramRangeSupport.normalizeRange(
            ramRangeSupport.defaultMin,
            ramRangeSupport.defaultMax
        );
        const storageRangeDefaults = storageRangeSupport.normalizeRange(
            storageRangeSupport.defaultMin,
            storageRangeSupport.defaultMax
        );
        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: ramRangeDefaults.min,
                    max: ramRangeDefaults.max,
                    dataType: 'ram',
                    steps: ramRangeSupport.steps
                },
                storage: {
                    type: 'range',
                    label: 'Memoria',
                    unit: 'GB',
                    min: storageRangeDefaults.min,
                    max: storageRangeDefaults.max,
                    dataType: 'storage',
                    steps: storageRangeSupport.steps
                },
                display_size: {
                    type: 'range',
                    label: 'Dimensione schermo',
                    unit: 'pollici',
                    min: parseFloat('{{productFilters.display_size.displaySizeMin}}'),
                    max: parseFloat('{{productFilters.display_size.displaySizeMax}}'),
                    dataType: 'display_size'
                },
                peso: {
                    type: 'range',
                    label: 'Peso',
                    unit: 'kg',
                    min: parseFloat('{{pesoMin}}'),
                    max: parseFloat('{{pesoMax}}'),
                    dataType: 'peso'
                },
                cpu: {
                    type: 'checkbox',
                    label: 'CPU',
                    dataType: 'cpu',
                    labelPrefix: true
                },
                gpu: {
                    type: 'checkbox',
                    label: 'GPU',
                    dataType: 'gpu',
                    labelPrefix: true
                },
                brand: {
                    type: 'checkbox',
                    label: 'Brand',
                    dataType: 'brand'
                }
            }
        };

        // Leggi i filtri decodificati dal JSON
        const filtersDecoded = JSON.parse("{{ filters_decoded|default({})|json_encode|e('js') }}");

        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 },
                peso: { min: config.filters.peso.min, max: config.filters.peso.max },
                cpu: [],
                gpu: [],
                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;
                            let min = parseFunc(filterValue.min);
                            let max = parseFunc(filterValue.max);

                            if (filterKey === 'ram') {
                                ({ min, max } = ramRangeSupport.normalizeRange(min, max));
                            } else if (filterKey === 'storage') {
                                ({ min, max } = storageRangeSupport.normalizeRange(min, 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 (gpu, 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);
                                }
                                const displayValue = filter.labelPrefix ? `${filter.label}: ${value}` : value;
                                if (!this.activeFilters.includes(displayValue)) {
                                    this.activeFilters.push(displayValue);
                                }
                            }
                        });
                    }
                });

                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) {
                        const filter = config.filters[filterType];
                        const displayValue = filter && filter.labelPrefix ? `${filter.label}: ${checkbox.value}` : checkbox.value;
                        this.activeFilters.push(displayValue);
                        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;

                if (filterKey === 'ram') {
                    ({ min, max } = ramRangeSupport.normalizeRange(min, max));
                } else if (filterKey === 'storage') {
                    ({ min, max } = storageRangeSupport.normalizeRange(min, max));
                }

                // 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;

                const displayValue = filter.labelPrefix ? `${filter.label}: ${value}` : value;

                if (checked) {
                    if (!this.activeFilters.includes(displayValue)) {
                        this.activeFilters.push(displayValue);
                    }
                    if (!this.selectedValues[filterKey].includes(value)) {
                        this.selectedValues[filterKey].push(value);
                    }
                } else {
                    this.activeFilters = this.activeFilters.filter(f => f !== displayValue);
                    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, with optional label prefix)
                let checkboxValue = filter;
                let checkboxFilterKey = null;
                Object.entries(config.filters).forEach(([key, filterConfig]) => {
                    if (filterConfig.labelPrefix && filter.startsWith(`${filterConfig.label}: `)) {
                        checkboxValue = filter.slice(`${filterConfig.label}: `.length);
                        checkboxFilterKey = key;
                    }
                });
                const checkbox = document.querySelector(`input[data-filter-type="${checkboxFilterKey || ''}"][value="${checkboxValue}"]`)
                    || document.querySelector(`input[value="${checkboxValue}"]`);
                if (checkbox) {
                    checkbox.checked = false;
                    const filterType = checkboxFilterKey || this.getFilterType(checkbox);
                    if (filterType) {
                        this.selectedValues[filterType] = this.selectedValues[filterType].filter(v => v !== checkboxValue);
                    }
                }

                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 },
                    peso: { min: config.filters.peso.min, max: config.filters.peso.max },
                    cpu: [],
                    gpu: [],
                    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/laptop/';
            },

            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/laptop/${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 peso
                if (this.selectedValues.peso.min !== config.filters.peso.min ||
                    this.selectedValues.peso.max !== config.filters.peso.max) {
                    const minPeso = parseFloat(this.selectedValues.peso.min).toFixed(1);
                    const maxPeso = parseFloat(this.selectedValues.peso.max).toFixed(1);
                    parts.push(`peso${minPeso}-${maxPeso}`);
                }

                // Aggiungi filtro CPU
                if (this.selectedValues.cpu.length > 0) {
                    parts.push(`cpu${this.selectedValues.cpu.join('-')}`);
                }

                // Aggiungi filtro GPU
                if (this.selectedValues.gpu.length > 0) {
                    parts.push(`gpu${this.selectedValues.gpu.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: {
                        cpu: this.selectedValues.cpu,
                        gpu: this.selectedValues.gpu,
                        brand: this.selectedValues.brand,
                        price: this.selectedValues.price,
                        ram: this.selectedValues.ram,
                        storage: this.selectedValues.storage,
                        display_size: this.selectedValues.display_size,
                        peso: this.selectedValues.peso
                    }
                });
                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>