<style>
    #modal {
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        opacity: 0;
        transition: opacity .5s ease;
        width: 500px;
        height: 480px;
        z-index: -1;
    }
    #modal.visible {
        opacity: 1;
        transition: opacity .2s ease;
        z-index: 9000;
    }


    #overlay {
        position: fixed;
        top: 0;
        left: 0;
        opacity: 0;
        transition: opacity .2s ease;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, .45);
        backdrop-filter: blur(12px);
        -webkit-backdrop-filter: blur(20px);
        z-index: -1;
        transform: scale(0);
    }
    #overlay.visible {
        transition: opacity .2s ease;
        opacity: 1;
        transform: scale(1);
        z-index: 1000;
    }

    #dismiss_modal {
        width: 24px;
        height: 24px;
        position: absolute;
        right: 10px;
        top: 8px;
        opacity: .5;
        cursor: pointer;
        z-index: 1200;
    }

    @media screen and (max-width: 600px) {
        #modal.visible {
            width: 90%;
            height: 80%;
            top: 28px;
        }
        #overlay {
            backdrop-filter: blur(3px);
        }
    }
</style>

<div id="overlay"></div>
<div id="modal" class="bg-white p-8  rounded-2xl shadow-2xl">
    <div id="dismiss_modal">
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
          </svg>
          
    </div>
    <div class="">
        <div class="items-center">
            <img class="h-5 lg:h-7 w-auto my-4" src="/logo/logo_color.svg" alt="">
            <div class="text-2xl font-semibold my-2">
                La newsletter gratuita 
            </div>
            <p>I migliori contenuti realizzati da HDmotori, impreziositi da commenti e sintesi inediti, ogni giorno nella tua e-mail.</p>
            <div class="bg-white mt-4 rounded-lg w-full max-w-md scrollbar-hide">
    <form id="captcha-form" x-data="formHandler()" @submit.prevent="submitForm">
        <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
        <div x-show="success" class="bg-emerald-200 text-emerald-700 px-4 py-2 rounded-md mb-4 text-xs" x-text="message"></div>
        <div x-show="error" class="bg-red-200 text-red-700 px-4 py-2 rounded-md mb-4 text-xs" x-text="message"></div>
        <div class="mb-4">
            <input type="email" id="email" x-model="email" placeholder="Il tuo indirizzo email" class="w-full px-3 py-4 border rounded-md focus:outline-none focus:border-blue-500" required>
        </div>
        <div class="mb-4" x-show="hideonsuccess">
            <label class="inline-flex items-center">
                <input type="checkbox" x-model="consent" class="form-checkbox size-8" required>
                <span class="ml-2 text-slate-700 text-xs">Ho letto l'informativa sulla <a rel="noopener" class="text-blue-500" target="_blank" href="https://www.hdnetwork.it/privacy-policy">privacy</a> e acconsento al trattamento dei dati. Dichiaro di essere maggiorenne</span>
            </label>
        </div>
        <div class="mb-4" x-show="hideonsuccess">
            <button type="submit" class="relative w-full bg-blue-600 text-white font-bold py-3 px-4 rounded-md hover:bg-blue-500 focus:outline-none focus:bg-blue-600" @click="submitForm">
                Iscriviti
                <div class="absolute inset-y-0 end-4 flex items-center ps-3 pointer-events-none">
                    <div x-show="loading" class="spinner">
                        <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                    </div>
                </div>
            </button>

        </div>
    </form>
</div>



<script>
    grecaptcha.ready(function() {
        grecaptcha.execute('6LfaZgoqAAAAALGx-gX4jZH8fsXWWLtOE-9Ue5Hu', {action: 'submit'}).then(function(token) {
            document.getElementById('g-recaptcha-response').value = token;
        });
    });
    function formHandler() {
        return {
            email: '',
            consent: false,
            success: false,
            error: false,
            loading: false,
            message: '',
            hideonsuccess: true,
            submitForm() {
                if (this.email && this.consent) {
                    const domain = window.location.host;
                    this.loading = true;
                    fetch('https://www.hdmotori.it/wp-json/api/v1/newsletter-register/?timestamp=' + Date.now(), {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            email: this.email,
                            consent: this.consent,
                            refer_url: "https://www.hdmotori.it"
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        this.loading = false;
                        if (!data.error) {
                            this.success = true;
                            this.error = false;
                            this.hideonsuccess = false;
                            this.message = data.message || 'Grazie! Controlla la tua email e conferma l\'iscrizione. Controlla anche le cartelle Spam e Promozioni se non vedi l\'email di conferma';
                        } else {
                            this.success = false;
                            this.error = true;
                            this.hideonsuccess = true;
                            this.message = data.message;
                        }
                    })
                    .catch(() => {
                        this.loading = false;
                        this.success = false;
                        this.error = true;
                        this.hideonsuccess = true;
                        this.message = 'Qualcosa non va, riprova';
                    });
                } else {
                    this.success = false;
                    this.loading = false;
                    this.error = false;
                    this.hideonsuccess = true;
                    this.message = 'Per favore ricontrolla i campi';
                }
            }
        }
    }
</script>


        </div>
    </div>
</div>

<script>
    function shouldShowModal() {
        const lastShown = localStorage.getItem('modalLastShown');
        if (!lastShown ) {
            return true;
        }
        const now = new Date().getTime();
        const oneDay = 24 * 60 * 60 * 1000; // millisecondi in un giorno
        const thirtyDays = oneDay * 30;    //  millisecondi in 30 giorni
        return (now - lastShown) > thirtyDays;
    }

    function showModal() {



        document.getElementById('modal').classList.add('visible');
        document.getElementById('overlay').classList.add('visible');
        localStorage.setItem('modalLastShown', new Date().getTime());
    }


    // Show modal on scroll
    window.onscroll = function () {
        let scrollPosition = window.scrollY || document.documentElement.scrollTop;
        let windowHeight = document.documentElement.scrollHeight - window.innerHeight;
        let scrollPercentage = (scrollPosition / windowHeight) * 100;

        if (scrollPercentage > 25 && shouldShowModal()) {
            
        //if (scrollPercentage > 0 ) {
            showModal();
            window.onscroll = null; // Remove the scroll event listener after displaying the modal
        }

    };

    // Hide modal on overlay click
    document.getElementById('overlay').onclick = function () {
        document.getElementById('modal').classList.remove('visible');
        document.getElementById('overlay').classList.remove('visible');
    };
    document.getElementById('dismiss_modal').onclick = function () {
        document.getElementById('modal').classList.remove('visible');
        document.getElementById('overlay').classList.remove('visible');
    };
</script>



