<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">
        <template x-for="(product, index) in displayedProducts" :key="index">
    <div>
        <div class="group lg:max-w-md max-w-xs flex flex-col text-center items-center relative border hover:shadow-xl p-2 lg:p-4 rounded-lg">                
        
            <a title="Scheda tecnica" :href="product.scheda_tecnica_url" class="w-28 lg:w-16 text-center lg:text-left h-32 max-h-32 flex items-center flex-shrink-0 ">
                <img x-show="product.model_image_url" :src="product.model_image_url" :alt="`${product.produttore} ${product.modello}`" class="block mx-auto object-contain lg:object-left text-white max-h-32" width="" height="">
            </a>

            <div class="py-4 px-1 w-full">
                <div x-text="product.produttore" class="text-primary-dark font-bold text-xs"></div>
                <div x-text="product.modello" class="line-clamp-3 text-base leading-5 font-semibold whitespace-normal min-h-10"></div>
                


            </div>

            <div class="w-full">
                <a :href="`/avviso-prezzo/${product.id}`" @click.prevent="window.priceAlertModal.openPriceAlertModal(product.id, `${product.produttore} ${product.modello}`)" class="mt-2 flex cursor-pointer min-h-10 items-center text-sm justify-between rounded-md bg-slate-100 hover:bg-slate-200 px-2 py-2 w-full">
                                        
                    <span class="text-xs mr-2">Avviso di prezzo</span>
                    <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="M14.857 17.082a23.848 23.848 0 0 0 5.454-1.31A8.967 8.967 0 0 1 18 9.75V9A6 6 0 0 0 6 9v.75a8.967 8.967 0 0 1-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 0 1-5.714 0m5.714 0a3 3 0 1 1-5.714 0M3.124 7.5A8.969 8.969 0 0 1 5.292 3m13.416 0a8.969 8.969 0 0 1 2.168 4.5"></path>
                    </svg>

                </a>
            </div>


            <a :href="product.scheda_tecnica_url" class="mt-2 flex h-10 items-center justify-between rounded-md bg-amber-500 hover:bg-[#fdb04b]  px-2 py-2 text-white w-full">
                <span class="text-xs mr-2">Miglior prezzo</span>
                <span class="text-lg font-normal font-condensed" x-text="`${product.prezzo}&euro;`"></span>
            </a>

            <!-- Nuovo pulsante Compara/Rimuovi -->

        </div>
    </div>
</template>    </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 -->
    <style>
    [x-cloak] {
        display: none !important;
    }
</style>

<div x-data="priceAlertModal()" x-show="showPriceAlertModal" x-cloak 
     class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 backdrop-blur-md">
    
    <div class="fixed inset-0 bg-slate-500/75" aria-hidden="true"></div>
  
    <div class="fixed inset-0 z-10 w-screen overflow-y-auto">
      <div class="flex min-h-full items-center justify-center p-4 text-center sm:items-center sm:p-0">

        <div x-transition:enter="transition ease duration-100" 
             x-transition:enter-start="opacity-0 translate-y-2 sm:translate-y-0 sm:scale-98" 
             x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100" 
             x-transition:leave="transition ease-in duration-100" 
             x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100" 
             x-transition:leave-end="opacity-0 translate-y-2 sm:translate-y-0 sm:scale-98"
             class="relative transform overflow-hidden rounded-md bg-white text-left shadow-xl sm:my-8 sm:w-full sm:max-w-lg">
          <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <div class="sm:flex sm:items-start">
              <div class="mx-auto flex size-12 shrink-0 items-center justify-center rounded-full bg-blue-100 sm:mx-0 sm:size-10">
                <svg class="size-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" aria-hidden="true">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0" />
                </svg>
              </div>
              <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                <div class="text-lg font-bold mt-1" id="modal-title">Avviso di prezzo</div>
                <div class="mt-2">
                  <p class="text-sm mb-3">Troppo caro? Lasciaci la tua email e ti avvisiamo quando il prezzo di <strong x-text="selectedProductName"></strong> scende.</p>
                  
                  <form id="priceAlertForm" @submit.prevent="submitPriceAlert()" class="space-y-4">
                    <div>
                      <label for="email" class="block text-sm font-medium text-slate-700 mb-1"></label>
                      <input type="email" id="email" x-model="alertEmail" required 
                             class="w-full px-3 py-2 border border-slate-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                             placeholder="Inserisci la tua email">
                    </div>
                    
                    <div>
                      <label for="targetPrice" class="block text-sm font-medium text-slate-700 mb-1"></label>
                      <input type="number" id="targetPrice" x-model="targetPrice" min="0" step="0.01"
                             class="w-full px-3 py-2 border border-slate-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                             placeholder="Prezzo desiderato (opzionale)">
                    </div>
                    
                    <div class="flex items-center">
                      <input type="checkbox" id="newsletter" x-model="includeNewsletter" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-slate-300 rounded">
                      <label for="newsletter" class="ml-2 block text-sm text-slate-700 text-left">
                        Ricevi anche la nostra newsletter con le migliori offerte giornaliere
                      </label>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </div>
          <div class="bg-white px-4 pb-4 sm:flex sm:flex-row-reverse sm:px-6">
            <button type="submit" form="priceAlertForm" class="inline-flex w-full justify-center rounded-md bg-blue-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-500 sm:ml-3 sm:w-auto">
              Attiva avviso
            </button>
            <button @click="closePriceAlertModal()" type="button" class="mt-3 inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-slate-900 shadow-sm ring-1 ring-inset ring-slate-300 hover:bg-slate-50 sm:mt-0 sm:w-auto">
              Annulla
            </button>
          </div>
        </div>

      </div>
    </div>

</div>

<script>
// Price Alert Modal functionality
function priceAlertModal() {
    return {
        showPriceAlertModal: false,
        selectedProductId: null,
        selectedProductName: '',
        alertEmail: '',
        targetPrice: '',
        includeNewsletter: false,

        init() {
            // Espone i metodi globalmente per essere chiamati da altri componenti
            window.priceAlertModal = {
                openPriceAlertModal: (productId, productName) => this.openPriceAlertModal(productId, productName),
                closePriceAlertModal: () => this.closePriceAlertModal()
            };
        },

        openPriceAlertModal(productId, productName) {
            this.selectedProductId = productId;
            this.selectedProductName = productName;
            this.showPriceAlertModal = true;
        },

        closePriceAlertModal() {
            this.showPriceAlertModal = false;
            this.alertEmail = '';
            this.targetPrice = '';
            this.includeNewsletter = false;
        },

        submitPriceAlert() {
            // Qui puoi implementare la logica per inviare i dati del price alert
            console.log('Price Alert submitted:', {
                productId: this.selectedProductId,
                productName: this.selectedProductName,
                email: this.alertEmail,
                targetPrice: this.targetPrice,
                includeNewsletter: this.includeNewsletter
            });
            
            // Esempio di chiamata API (da implementare)
            // fetch('/api/price-alerts', {
            //     method: 'POST',
            //     headers: { 'Content-Type': 'application/json' },
            //     body: JSON.stringify({
            //         productId: this.selectedProductId,
            //         productName: this.selectedProductName,
            //         email: this.alertEmail,
            //         targetPrice: this.targetPrice,
            //         includeNewsletter: this.includeNewsletter
            //     })
            // });
            
            // Chiudi il modale dopo l'invio
            this.closePriceAlertModal();
            
            // Mostra un messaggio di successo (opzionale)
            alert('Avviso di prezzo attivato con successo!');
        }
    };
}
</script> </div>

<script>
// Variabile globale con i dati dei prodotti
    window.productsData = [];

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>

