<div class="results-container min-h-screen" x-data="productFilter()">

    <div class="text-center py-8" x-cloak x-show="filteredResults.length === 0">
        <div class="text-gray-200 text-center">
            <svg version="1.1" class="w-44 h-auto block mx-auto" fill="currentColor" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
            viewBox="0 0 487.601 487.601" style="enable-background:new 0 0 487.601 487.601;" xml:space="preserve">
                <g>
                    <g id="XMLID_1736_">
                        <path id="XMLID_1737_" d="M379,229.65c-25.6,0-46.3,20.8-46.3,46.3c0,6.1,5,11.1,11.1,11.1s11.1-5,11.1-11.1
                            c0-13.3,10.9-24.2,24.2-24.2c6.1,0,11.1-5,11.1-11.1C390.1,234.55,385.1,229.65,379,229.65z"/>
                        <path id="XMLID_1738_" d="M454.5,197.75c-2.7-2.6-5.6-5.1-8.6-7.5l0,0l-41-34.8c-15.8-11.2-34.6-18.3-55-19.7l2.2,2.2l-24.9-25
                            H327c-6.9-6.3-16.2-10.2-26.3-10.2c-17.4,0-32.1,11.3-37.1,27c-5-3.2-10.8-5.1-17.1-5.5c-1-0.1-2.1-0.1-3.1-0.1
                            c-7.1,0-13.7,2.1-19.3,5.6c-5.1-15.6-19.8-26.9-37.1-26.9c-10.1,0-19.3,3.8-26.3,10.2h-0.2l-24.9,25l2.2-2.2
                            c-20.4,1.4-39.3,8.6-55,19.7l-41,34.8l0,0c-3,2.3-5.9,4.8-8.6,7.5C12.7,217.65,0,245.35,0,276.05c0,60,48.8,108.8,108.8,108.8
                            c55.4,0,101.3-41.7,107.9-95.4c8,4.6,17.3,7.2,27.1,7.2c9.9,0,19.1-2.6,27.1-7.2c6.7,53.6,52.5,95.3,107.9,95.3
                            c60,0,108.8-48.8,108.8-108.8C487.7,245.25,475,217.55,454.5,197.75z M108.8,350.25c-41,0-74.2-33.2-74.2-74.2
                            s33.2-74.2,74.2-74.2s74.2,33.2,74.2,74.2C183.1,316.95,149.8,350.25,108.8,350.25z M243.9,265.85c-13.3,0-24.1-10.8-24.1-24.1
                            c0-13.3,10.8-24.1,24.1-24.1c13.3,0,24.1,10.8,24.1,24.1C268,255.05,257.2,265.85,243.9,265.85z M379,350.25
                            c-41,0-74.2-33.2-74.2-74.2s33.2-74.2,74.2-74.2s74.2,33.2,74.2,74.2C453.2,316.95,420,350.25,379,350.25z"/>
                        <path id="XMLID_1745_" d="M108.8,229.65c-25.6,0-46.3,20.8-46.3,46.3c0,6.1,5,11.1,11.1,11.1c6.1,0,11.1-5,11.1-11.1
                            c0-13.3,10.9-24.2,24.2-24.2c6.1,0,11.1-5,11.1-11.1C119.9,234.55,114.9,229.65,108.8,229.65z"/>
                    </g>
                </g>
            </svg>
        </div>
        <div class="text-xl">Nessun risultato trovato</div>
        <div class="text-base text-slate-400 ">Prova a cambiare o resettare i filtri di ricerca</div>
    </div>

    <div x-cloak x-show="filteredResults.length > 0" class="grid lg:grid-cols-3 grid-cols-2 gap-2 -mx-2 lg:mx-0 lg:gap-4 mb-12">
        {% include "templates/components/prodotti/finder/product-card.twig" %}
    </div>
    <div class="flex justify-center mt-6" x-cloak x-show="filteredResults.length > 0 && hasMoreProducts()">
        <button @click="loadMore()" class="px-4 py-2 border text-sm text-slate-500 rounded-md hover:bg-slate-100 -mt-6 mb-12 flex items-center gap-2">
 
            <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="M12 4.5v15m7.5-7.5h-15" />
            </svg>
            <span>Carica altro</span>
        </button>
    </div>

    <!-- Price Alert Modal -->
    {% include "templates/components/prodotti/price-alert-modal.twig" %}
