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


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


    
    <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':''">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M201.4 374.6c12.5 12.5 32.8 12.5 45.3 0l160-160c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L224 306.7 86.6 169.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l160 160z"/></svg>            </div>
        </button>

        <div x-show="open" x-transition class="mb-6">
            <div x-data="rangePrice({ min: , max:  })" class="relative max-w-xl w-full">
    <div class="mt-4">
        <!-- Range inputs -->
        <input
            type="range"
            aria-label="Min price value"
            step="1"
            :min="min"
            :max="max"
            @input="mintrigger"
            x-model="minval"
            data-filter-type="price_min" 
            @change="updateFilters($event)"
            class="absolute pointer-events-none appearance-none z-20 h-2 w-full opacity-0 cursor-pointer"
        >

        <input
            type="range"
            aria-label="Max price value"
            step="1"
            :min="min"
            :max="max"
            @input="maxtrigger"
            x-model="maxval"
            data-filter-type="price_max" 
            @change="updateFilters($event)"
            class="absolute pointer-events-none appearance-none z-20 h-2 w-full opacity-0 cursor-pointer"
        >

        <!-- Track -->
        <div class="relative z-10 h-1">
            <div class="absolute inset-0 rounded-md bg-slate-200"></div>
            <div
                class="absolute top-0 bottom-0 rounded-md bg-primary-dark z-20"
                :style="`left: ${minthumb}%; right: ${maxthumb}%`"
            ></div>
            <div
                class="absolute z-30 w-4 h-4 top-1/2 -translate-y-1/2 bg-primary-dark rounded-full"
                :style="`left: ${minthumb}%`"
            ></div>
            <div
                class="absolute z-30 w-4 h-4 top-1/2 -translate-y-1/2 bg-primary-dark rounded-full"
                :style="`right: ${maxthumb}%`"
            ></div>
        </div>
    </div>

    <!-- Value display -->
    <div class="flex items-center pt-5 text-base lg:text-sm">
                Da <strong class="ml-1"><span x-text="minval"></span>&euro;</strong>
        <span class="mx-1">a</span>
        <strong><span x-text="maxval"></span>&euro;</strong>
            </div>
</div>

<script>
    if (typeof window !== 'undefined' && typeof window.formatStorageLabel !== 'function') {
        window.formatStorageLabel = function formatStorageLabel(value, unit = 'GB') {
            const numericValue = typeof value === 'number' ? value : parseFloat(value);
            if (!Number.isFinite(numericValue)) {
                return `${value}${unit}`;
            }

            const normalizedValue = Number.isInteger(numericValue)
                ? numericValue.toString()
                : numericValue.toFixed(1).replace(/\.0$/, '');

            if (numericValue >= 1000) {
                const tbValue = numericValue / 1024;
                const formattedTb = Number.isInteger(tbValue)
                    ? tbValue.toString()
                    : tbValue.toFixed(1).replace(/\.0$/, '');
                return `${formattedTb}tb`;
            }

            return `${normalizedValue}${unit}`;
        };
    }

    function rangePrice({ min, max }) {
                min = parseInt(min);
        max = parseInt(max);
                return {
            min,
            max,
            minval: min,
            maxval: 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) {
                                this.minval = Math.min(parseInt(e.target.value), this.maxval - 1);
                            },
            maxtrigger(e) {
                                this.maxval = Math.max(parseInt(e.target.value), this.minval + 1);
                            }
        }
    }
