$(document).ready(function () {
    $('.quick-sign .sign-btn').on('click', function (e) {
        e.preventDefault();
        const parent = $(this).closest('.quick-sign');
        const email = parent.find('input').val().trim();
        if (email !== '') {
            // window.location.href = base_url + 'registration?email=' + email;
            quick_regis(email);
        }
    });
    $('.quick-sign input').on('keydown', function(e) {
        const email = $(this).val().trim();
        if (email != '') {
            if (e.keyCode === 13) {
                e.preventDefault();
                quick_regis(email);
            }
        }    
    });
});

function sendWhatShouldWeCover(tellus) {
    Swal.mixin({
        customClass: {
            confirmButton: "bg-blue",
            cancelButton: "bg-red",
        },
    }).fire({
        title: "Send this idea to us?",
        showCancelButton: true,
        confirmButtonText: "Yes, Send",
        showLoaderOnConfirm: true,
        reverseButtons: true,
        preConfirm: async () => {
            try {
                const url = base_url + 'send_tellus';
                const captchaToken = await grecaptcha.execute(CAPTCHA_FRONT, { action: 'submit' });
                const response = await fetch(url, {method: 'POST', headers: {'Accept': 'application/json', 'Content-Type': 'application/json'}, body: JSON.stringify({'tellus': tellus, 'captcha_token': captchaToken})});
                if (!response.ok) {
                    let res = await response.json();
                    return Swal.showValidationMessage(`
                        ${JSON.stringify(res.message)}
                    `);
                }
                return response.json();
            } catch (error) {
                Swal.showValidationMessage(`
                    Request failed: ${error}
                `);
            }
        },
        allowOutsideClick: () => !Swal.isLoading()
        }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: `Thank You for Sharing Your Ideas!`,
                icon: "success",
                html: `<p class="margin-no">We appreciate you taking the time to let us know what you'd like to see next. Your feedback is invaluable in helping us create content that matters to you.</p>
                <p class="margin-no">Keep an eye out for future updates—we might just feature your suggestion! If you have more ideas, feel free to share them anytime.</p>
                <p class="margin-no">Thanks for being part of our community!</p>`,
            }).then((result) => {
                if (result.isConfirmed) {
                    $('#input-tellus').val("");
                }
            });
        }
    });
}

function alertFillData(url) {
    Swal.mixin({
        customClass: {
            confirmButton: "bg-blue",
            denyButton: "bg-red",
        }
    }).fire({
        title: 'Would you like to complete your profile now? It only takes a minute!',
        showDenyButton: true,
        // showCancelButton: true,
        confirmButtonText: 'Sure',
        denyButtonText: 'Later',
        reverseButtons: true,
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = url +"profile/edit_details";
        }
        // else if (result.isDenied && !result.isDismissed) {
        //     $.ajax({
        //         type: "get",
        //         url: base_url + 'skip_filluserdata',
        //         success: function (response) {}
        //     });
        // }
    })
}

function quick_regis(email) {
    grecaptcha.execute(CAPTCHA_FRONT, { action: 'submit' }).then(function (captchaToken) {
        $.ajax({
            type: "post",
            url: base_url + "quick-regis",
            data: {'email': email, 'captcha_token': captchaToken},
            dataType: "json",
            success: function (response) {
                if (response.status == true) {
                    Swal.mixin({
                        customClass: {
                            confirmButton: "bg-blue"
                        }
                    }).fire({
                        title: "Verify Your Email",
                        icon: "success",
                        html: `<p class="fo18 margin-top-no">Please check your email inbox and follow the instruction to verify your email.</p>
                        <p class="fo12 italic margin-bottom-no">**Do not close this popup if you haven't got the email yet. For further inquiry please <a href="${base_url + 'contact-us'}" target="_blank" class="cl-blue4" style="text-decoration:underline;">contact us</a></p>`,
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        didOpen: () => {
                            // Get the SweetAlert2 actions container
                            const actionsContainer = Swal.getActions();
                        
                            // Create a new button element
                            const customButton = document.createElement('button');
                            customButton.textContent = 'Resend Email';
                            customButton.className = 'swal2-confirm swal2-styled bg-yellow cl-text'; // Match default button styling
                            customButton.style.marginLeft = '10px'; // Add spacing to align properly
                        
                            // Append the custom button to the actions container
                            actionsContainer.appendChild(customButton);
                        
                            // Add an event listener for the custom button
                            customButton.addEventListener('click', () => {
                                Swal.resetValidationMessage();
                                customButton.disabled = true;
                                customButton.textContent = 'Processing...';
                            
                                $.ajax({
                                    type: "post",
                                    url: base_url + "auth/resend-email",
                                    data: { 'email': email, 'ajax': true },
                                    dataType: "json",
                                    success: function (response) {
                                        if (response.status == true) {
                                            // Start cooldown after successful response
                                            let timeleft = 5;
                                            const holdTimer = setInterval(() => {
                                                if (timeleft <= 0) {
                                                    clearInterval(holdTimer);
                                                    customButton.disabled = false;
                                                    customButton.textContent = 'Resend Email';
                                                } else {
                                                    customButton.textContent = `Wait ${timeleft}`;
                                                }
                                                timeleft -= 1;
                                            }, 1000);
                                        } else {
                                            Swal.showValidationMessage('Failed to resend email. Please try again.');
                                            customButton.disabled = false;
                                            customButton.textContent = 'Resend Email';
                                        }
                                    },
                                    error: function (err) {
                                        Swal.showValidationMessage('Something went wrong. Please try again.');
                                        customButton.disabled = false;
                                        customButton.textContent = 'Resend Email';
                                    }
                                });
                            });                            
                        }
                    }).then((result) => {
                        if (result.isConfirmed) {
                            $('.quick-sign input').val(""); // clean up
                        }
                    })
                }
            },
            error: function (err) {
                const error = err.responseJSON;
                Swal.mixin({
                    customClass: {
                        confirmButton: "bg-blue"
                    }
                }).fire({
                    title: error.message
                })
            }
        });
    });
}

function alertToast(type, message) {
    const Toast = Swal.mixin({
        toast: true,
        position: "top-end",
        showConfirmButton: false,
        timer: 4000,
        timerProgressBar: true,
        didOpen: (toast) => {
          toast.onmouseenter = Swal.stopTimer;
          toast.onmouseleave = Swal.resumeTimer;
        }
    });
    Toast.fire({
        icon: type,
        title: message,
    });
}