<style>
    [x-cloak] {
        display: none !important;
    }

    .no-scrollbar::-webkit-scrollbar {
        display: none;
    }

    .no-scrollbar {
        -ms-overflow-style: none;
        /* IE and Edge */
        scrollbar-width: none;
        /* Firefox */
    }

    .disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }
</style>

<section x-data="productCompare()">

    <div class="grid grid-cols-1 divide-y">
            </div>



    
<div x-show="showModal" x-cloak x-transition:enter="transition ease-in-out duration-300 transform"
    x-transition:enter-start="translate-y-full" x-transition:enter-end="translate-y-0"
    x-transition:leave="transition ease-in-out duration-300 transform" x-transition:leave-start="translate-y-0"
    x-transition:leave-end="translate-y-full"
    class="fixed inset-x-0 bottom-0 bg-white w-full boxed z-30 shadow-[0_-15px_25px_rgba(0,0,0,0.05),0_-5px_10px_rgba(0,0,0,0.05)]">
    <div x-cloak x-show="selectedProducts.length >= 4" class="flex items-center justify-left gap-2 text-left pl-6 font-normal text-xs lg:text-sm mt-4 text-primary">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" data-slot="icon" class="size-6"><path fill-rule="evenodd" d="M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0Zm-7-4a1 1 0 1 1-2 0 1 1 0 0 1 2 0ZM9 9a.75.75 0 0 0 0 1.5h.253a.25.25 0 0 1 .244.304l-.459 2.066A1.75 1.75 0 0 0 10.747 15H11a.75.75 0 0 0 0-1.5h-.253a.25.25 0 0 1-.244-.304l.459-2.066A1.75 1.75 0 0 0 9.253 9H9Z" clip-rule="evenodd"></path></svg> 
        <span class="text-black">Hai raggiunto il limite di</span> <strong>4</strong> <span class="text-black">device da confrontare</span>
    </div>
    <ul class="mb-16 grid lg:grid-cols-2 gap-4">
        <template x-for="product in selectedProducts" :key="product.id">
            <li class="relative flex items-center px-2 py-4 border-b last-of-type:border-0">
                <img :src="product.image_url" alt="Product Image" class="w-16 h-16 object-contain mr-4">
                <span x-text="`${product.producer_name} ${product.model}`"></span>

                <button @click="removeFromCompare(product.id)"
                    class="absolute border-2 right-6 lg:right-10 top-8 text-slate-300 rounded-full border-slate-300 p-2">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="3"
                        stroke="currentColor" class="size-4">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
                    </svg>
                </button>
            </li>
        </template>
    </ul>

</div>


<div x-show="selectedProducts.length" x-cloak x-transition:enter="transition ease-in-out duration-300"
    x-transition:leave="transition ease-in-out duration-300"
    class="fixed boxed bottom-0 left-0 right-0 bg-slate-900 py-2 px-4 flex items-center justify-between shadow-lg z-40">
    <div class="relative flex items-center border-2 border-slate-400 text-slate-400 p-2 rounded-full lg:cursor-pointer">
        <span :class="showModal ? 'opacity-0' : 'opacity-1'"
            class="absolute h-5 w-5 flex bg-emerald-500 text-white font-semibold text-xs transition-opacity ml-4 text-md rounded-full items-center justify-center -left-6 -top-1"
            x-text="selectedProducts.length">
        </span>
        <svg @click="showModal = !showModal" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
            stroke-width="1.5" stroke="currentColor" class="size-6 transition-transform duration-300 cursor-pointer"
            :class="showModal ? 'rotate-180' : 'rotate-0'">
            <path stroke-linecap="round" stroke-linejoin="round" d="m4.5 15.75 7.5-7.5 7.5 7.5" />
        </svg>
    </div>
    <button @click="compareProducts()" :class="selectedProducts.length > 1 ? 'bg-primary border-primary border-2  text-white' : 'bg-transparent text-slate-400 border-2 border-slate-400'"
        class="px-4 py-2 rounded-md text-sm relative font-semibold flex items-center gap-2">
        <span x-text="selectedProducts.length > 1 ? 'VAI AL CONFRONTO' : 'seleziona almeno 2 '">

        </span>
    </button>
</div>

<style>
    .border-slate-400 {
        border-color: #94a3b8;
    }

</style>
    <div x-show="showLimitModal" x-cloak x-transition:enter="transition ease-out duration-300" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100" x-transition:leave="transition ease-in duration-300" x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0" 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 transition-opacity" 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 class="relative transform overflow-hidden rounded-lg bg-white text-left shadow-xl transition-all 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-slate-100 sm:mx-0 sm:size-10">
                <svg class="size-6 text-blue-500" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" aria-hidden="true" data-slot="icon">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z" />
                </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">Limite raggiunto</div>
                <div class="mt-2">
                  <p class="text-sm">Puoi aggiungere un massimo di <strong>4</strong> device al confronto.</p>
                  <p class="text-sm">Per comparare altri prodotti devi rimuovere almeno uno dei selezionati</p>
                </div>
              </div>
            </div>
          </div>
          <div class="px-4 pb-4 sm:flex sm:flex-row-reverse sm:px-6">
            <button @click="showLimitModal = false" type="button" class="inline-flex w-full justify-center rounded-md bg-blue-500 px-3 py-2 text-sm font-semibold text-white shadow-xs hover:bg-blue-600 sm:ml-3 sm:w-auto">Ho capito</button>
          </div>
        </div>


      </div>
    </div>


</div>




</section>





<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 >= 4) {
                    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 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>