document.addEventListener("DOMContentLoaded", (event) => {

    const cartForm = document.getElementById('cart-form');

    Fancybox.bind("[data-fancybox]");

    document.body.addEventListener('submit', function(e) {
        const form = e.target;
        if (form.matches('.add-to-cart-form')) {
            e.preventDefault();
            e.stopImmediatePropagation();

            addToCart(form);
        }
    });

    cartForm?.addEventListener('submit', function(e) {
        e.preventDefault();
        e.stopImmediatePropagation();

        cartCheckout(e.target);
    });

});

function cartCheckout(formElement) {

    if(!formElement) return;

    const formData = new FormData(formElement);
    const submitButton = formElement.querySelector('button[type=submit]');

    formData.forEach((value, key) => {
        console.log(`${key}: ${value}`);
    });

}

function addToCart(formElement) {
    if (!formElement) return;

    const formData = new FormData(formElement);
    const submitButton = formElement.querySelector('.add-to-cart-button');

    if (submitButton) {
        submitButton.disabled = true;
        submitButton.classList.add('is-loading');
    }

    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .then(data => {

            if (data.STATUS === 'OK') {
                showCartToast();
                reloadCartLine();
            } else {
                showCartToast("Ошибка при добавлении в корзину", 3000, 'error');
            }
        })
        .catch(error => {
            showCartToast("Сервер недоступен или произошла ошибка", 3000, 'error');
        })
        .finally(() => {
            if (submitButton) {
                submitButton.disabled = false;
                submitButton.classList.remove('is-loading');
            }
        });
}

function showCartToast(message = "Товар добавлен в корзину", timeout = 3000, type = 'success') {
    const container = document.querySelector('.cart-toast-container');
    if (!container) return;

    const toast = document.createElement('div');
    toast.className = `cart-toast ${type === 'error' ? 'cart-toast--error' : 'cart-toast--success'}`;
    toast.innerHTML = `
        <div class="cart-toast__message">${message}</div>
        <div class="cart-toast__progress"></div>
    `;

    container.appendChild(toast);

    setTimeout(() => {
        toast.classList.add('show');
    }, 10);

    setTimeout(() => {
        toast.classList.remove('show');
        toast.addEventListener('transitionend', () => toast.remove());
    }, timeout);
}

function reloadCartLine() {
    fetch('/local/ajax/cart-line.php')
        .then(res => res.text())
        .then(html => {
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            const newCart = doc.querySelector('.header__cart');

            if (newCart) {
                const currentCart = document.querySelector('.header__cart');
                currentCart.replaceWith(newCart);
            }
        })
        .catch(err => console.error('Ошибка обновления корзины:', err));
}