</script>
            </div>

    </div>

    
    <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':''">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M201.4 374.6c12.5 12.5 32.8 12.5 45.3 0l160-160c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L224 306.7 86.6 169.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l160 160z"/></svg>            </div>
        </button>

        <div x-cloak x-show="open" x-transition class="mb-6">
            <div class="grid grid-cols-2 gap-2">
    </div>        </div>
    </div>

    
    <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':''">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M201.4 374.6c12.5 12.5 32.8 12.5 45.3 0l160-160c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L224 306.7 86.6 169.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l160 160z"/></svg>            </div>
        </button>

        <div x-cloak x-show="open" x-transition class="mb-6">
            <div x-data="rangeDisplay_size({ min: , max:  })" class="relative max-w-xl w-full">
    <div class="mt-4">
        <!-- Range inputs -->
        <input
            type="range"
            aria-label="Min display_size value"
            step="0.1"
            :min="min"
            :max="max"
            @input="mintrigger"
            x-model="minval"
            data-filter-type="display_size_min" 
            @change="updateFilters($event)"
            class="absolute pointer-events-none appearance-none z-20 h-2 w-full opacity-0 cursor-pointer"
        >

        <input
            type="range"
            aria-label="Max display_size value"
            step="0.1"
            :min="min"
            :max="max"
            @input="maxtrigger"
            x-model="maxval"
            data-filter-type="display_size_max" 
            @change="updateFilters($event)"
            class="absolute pointer-events-none appearance-none z-20 h-2 w-full opacity-0 cursor-pointer"
        >

        <!-- Track -->
        <div class="relative z-10 h-1">
            <div class="absolute inset-0 rounded-md bg-slate-200"></div>
            <div
                class="absolute top-0 bottom-0 rounded-md bg-primary-dark z-20"
                :style="`left: ${minthumb}%; right: ${maxthumb}%`"
            ></div>
            <div
                class="absolute z-30 w-4 h-4 top-1/2 -translate-y-1/2 bg-primary-dark rounded-full"
                :style="`left: ${minthumb}%`"
            ></div>
            <div
                class="absolute z-30 w-4 h-4 top-1/2 -translate-y-1/2 bg-primary-dark rounded-full"
                :style="`right: ${maxthumb}%`"
            ></div>
        </div>
    </div>

    <!-- Value display -->
    <div class="flex items-center pt-5 text-base lg:text-sm">
                Da <strong class="ml-1"><span x-text="parseFloat(minval).toFixed(1)"></span>pollici</strong>
        <span class="mx-1">a</span>
        <strong><span x-text="parseFloat(maxval).toFixed(1)"></span>pollici</strong>
            </div>
</div>

<script>
    if (typeof window !== 'undefined' && typeof window.formatStorageLabel !== 'function') {
        window.formatStorageLabel = function formatStorageLabel(value, unit = 'GB') {
            const numericValue = typeof value === 'number' ? value : parseFloat(value);
            if (!Number.isFinite(numericValue)) {
                return `${value}${unit}`;
            }

            const normalizedValue = Number.isInteger(numericValue)
                ? numericValue.toString()
                : numericValue.toFixed(1).replace(/\.0$/, '');

            if (numericValue >= 1000) {
                const tbValue = numericValue / 1024;
                const formattedTb = Number.isInteger(tbValue)
                    ? tbValue.toString()
                    : tbValue.toFixed(1).replace(/\.0$/, '');
                return `${formattedTb}tb`;
            }

            return `${normalizedValue}${unit}`;
        };
    }

    function rangeDisplay_size({ min, max }) {
                min = parseFloat(min);
        max = parseFloat(max);
                return {
            min,
            max,
            minval: min,
            maxval: 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) {
                                this.minval = Math.min(parseFloat(e.target.value), this.maxval - 0.1);
                            },
            maxtrigger(e) {
                                this.maxval = Math.max(parseFloat(e.target.value), this.minval + 0.1);
                            }
        }
    }
</script>
            </div>
    </div>

    
    <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':''">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M201.4 374.6c12.5 12.5 32.8 12.5 45.3 0l160-160c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L224 306.7 86.6 169.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l160 160z"/></svg>            </div>
        </button>

        <div x-cloak x-show="open" x-transition class="mb-6">
            <div x-data="rangeWeight({ min: , max:  })" class="relative max-w-xl w-full">
    <div class="mt-4">
        <!-- Range inputs -->
        <input
            type="range"
            aria-label="Min weight value"
            step="1"
            :min="min"
            :max="max"
            @input="mintrigger"
            x-model="minval"
            data-filter-type="weight_min" 
            @change="updateFilters($event)"
            class="absolute pointer-events-none appearance-none z-20 h-2 w-full opacity-0 cursor-pointer"
        >

        <input
            type="range"
            aria-label="Max weight value"
            step="1"
            :min="min"
            :max="max"
            @input="maxtrigger"
            x-model="maxval"
            data-filter-type="weight_max" 
            @change="updateFilters($event)"
            class="absolute pointer-events-none appearance-none z-20 h-2 w-full opacity-0 cursor-pointer"
        >

        <!-- Track -->
        <div class="relative z-10 h-1">
            <div class="absolute inset-0 rounded-md bg-slate-200"></div>
            <div
                class="absolute top-0 bottom-0 rounded-md bg-primary-dark z-20"
                :style="`left: ${minthumb}%; right: ${maxthumb}%`"
            ></div>
            <div
                class="absolute z-30 w-4 h-4 top-1/2 -translate-y-1/2 bg-primary-dark rounded-full"
                :style="`left: ${minthumb}%`"
            ></div>
            <div
                class="absolute z-30 w-4 h-4 top-1/2 -translate-y-1/2 bg-primary-dark rounded-full"
                :style="`right: ${maxthumb}%`"
            ></div>
        </div>
    </div>

    <!-- Value display -->
    <div class="flex items-center pt-5 text-base lg:text-sm">
                Da <strong class="ml-1"><span x-text="minval"></span>g</strong>
        <span class="mx-1">a</span>
        <strong><span x-text="maxval"></span>g</strong>
            </div>