</div>

<script>
// Variabile globale con i dati dei prodotti
{% if products is defined %}
    window.productsData = {{ products|json_encode|raw }};
{% else %}
    window.productsData = [];
{% endif %}

function productFilter() {
    return {
        allProducts: window.productsData,
        filteredResults: [],
        displayedProducts: [],
        currentPage: 1,
        productsPerPage: 12,
        searchTerm: '',
        currentFilters: {
            os: [],
            brands: [],
            payment_ready: [],
            price: { min: 0, max: 999999 },
            camera: { min: 0, max: 999999 }
        },

        init() {
            // Inizializza con tutti i prodotti
            this.filteredResults = [...this.allProducts];
            this.updateDisplayedProducts();
            
            // Ascolta l'evento filter-updated
            window.addEventListener('filter-updated', (event) => {
                this.currentFilters = event.detail;
                this.applyFilters();
            });

            // Ascolta l'evento search-updated
            window.addEventListener('search-updated', (event) => {
                console.log('Search event received:', event.detail);
                this.searchTerm = event.detail;
                this.applyFilters();
            });
        },

        applyFilters() {
            console.log('Applying filters with search term:', this.searchTerm);
            console.log('Total products:', this.allProducts.length);
            
            this.filteredResults = this.allProducts.filter(product => {
                return this.matchesFilters(product, this.searchTerm);
            });
            
            console.log('Filtered results:', this.filteredResults.length);
            
            this.currentPage = 1;
            this.updateDisplayedProducts();
        },

        updateDisplayedProducts() {
            const startIndex = 0;
            const endIndex = this.currentPage * this.productsPerPage;
            this.displayedProducts = this.filteredResults.slice(startIndex, endIndex);
        },

        loadMore() {
            this.currentPage++;
            this.updateDisplayedProducts();
        },

        hasMoreProducts() {
            return this.displayedProducts.length < this.filteredResults.length;
        },

        matchesFilters(product, searchTerm) {
            // Filtro per ricerca testuale
            if (searchTerm && searchTerm.trim() !== '') {
                const searchLower = searchTerm.toLowerCase().trim();
                const productName = `${product.produttore} ${product.modello}`.toLowerCase();
                
                if (!productName.includes(searchLower)) {
                    return false;
                }
            }

            // Filtro per OS
            if (this.currentFilters.os.length > 0) {
                const productOS = this.getProductFeature(product, 'os');
                if (!productOS || !this.currentFilters.os.includes(productOS.slug)) {
                    return false;
                }
            }

            // Filtro per Brand
            if (this.currentFilters.brands.length > 0) {
                const productBrand = product.produttore.toLowerCase();
                if (!this.currentFilters.brands.some(brand => 
                    productBrand.includes(brand.toLowerCase())
                )) {
                    return false;
                }
            }

            // Filtro per Prezzo
            const productPrice = parseInt(product.prezzo);
            if (productPrice < this.currentFilters.price.min || 
                productPrice > this.currentFilters.price.max) {
                return false;
            }

            // Filtro per Camera
            if (this.currentFilters.camera.min > 0 || this.currentFilters.camera.max < 999999) {
                const productCamera = this.getProductFeature(product, 'camera');
                if (productCamera) {
                    const cameraValue = this.extractCameraValue(productCamera.value);
                    if (cameraValue < this.currentFilters.camera.min || 
                        cameraValue > this.currentFilters.camera.max) {
                        return false;
                    }
                }
            }

            // Filtro per Supporto pagamenti
            if (this.currentFilters.payment_ready.length > 0) {
                const productPaymentReady = this.getProductFeature(product, 'payment_ready');
                if (!productPaymentReady || !this.currentFilters.payment_ready.includes(productPaymentReady.slug)) {
                    return false;
                }
            }

            return true;
        },

        getProductFeature(product, filterType) {
            return product.features?.find(feature => feature.filter === filterType);
        },

        extractCameraValue(cameraString) {
            // Estrae il valore numerico dalla stringa della camera (es: "108 Mpx" -> 108)
            const match = cameraString.match(/(\d+)/);
            return match ? parseInt(match[1]) : 0;
        },

    };
}
</script>

