
document.addEventListener("DOMContentLoaded", function () {
    function getPriceNumber(text) {
        return parseFloat(text.replace(/[^\d]/g, '')) || 0;
    }

    function applyGiftDiscount() {
        const productBlocks = document.querySelectorAll('.js-store-product');
        let allUnits = [];

        productBlocks.forEach(block => {
            const priceEl = block.querySelector('.js-store-prod-price');
            const quantityEl = block.querySelector('.js-store-prod-quantity');

            if (!priceEl || !quantityEl) return;

            const totalText = priceEl.textContent.trim();
            const totalPrice = getPriceNumber(totalText);
            const qty = parseInt(quantityEl.textContent.trim());

            if (qty > 0 && totalPrice > 0) {
                const unitPrice = totalPrice / qty;
                for (let i = 0; i < qty; i++) {
                    allUnits.push({
                        block,
                        unitPrice,
                        totalPrice,
                        qty,
                        priceEl
                    });
                }
            }
        });

        if (allUnits.length < 3) return;

        // Сортируем по цене
        allUnits.sort((a, b) => a.unitPrice - b.unitPrice);
        const freeUnit = allUnits[0];

        // Пересчитываем общую сумму
        const newTotal = allUnits.reduce((sum, item) => sum + item.unitPrice, 0) - freeUnit.unitPrice;

        // Обновим отображение только в блоке с подарком
        const block = freeUnit.block;
        const newBlockTotal = freeUnit.totalPrice - freeUnit.unitPrice;
        if (freeUnit.qty > 1) {
            freeUnit.priceEl.innerHTML = `${freeUnit.totalPrice.toFixed(0)} р. ${newBlockTotal.toFixed(0)} р.`;
        } else {
            freeUnit.priceEl.innerHTML = `0 р.`;
        }

        // Обновим сумму заказа
        const sumEls = document.querySelectorAll('strong');
        sumEls.forEach(el => {
            if (el.textContent.includes('р')) {
                el.textContent = `Сумма: ${newTotal.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, " ")} р.`;
            }
        });
    }

    // Задержка запуска и реакция на клики
    setTimeout(applyGiftDiscount, 1000);

    document.body.addEventListener('click', function (e) {
        if (
            e.target.closest('.js-store-prod-plus') ||
            e.target.closest('.js-store-prod-minus') ||
            e.target.closest('.js-store-btn')
        ) {
            setTimeout(applyGiftDiscount, 700);
        }
    });
});

