document.addEventListener('DOMContentLoaded', () => {
    const productItems = document.querySelectorAll('.product-item');
    const productSubtotal = document.querySelector('.product-subtotal');
    const addToCartBtn = document.querySelector('.custom-add-to-cart');

    function calculateSubtotal() {
        let total = 0;

        for (let i = 0; i < productItems.length; i++) {
            const productItem = productItems[i];
            const inputsQuantity = productItem.querySelectorAll('input');

            if (inputsQuantity && inputsQuantity.length > 0) {
                for (let j = 0; j < inputsQuantity.length; j++) {
                    const inputQuantity = inputsQuantity[j];
                    
                    if (inputQuantity.value >= 1) {
                        total += Number(inputQuantity.dataset.price) * Number(inputQuantity.value);
                    }
                }
            }

        }
        productSubtotal.textContent = new Intl.NumberFormat('pt-BR', { maximumFractionDigits: 2, minimumFractionDigits: 2 }).format(total);
    }

    for (let i = 0; i < productItems.length; i++) {
        const productItem = productItems[i];
        const inputsQuantity = productItem.querySelectorAll('input');
        
        if (inputsQuantity && inputsQuantity.length > 0) {
            for (let j = 0; j < inputsQuantity.length; j++) {
                const inputQuantity = inputsQuantity[j];
                const lessBtn = inputQuantity.closest('div').querySelector('.less');
                const plusBtn = inputQuantity.closest('div').querySelector('.plus');
                
                if(lessBtn){
                    lessBtn.addEventListener('click', (e) => {
                        e.preventDefault();
                        if (inputQuantity.value >= 1) {
                            inputQuantity.value = Number(inputQuantity.value) - 1;
                            inputQuantity.setAttribute('value', inputQuantity.value);
                            calculateSubtotal();
                        }
                    });
                    plusBtn.addEventListener('click', (e) => {
                        e.preventDefault();
                        if (Number(inputQuantity.dataset.stock) > Number(inputQuantity.value)) {
                            inputQuantity.value = Number(inputQuantity.value) + 1;
                            inputQuantity.setAttribute('value', inputQuantity.value);
                            calculateSubtotal();
                        } else {
                            TOAST.error('Quantidade em estoque não disponível');
                        }
                    });
                }
                
                inputQuantity.addEventListener('input', (e) => {
                    if (Number(e.target.value) > Number(inputQuantity.dataset.stock)) {
                        e.target.value = Number(inputQuantity.dataset.stock);
                        e.target.setAttribute('value', Number(inputQuantity.dataset.stock));
                    }
                    calculateSubtotal();
                });
            }
        }
    }

    if (addToCartBtn) {
        addToCartBtn.addEventListener('click', async (e) => {
            e.preventDefault();
        
            const productItems = document.querySelectorAll('.product-item');
            const additionalItem = document.querySelector('[data-is-additional]');
            const miniCartCount = document.querySelector('.header-user-cart-count');
            const miniCartTotals = document.querySelector('.header-user-cart-totals .totals');
            const oldContent = addToCartBtn.innerHTML;
        
            let temProdutoValido = false;
        
            addToCartBtn.innerHTML = `<span>Adicionando...</span>`;
            addToCartBtn.setAttribute('disabled', 'true');
        
            for (let i = 0; i < productItems.length; i++) {
                const productItem = productItems[i];
        
                const inputsQuantity = productItem.querySelectorAll('input[name="qnt"]');
                
                const validInputs = Array.from(inputsQuantity).filter(input => Number(input.value) > 0);
        
                if (validInputs.length === 0) {
                    continue;
                }
        
                temProdutoValido = true;
                let fetchCalls = validInputs.map((input, j) => {
                    return new Promise((resolve) => {
                        setTimeout(async () => {
                            try {
                                await fetch('/cart/add', {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json',
                                        'Accept': 'application/json'
                                    },
                                    redirect: 'follow',
                                    body: JSON.stringify({
                                        id: input.dataset.id,
                                        quantity: Number(input.value),
                                        additionalVariantId: additionalItem && Number(additionalItem.value) > 0 ? additionalItem.dataset.id : [],
                                        distributionCenter: input.dataset.dc
                                    })
                                });
                            } catch (err) {
                                console.error(err.message);
                            }
                            resolve();
                        }, j * 200);
                    });
                });
        
                await Promise.all(fetchCalls);
        
                await fetch('/checkout/current-cart')
                    .then((response) => response.json())
                    .then((response) => {
                        let itemsTotal = 0;
                        response.sales.forEach(sale => {
                            sale.items.forEach(item => {
                                itemsTotal += item.quantity;
                            });
                        });
                        miniCartCount.textContent = itemsTotal;
                        miniCartTotals.textContent = new Intl.NumberFormat('pt-BR', { 
                            style: 'currency', 
                            currency: 'BRL' 
                        }).format(response.totalWithDiscount);
                    });
        
                TOAST.success("Produto adicionado ao carrinho");
            }
        
            if (!temProdutoValido) {
                TOAST.error("Selecione a quantidade de pelo menos 1 item");
            }
    
            addToCartBtn.innerHTML = oldContent;
            addToCartBtn.removeAttribute('disabled');
        });
    }

    const tabButtons = document.querySelectorAll('.product-tab-item');
    const tabContents = document.querySelectorAll('.product-tab-content');

    for (let i = 0; i < tabButtons.length; i++) {
        const tabBtn = tabButtons[i];
        const dest = tabBtn.dataset.tab;

        tabBtn.addEventListener('click', (e) => {
            e.preventDefault();

            for (let j = 0; j < tabContents.length; j++) {
                const content = tabContents[j];

                content.classList.remove('active');
            }

            for (let k = 0; k < tabButtons.length; k++) {
                const btn = tabButtons[k];
                
                btn.classList.remove('active');
            }

            tabBtn.classList.add('active');
            document.querySelector(`[data-tab-content="${dest}"]`).classList.add('active');
        });
    }

    tabButtons[0].click();

    function zoom(event) {
        if (event.type === 'mousemove') {
            var t = event.currentTarget;
            var offsetX, offsetY;

            offsetX = event.offsetX;
            offsetY = event.offsetY;

            var x = (offsetX / t.offsetWidth) * 100;
            var y = (offsetY / t.offsetHeight) * 100;

            t.style.backgroundSize = '300%';
            t.style.backgroundPosition = x + '% ' + y + '%';
        }
    }

    const imagesZoom = document.querySelectorAll('[data-zoom]');

    if (window.innerWidth > 1024) {
        if (imagesZoom.length > 0) {
            imagesZoom.forEach((image) => {
                image.addEventListener('mousemove', zoom);
            });
        }
    }

    const reviewBtn = document.querySelector('.review-product-link');
    const reviewTabItem = document.querySelector('[data-tab="tab-3"]');

    reviewBtn.addEventListener('click', (e) => {
        e.preventDefault();

        reviewTabItem.click();

        window.scrollTo({
            top: reviewTabItem.getBoundingClientRect().top - 100,
            behavior: 'smooth'
        });
    });
});