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

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

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

    <div id="filters_actions" class="grid grid-cols-2 gap-2 mb-4" x-cloak x-show="activeFilters.length >= 1">
        <button class="bg-slate-100 hover:bg-slate-200 text-slate-600 lg:text-sm text-base font-medium px-4 py-2 rounded-md w-full relative" @click="resetFilters">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">Applica</button>
    </div>

    <div id="active_filters" class="flex flex-wrap gap-2 mb-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">x</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</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>

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

    <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">Aspirazione (Pa)</button>
        <div x-cloak x-show="open" x-transition class="mb-6">
            {% include "templates/components/prodotti/finder/filters/slider.twig" with {
                id: 'suction',
                min: productFilters.suction.suctionMin|default(0),
                max: productFilters.suction.suctionMax|default(20000),
                unit: 'Pa',
                step: 100
            }%}
        </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">Rumore (dBA)</button>
        <div x-cloak x-show="open" x-transition class="mb-6">
            {% include "templates/components/prodotti/finder/filters/slider.twig" with {
                id: 'noise',
                min: productFilters.noise.noiseMin|default(40),
                max: productFilters.noise.noiseMax|default(80),
                unit: 'dBA',
                step: 0.5,
                useFloat: true
            }%}
        </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">Navigazione</button>
        <div x-cloak x-show="open" x-transition class="mb-6">
            {% include "templates/components/prodotti/finder/filters/checkbox.twig" with {
                id: 'navigation_technology',
                cols: 1,
                loop: productFilters.navigation_technology
            }%}
        </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">Anno</button>
        <div x-cloak x-show="open" x-transition class="mb-6">
            {% include "templates/components/prodotti/finder/filters/checkbox.twig" with {
                id: 'release_year',
                loop: productFilters.release_year
            }%}
        </div>
    </div>

    {% for toggle in [
        {id: 'mapping_supported', label: 'Mappatura'},
        {id: 'carpet_detection', label: 'Rilevamento tappeti'},
        {id: 'hepa_filter', label: 'Filtro HEPA'},
        {id: 'obstacle_avoidance', label: 'Evitamento ostacoli'}
    ] %}
    <div class="border-b py-2">
        <label class="flex items-center justify-between text-sm font-medium text-slate-900">
            <span>{{ toggle.label }}</span>
            <span class="relative inline-flex items-center cursor-pointer">
                <input type="checkbox" aria-label="Attiva filtro {{ toggle.label }}" data-filter-type="{{ toggle.id }}" value="1" @change="updateFilters($event)" class="sr-only peer">
                <span 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"></span>
            </span>
        </label>
    </div>
    {% endfor %}
</section>

