(function () {
    'use strict';

    function initializeCheckout() {
        // Hide all popups immediately — prevents FOUC flash
        document.querySelectorAll('.sitsel-popup').forEach(function (popup) {
            popup.style.display = 'none';
        });

        document.querySelectorAll('[data-sitsel-checkout-btn]').forEach(function (button) {
            if (button.dataset.sitselInitialized) return;
            button.dataset.sitselInitialized = 'true';
            setupButton(button);
        });
    }

    function setupButton(button) {
        const wrapper = button.closest('.sitsel-btn-wrapper');
        if (!wrapper) return;

        const popup = wrapper.querySelector('.sitsel-popup');
        const closeBtn = wrapper.querySelector('.close-btn');
        const form = wrapper.querySelector('.sitsel-checkout-form');

        if (!popup || !closeBtn || !form) return;

        const buttonId = button.id;

        // Style close button to match main button
        const buttonStyles = window.getComputedStyle(button);
        closeBtn.style.background = buttonStyles.backgroundColor;
        closeBtn.style.color = buttonStyles.color;

        // Open popup
        button.addEventListener('click', function (e) {
            e.preventDefault();
            popup.style.display = ''; // clear inline hide
            popup.classList.add('active');
        });

        // Close popup - close btn
        closeBtn.addEventListener('click', function (e) {
            e.preventDefault();
            popup.classList.remove('active');
            popup.style.display = 'none';
        });

        // Close popup - backdrop click
        popup.addEventListener('click', function (e) {
            if (e.target === popup) {
                popup.classList.remove('active');
                popup.style.display = 'none';
            }
        });

        // Close popup - Escape key
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape' && popup.classList.contains('active')) {
                popup.classList.remove('active');
                popup.style.display = 'none';
            }
        });

        // Form submission
        form.addEventListener('submit', function (e) {
            e.preventDefault();

            if (form.dataset.submitting === 'true') return;
            form.dataset.submitting = 'true';

            const formData = new FormData(form);
            const priceSource = formData.get('price_source');

            let price;
            if (priceSource === 'user_input') {
                price = parseFloat(formData.get('price'));
                const minAmount = parseFloat(button.dataset.minAmount || 0);
                if (!price || price < minAmount) {
                    alert('Please enter a valid price (minimum: ' + minAmount + ')');
                    form.dataset.submitting = 'false';
                    return;
                }
            } else {
                price = parseFloat(formData.get('price'));
                if (!price || price <= 0) {
                    alert('Invalid price');
                    form.dataset.submitting = 'false';
                    return;
                }
            }

            const nonceFieldName = 'sitsel_nonce_' + buttonId;
            const body = new URLSearchParams({
                action: 'sitsel_create_checkout',
                nonce: formData.get(nonceFieldName),
                name: formData.get('name'),
                email: formData.get('email'),
                page: formData.get('page'),
                currency: formData.get('currency'),
                price: price,
                button_id: buttonId
            });

            fetch(sitselCheckout.ajaxUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: body
            })
            .then(function (response) { return response.json(); })
            .then(function (data) {
                form.dataset.submitting = 'false';
                if (data.success && data.data && data.data.url) {
                    window.location.href = data.data.url;
                } else {
                    alert('Stripe Error: ' + (data.data || JSON.stringify(data)));
                }
            })
            .catch(function (err) {
                form.dataset.submitting = 'false';
                console.error('Checkout Error:', err);
                alert('An error occurred. Please try again.');
            });
        });
    }

    // Init on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initializeCheckout);
    } else {
        initializeCheckout();
    }

    // Re-init for Elementor editor
    if (window.elementorFrontend && window.elementorFrontend.hooks) {
        window.elementorFrontend.hooks.addAction(
            'frontend/element_ready/sitsel_stripe_checkout',
            function () { initializeCheckout(); }
        );
    }

})();