</div>

<script>
    if (typeof window !== 'undefined' && typeof window.formatStorageLabel !== 'function') {
        window.formatStorageLabel = function formatStorageLabel(value, unit = 'GB') {
            const numericValue = typeof value === 'number' ? value : parseFloat(value);
            if (!Number.isFinite(numericValue)) {
                return `${value}${unit}`;
            }

            const normalizedValue = Number.isInteger(numericValue)
                ? numericValue.toString()
                : numericValue.toFixed(1).replace(/\.0$/, '');

            if (numericValue >= 1000) {
                const tbValue = numericValue / 1024;
                const formattedTb = Number.isInteger(tbValue)
                    ? tbValue.toString()
                    : tbValue.toFixed(1).replace(/\.0$/, '');
                return `${formattedTb}tb`;
            }

            return `${normalizedValue}${unit}`;
        };
    }

    function rangeWeight({ min, max }) {
                min = parseInt(min);
        max = parseInt(max);
                return {
            min,
            max,
            minval: min,
            maxval: 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) {
                                this.minval = Math.min(parseInt(e.target.value), this.maxval - 1);
                            },
            maxtrigger(e) {
                                this.maxval = Math.max(parseInt(e.target.value), this.minval + 1);
                            }
        }
    }
</script>
            </div>
    </div>

    
    <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"
            >
            Capacit&agrave; batteria
            <div class="h-3 w-3 ml-2 fill-primary-dark block" :class="open?'rotate-180':''">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M201.4 374.6c12.5 12.5 32.8 12.5 45.3 0l160-160c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L224 306.7 86.6 169.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l160 160z"/></svg>            </div>
        </button>

        <div x-cloak x-show="open" x-transition class="mb-6">
            <div x-data="rangeBattery({ min: , max:  })" class="relative max-w-xl w-full">
    <div class="mt-4">
        <!-- Range inputs -->
        <input
            type="range"
            aria-label="Min battery value"
            step="100"
            :min="min"
            :max="max"
            @input="mintrigger"
            x-model="minval"
            data-filter-type="battery_min" 
            @change="updateFilters($event)"
            class="absolute pointer-events-none appearance-none z-20 h-2 w-full opacity-0 cursor-pointer"
        >

        <input
            type="range"
            aria-label="Max battery value"
            step="100"
            :min="min"
            :max="max"
            @input="maxtrigger"
            x-model="maxval"
            data-filter-type="battery_max" 
            @change="updateFilters($event)"
            class="absolute pointer-events-none appearance-none z-20 h-2 w-full opacity-0 cursor-pointer"
        >

        <!-- Track -->
        <div class="relative z-10 h-1">
            <div class="absolute inset-0 rounded-md bg-slate-200"></div>
            <div
                class="absolute top-0 bottom-0 rounded-md bg-primary-dark z-20"
                :style="`left: ${minthumb}%; right: ${maxthumb}%`"
            ></div>
            <div
                class="absolute z-30 w-4 h-4 top-1/2 -translate-y-1/2 bg-primary-dark rounded-full"
                :style="`left: ${minthumb}%`"
            ></div>
            <div
                class="absolute z-30 w-4 h-4 top-1/2 -translate-y-1/2 bg-primary-dark rounded-full"
                :style="`right: ${maxthumb}%`"
            ></div>
        </div>
    </div>

    <!-- Value display -->
    <div class="flex items-center pt-5 text-base lg:text-sm">
                Da <strong class="ml-1"><span x-text="minval"></span>mAh</strong>
        <span class="mx-1">a</span>
        <strong><span x-text="maxval"></span>mAh</strong>
            </div>
</div>

<script>
    if (typeof window !== 'undefined' && typeof window.formatStorageLabel !== 'function') {
        window.formatStorageLabel = function formatStorageLabel(value, unit = 'GB') {
            const numericValue = typeof value === 'number' ? value : parseFloat(value);
            if (!Number.isFinite(numericValue)) {
                return `${value}${unit}`;
            }

            const normalizedValue = Number.isInteger(numericValue)
                ? numericValue.toString()
                : numericValue.toFixed(1).replace(/\.0$/, '');

            if (numericValue >= 1000) {
                const tbValue = numericValue / 1024;
                const formattedTb = Number.isInteger(tbValue)
                    ? tbValue.toString()
                    : tbValue.toFixed(1).replace(/\.0$/, '');
                return `${formattedTb}tb`;
            }

            return `${normalizedValue}${unit}`;
        };
    }

    function rangeBattery({ min, max }) {
                min = parseInt(min);
        max = parseInt(max);
                return {
            min,
            max,
            minval: min,
            maxval: 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) {
                                this.minval = Math.min(parseInt(e.target.value), this.maxval - 100);
                            },
            maxtrigger(e) {
                                this.maxval = Math.max(parseInt(e.target.value), this.minval + 100);
                            }
        }
    }