<script>
    function filterData() {
        const config = {
            filters: {
                price: { type: 'range', label: 'Prezzo', unit: '\u20AC', min: parseInt('{{productFilters.price.priceMin}}'), max: parseInt('{{productFilters.price.priceMax}}') },
                suction: { type: 'range', label: 'Aspirazione', unit: 'Pa', min: parseInt('{{productFilters.suction.suctionMin|default(0)}}'), max: parseInt('{{productFilters.suction.suctionMax|default(20000)}}') },
                noise: { type: 'range', label: 'Rumore', unit: 'dBA', min: parseFloat('{{productFilters.noise.noiseMin|default(40)}}'), max: parseFloat('{{productFilters.noise.noiseMax|default(80)}}') },
                brand: { type: 'checkbox', label: 'Brand', dataType: 'brand' },
                navigation_technology: { type: 'checkbox', label: 'Navigazione', dataType: 'navigation_technology', labelPrefix: true },
                release_year: { type: 'checkbox', label: 'Anno', dataType: 'release_year', labelPrefix: true },
                mapping_supported: { type: 'toggle', label: 'Mappatura' },
                carpet_detection: { type: 'toggle', label: 'Rilevamento tappeti' },
                hepa_filter: { type: 'toggle', label: 'Filtro HEPA' },
                obstacle_avoidance: { type: 'toggle', label: 'Evitamento ostacoli' }
            }
        };

        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 },
                suction: { min: config.filters.suction.min, max: config.filters.suction.max },
                noise: { min: config.filters.noise.min, max: config.filters.noise.max },
                brand: [],
                navigation_technology: [],
                release_year: [],
                mapping_supported: [],
                carpet_detection: [],
                hepa_filter: [],
                obstacle_avoidance: []
            },
            isDirty: false,
            init() {
                this.$nextTick(() => this.applyDecodedFilters(filtersDecoded));
            },
            applyDecodedFilters(decoded) {
                if (!decoded) return;
                Object.entries(decoded).forEach(([key, value]) => {
                    const filter = config.filters[key];
                    if (!filter) return;
                    if (filter.type === 'range' && value.min !== undefined) {
                        this.selectedValues[key] = { min: value.min, max: value.max };
                        if (value.min > filter.min || value.max < filter.max) {
                            this.activeFilters.push(`${filter.label}: ${value.min}${filter.unit} - ${value.max}${filter.unit}`);
                        }
                    }
                    if ((filter.type === 'checkbox' || filter.type === 'toggle') && Array.isArray(value)) {
                        value.forEach(v => {
                            const checkbox = document.querySelector(`input[data-filter-type="${key}"][value="${v}"]`);
                            if (checkbox) checkbox.checked = true;
                            this.selectedValues[key].push(v);
                            const label = filter.labelPrefix ? `${filter.label}: ${v}` : filter.label;
                            if (!this.activeFilters.includes(label)) this.activeFilters.push(label);
                        });
                    }
                });
            },
            getFilterType(el) { return el.getAttribute('data-filter-type'); },
            updateFilters(event) {
                const el = event.target;
                const type = this.getFilterType(el);
                if (!type) return;
                if (el.type === 'range') {
                    const base = type.replace(/_min$|_max$/, '');
                    const minInput = document.querySelector(`input[data-filter-type="${base}_min"]`);
                    const maxInput = document.querySelector(`input[data-filter-type="${base}_max"]`);
                    if (minInput && maxInput) {
                        const parseFn = base === 'noise' ? parseFloat : parseInt;
                        this.updateRangeFilter(base, parseFn(minInput.value), parseFn(maxInput.value));
                    }
                } else if (el.type === 'checkbox') {
                    const filter = config.filters[type];
                    if (filter.type === 'toggle') {
                        this.selectedValues[type] = el.checked ? ['1'] : [];
                        this.activeFilters = this.activeFilters.filter(f => f !== filter.label);
                        if (el.checked) this.activeFilters.push(filter.label);
                    } else {
                        const display = filter.labelPrefix ? `${filter.label}: ${el.value}` : el.value;
                        if (el.checked) {
                            if (!this.selectedValues[type].includes(el.value)) this.selectedValues[type].push(el.value);
                            if (!this.activeFilters.includes(display)) this.activeFilters.push(display);
                        } else {
                            this.selectedValues[type] = this.selectedValues[type].filter(v => v !== el.value);
                            this.activeFilters = this.activeFilters.filter(f => f !== display);
                        }
                    }
                }
                this.isDirty = true;
            },
            updateRangeFilter(key, min, max) {
                const filter = config.filters[key];
                this.activeFilters = this.activeFilters.filter(f => !f.startsWith(`${filter.label}:`));
                this.selectedValues[key] = { min, max };
                if (min > filter.min || max < filter.max) {
                    this.activeFilters.push(`${filter.label}: ${min}${filter.unit} - ${max}${filter.unit}`);
                }
            },
            removeFilter(filter) {
                this.activeFilters = this.activeFilters.filter(f => f !== filter);
                this.isDirty = true;
            },
            resetFilters() {
                window.location.href = '/schede-tecniche/robot-lavapavimenti/';
            },
            applyFilters() {
                const parts = [];
                const sv = this.selectedValues;
                if (sv.price.min !== config.filters.price.min || sv.price.max !== config.filters.price.max) {
                    parts.push(`price${sv.price.min}-${sv.price.max}`);
                }
                if (sv.suction.min !== config.filters.suction.min || sv.suction.max !== config.filters.suction.max) {
                    parts.push(`suction${sv.suction.min}-${sv.suction.max}`);
                }
                if (sv.noise.min !== config.filters.noise.min || sv.noise.max !== config.filters.noise.max) {
                    parts.push(`noise${sv.noise.min}-${sv.noise.max}`);
                }
                if (sv.brand.length) parts.push(`brands${sv.brand.join('-')}`);
                if (sv.navigation_technology.length) parts.push(`navigation${sv.navigation_technology.join('-')}`);
                if (sv.release_year.length) parts.push(`year${sv.release_year.join('-')}`);
                const togglePrefixes = {
                    mapping_supported: 'mapping',
                    carpet_detection: 'carpet',
                    hepa_filter: 'hepa',
                    obstacle_avoidance: 'obstacle'
                };
                Object.keys(togglePrefixes).forEach(k => {
                    if (sv[k].length) parts.push(`${togglePrefixes[k]}1`);
                });
                const filterString = parts.length ? '_filter_' + parts.join('_') : '';
                window.location.href = filterString
                    ? `/schede-tecniche/robot-lavapavimenti/${filterString}/`
                    : '/schede-tecniche/robot-lavapavimenti/';
            }
        };
    }
</script>
