





<script>
    document.addEventListener('alpine:init', () => {
        Alpine.store('productCompare', {
            showModal: false,
            showLimitModal: false,
            deviceType: 'smartphone',
            selectedProducts: JSON.parse(localStorage.getItem('selectedProducts_smartphone')) || [],

            _storageKey() {
                return 'selectedProducts_' + this.deviceType;
            },

            addToCompare(product) {
                const formattedProduct = {
                    id: product.id,
                    producer_name: product.producer_name || product.maker || 'Produttore sconosciuto',
                    model: product.model,
                    image_url: product.image_url || ''
                };

                if (this.selectedProducts.length >= 6) {
                    this.showLimitModal = true;
                    return;
                }

                if (!this.selectedProducts.some(p => p.id === formattedProduct.id)) {
                    this.selectedProducts.push(formattedProduct);
                    localStorage.setItem(this._storageKey(), JSON.stringify(this.selectedProducts));
                    this.showModal = true;
                }
            },

            removeFromCompare(productId) {
                this.selectedProducts = this.selectedProducts.filter(p => p.id !== productId);
                localStorage.setItem(this._storageKey(), JSON.stringify(this.selectedProducts));
                if (this.selectedProducts.length === 0) {
                    this.showModal = false;
                }
            },

            _currentComparisonProducts() {
                const source = document.getElementById('current-comparison-products');
                if (!source) {
                    return [];
                }

                try {
                    return Object.entries(JSON.parse(source.textContent)).map(([productId, product]) => ({
                        id: String(product.id || product.model_id || productId || ''),
                        producer_name: product.producer_name || product.maker || product.produttore || '',
                        model: product.model || product.modello || product.name || '',
                        image_url: product.image_url || product.model_image_url || ''
                    })).filter(product => product.id);
                } catch (error) {
                    console.error('Errore nel parsing dei prodotti del confronto:', error);
                    return [];
                }
            },

            removeFromCurrentComparison(productId, removeUrl) {
                const id = String(productId);
                const currentProducts = this._currentComparisonProducts();

                if (currentProducts.length > 0) {
                    this.selectedProducts = currentProducts.filter(product => product.id !== id);
                    localStorage.setItem(this._storageKey(), JSON.stringify(this.selectedProducts));
                } else {
                    this.selectedProducts = this.selectedProducts.filter(product => String(product.id) !== id);
                    localStorage.setItem(this._storageKey(), JSON.stringify(this.selectedProducts));
                }

                if (this.selectedProducts.length > 0) {
                    this.compareProducts();
                    return;
                }

                window.location.href = removeUrl;
            },

            clearAll() {
                this.selectedProducts = [];
                localStorage.setItem(this._storageKey(), JSON.stringify(this.selectedProducts));
                this.showModal = false;
            },

            compareProducts() {
                const query = this.selectedProducts.map(p => p.id).join('-');
                const base = this.deviceType && this.deviceType !== 'smartphone'
                    ? `/compara/${this.deviceType}/`
                    : '/compara/';
                window.location.href = base + query + '.html';
            }
        });
    });
</script>


<script>

    // Funzione per la ricerca dei prodotti
    function productSearch() {
        return {
            query: '',
            filteredProducts: [],
            loading: false,

            async filterProducts() {
                if (this.query.length < 3) {
                    this.filteredProducts = [];
                    return;
                }


                this.loading = true;
                try {
                    //const response = await fetch('http://hdnetwork.test/test.json');
                    const response = await fetch(`/new_files/ajax/fullsearch.php?search_str=${this.query}&ltype=json`);
                    const data = await response.json();
                    this.filteredProducts = data[1];
                } catch (error) {
                    console.error('Errore nel fetch:', error);
                    this.filteredProducts = [];
                } finally {
                    this.loading = false;
                }
            },

            selectProduct(product) {
                this.query = '';  // Reset dell'input
                this.filteredProducts = [];

                // Aggiunge il prodotto selezionato al confronto utilizzando Alpine.store
                Alpine.store('productCompare').addToCompare(product);
            }
        };
    }

    // Component per il confronto dei prodotti
    function productCompare() {
        return Alpine.store('productCompare');
    }

</script>