document.addEventListener("DOMContentLoaded", function () {

    // Function to initiate checkout
    function initiateCheckout() {
        // Fetch the CSRF token from the cookie
        const csrftoken = getCookie('csrftoken');

        console.log('CSRF Token:', csrftoken);

        fetch('/initiate_checkout/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrftoken // Include the CSRF token in the request headers
            },
            body: JSON.stringify({})
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                // Handle success response
                console.log("Session ID: " + data.session_id);
                // Configure Checkout with the fetched session ID
                configureCheckout(data.session_id);
            })
            .catch(error => {
                // Handle error response
                console.error('There was a problem with the fetch operation:', error);
                // You can display an error message to the user or perform other actions
            });
    }

    // Function to configure Checkout with session ID
    function configureCheckout(sessionId) {
        // Configure Checkout session with the fetched session ID
        Checkout.configure({
            session: {
                id: sessionId,
            }
        });
    }

    // Function to get CSRF token from cookie
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // Configure Checkout and modal
    Checkout.configure({
        session: {
            id: 1, // Default session ID, will be replaced with actual session ID after initiation
        }
    });


    const displayPaymentModalButton = document.querySelectorAll('.displayPaymentModal');
    const closeButton = document.querySelector('#closePaymentModalButton');
    const paymentModal = document.getElementById('paymentModal');

    // Add click event listener to each button
    displayPaymentModalButton.forEach(function (button) {
        button.addEventListener('click', function () {
            paymentModal.classList.remove('hidden');

            initiateCheckout();

            Checkout.showEmbeddedPage('#paymentContent', () => { $('#paymentModal').modal(); });
        });
    });

    closeButton.addEventListener('click', function () {
        paymentModal.classList.add('hidden');
        sessionStorage.clear();
    });

});