</script>
            </div>
    </div>


    
    <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"
            >
            Tipo display
            <div class="h-3 w-3 ml-2 fill-primary-dark block" :class="open?'rotate-180':''">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M201.4 374.6c12.5 12.5 32.8 12.5 45.3 0l160-160c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L224 306.7 86.6 169.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l160 160z"/></svg>            </div>
        </button>
        <div x-cloak x-show="open" x-transition class="mb-6">
            <div class="grid grid-cols-1 gap-2">
    </div>        </div>
    </div>

    
    <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"
            >
            Compatibile con
            <div class="h-3 w-3 ml-2 fill-primary-dark block" :class="open?'rotate-180':''">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M201.4 374.6c12.5 12.5 32.8 12.5 45.3 0l160-160c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L224 306.7 86.6 169.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l160 160z"/></svg>            </div>
        </button>
        <div x-cloak x-show="open" x-transition class="mb-6">
            <div class="grid grid-cols-2 gap-2">
    </div>        </div>
    </div>


    
    <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':''">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M201.4 374.6c12.5 12.5 32.8 12.5 45.3 0l160-160c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L224 306.7 86.6 169.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l160 160z"/></svg>            </div>
        </button>

        <div x-cloak x-show="open" x-transition class="mb-6">
            <div class="grid grid-cols-1 gap-2">
    </div>        </div>
    </div>

    
    <div class="flex items-center justify-between text-slate-900 py-2 lg:text-sm text-base font-medium border-b">
        <span>Supporto pagamenti</span>
        <label class="relative inline-flex items-center cursor-pointer">
            <input type="checkbox" aria-label="Attiva filtro supporto pagamenti" id="payment_supported" name="payment_supported" value="true" data-filter-type="payment_supported" @change="updateToggleFilter('payment_supported', $event.target.value, $event.target.checked)" class="sr-only peer">
            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-dark"></div>
        </label>
    </div>

    
    <div class="flex items-center justify-between text-slate-900 py-2 lg:text-sm text-base font-medium border-b">
        <span>SIM</span>
        <label class="relative inline-flex items-center cursor-pointer">
            <input type="checkbox" aria-label="Attiva filtro SIM" id="sim" name="sim" value="true" data-filter-type="sim" @change="updateToggleFilter('sim', $event.target.value, $event.target.checked)" class="sr-only peer">
            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-dark"></div>
        </label>
    </div>


</section>


<script>
function filterData() {
    const euro = '&euro;';
    const config = {
        filters: {
            price: {
                type: 'range',
                label: 'Prezzo',
                unit: '\u20AC',
                min: parseInt(''),
                max: parseInt(''),
                dataType: 'price'
            },
            display_size: {
                type: 'range',
                label: 'Dimensione schermo',
                unit: 'pollici',
                min: parseFloat(''),
                max: parseFloat(''),
                dataType: 'display_size'
            },
            os: {
                type: 'checkbox',
                label: 'Sistema Operativo',
                dataType: 'os'
            },
            brand: {
                type: 'checkbox',
                label: 'Brand',
                dataType: 'brand'
            },
            weight: {
                type: 'range',
                label: 'Peso',
                unit: 'g',
                min: parseInt(''),
                max: parseInt(''),
                dataType: 'weight'
            },
            battery: {
                type: 'range',
                label: 'Batteria',
                unit: 'mAh',
                min: parseInt(''),
                max: parseInt(''),
                dataType: 'battery'
            },
            sim: {
                type: 'checkbox',
                label: 'SIM',
                dataType: 'sim'
            },
            payment_supported: {
                type: 'checkbox',
                label: 'Supporto pagamenti',
                dataType: 'payment_supported'
            },
            supported_opsys: {
                type: 'checkbox',
                label: 'Compatibile con',
                dataType: 'supported_opsys'
            },
            display_type: {
                type: 'checkbox',
                label: 'Tipo display',
                dataType: 'display_type'
            }
        }
    };
    
    // Leggi i filtri decodificati dal JSON
    const filtersDecoded = {};

    return {
        activeFilters: [],
        selectedValues: {
            price: { min: config.filters.price.min, max: config.filters.price.max },
            display_size: { min: config.filters.display_size.min, max: config.filters.display_size.max },
            os: [],
            brand: [],
            weight: { min: config.filters.weight.min, max: config.filters.weight.max },
            battery: { min: config.filters.battery.min, max: config.filters.battery.max },
            sim: [],
            payment_supported: [],
            display_type: [],
            supported_opsys: []
        },
        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);
            
            // Mappa chiavi alternative (payment_support -> payment_supported)
            const keyMapping = {
                'payment_support': 'payment_supported'
            };
            
            // Applica filtri range (price, ram, storage, display_size)
            Object.entries(decoded).forEach(([filterKey, filterValue]) => {
                // Applica mapping se necessario
                const mappedKey = keyMapping[filterKey] || filterKey;
                const filter = config.filters[mappedKey];
                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="${mappedKey}_min"]`);
                    const maxInput = document.querySelector(`input[data-filter-type="${mappedKey}_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[mappedKey] = { 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 = mappedKey === 'display_size' ? parseFloat(min).toFixed(1) : min;
                            const maxFormatted = mappedKey === '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, display_type, supported_opsys)
                if (filter.type === 'checkbox' && Array.isArray(filterValue)) {
                    // Verifica se è un toggle filter (sim, payment_supported) - hanno un singolo checkbox
                    const toggleInput = document.querySelector(`input[data-filter-type="${mappedKey}"]`);
                    const isToggleFilter = toggleInput && toggleInput.type === 'checkbox' && 
                                          document.querySelectorAll(`input[data-filter-type="${mappedKey}"]`).length === 1;
                    
                    if (isToggleFilter) {
                        // Toggle filter: usa la label, gestisce booleani nell'array
                        if (filterValue.length > 0) {
                            let value = filterValue[0];
                            // Converti booleano in stringa se necessario
                            if (typeof value === 'boolean') {
                                value = value ? 'true' : 'false'; 
                            } else {
                                value = String(value);
                            }
                            
                            // Verifica se il valore indica attivazione
                            if (value === 'true' || value === '1' || value === true) {
                                toggleInput.checked = true;
                                if (!this.selectedValues[mappedKey].includes('true')) {
                                    this.selectedValues[mappedKey].push('true');
                                }
                                if (!this.activeFilters.includes(filter.label)) {
                                    this.activeFilters.push(filter.label);
                                }
                            }
                        }
                    } else {
                        // Checkbox filter normale: usa il valore
                        filterValue.forEach(value => {
                            const checkbox = document.querySelector(`input[data-filter-type="${mappedKey}"][value="${value}"]`);
                            if (checkbox) {
                                checkbox.checked = true;
                                if (!this.selectedValues[mappedKey].includes(value)) {
                                    this.selectedValues[mappedKey].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 };
                        
                        // 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 = filterConfig.min;
                                sliderComponent.maxval = 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 },
                display_size: { min: config.filters.display_size.min, max: config.filters.display_size.max },
                os: [],
                brand: [],
                weight: { min: config.filters.weight.min, max: config.filters.weight.max },
                battery: { min: config.filters.battery.min, max: config.filters.battery.max },
                sim: [],
                payment_supported: [],
                display_type: [],
                supported_opsys: []
            };
            
            // 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/smartwatch/';
        },

        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/smartwatch/${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 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 weight
            if (this.selectedValues.weight.min !== config.filters.weight.min || 
                this.selectedValues.weight.max !== config.filters.weight.max) {
                parts.push(`weight${this.selectedValues.weight.min}-${this.selectedValues.weight.max}`);
            }

                // Aggiungi filtro battery
            if (this.selectedValues.battery.min !== config.filters.battery.min || 
                this.selectedValues.battery.max !== config.filters.battery.max) {
                parts.push(`battery${this.selectedValues.battery.min}-${this.selectedValues.battery.max}`);
            }
            
            // 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('-')}`);
            }

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

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

            // Aggiungi filtro payment_supported
            if (this.selectedValues.payment_supported.length > 0) {
                parts.push(`payment_supported${this.selectedValues.payment_supported.join('-')}`);
            }
            
            // Aggiungi filtro sim
            if (this.selectedValues.sim.length > 0) {
                parts.push(`sim${this.selectedValues.sim.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,
                    display_size: this.selectedValues.display_size,
                    weight: this.selectedValues.weight,
                    battery: this.selectedValues.battery,
                    sim: this.selectedValues.sim,
                    payment_supported: this.selectedValues.payment_supported,
                    display_type: this.selectedValues.display_type,
                    supported_opsys: this.selectedValues.supported_opsys
                }
            });
            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>

