(function(){
    var formatMoney = Bridge.formatMoney;

    function recalcPrice(card) {
        var base = parseFloat(card.dataset.basePrice) || 0;
        var variantPrice = 0, sizePrice = 0;
        var hasVariant = false, hasSize = false;

        var vActive = card.querySelector('[data-group="variant"] .pc-pill.active');
        if (vActive) { variantPrice = parseFloat(vActive.dataset.price) || 0; hasVariant = true; }

        var sActive = card.querySelector('[data-group="size"] .pc-pill.active');
        if (sActive) { sizePrice = parseFloat(sActive.dataset.price) || 0; hasSize = true; }

        var qtyEl = card.querySelector('.pc-qty-val');
        var qty = parseInt(qtyEl?.textContent) || 1;

        // Prices are absolute. Size price = final price for that variant+size combo.
        var unitPrice;
        if (hasSize) {
            unitPrice = sizePrice;
        } else if (hasVariant) {
            unitPrice = variantPrice;
        } else {
            unitPrice = base;
        }
        if (unitPrice <= 0) unitPrice = base;
        var total = unitPrice * qty;

        var priceEl = card.querySelector('.pc-info-price');
        if (priceEl) {
            priceEl.dataset.unitPrice = unitPrice;
            priceEl.textContent = formatMoney(total);
            priceEl.style.transition = 'none';
            priceEl.style.transform = 'scale(1.15) translateY(-2px)';
            priceEl.style.color = '#1B4332';
            requestAnimationFrame(function() {
                requestAnimationFrame(function() {
                    priceEl.style.transition = 'transform 0.4s cubic-bezier(0.34, 1.56, 0.64, 1), color 0.5s ease';
                    priceEl.style.transform = 'scale(1) translateY(0)';
                    priceEl.style.color = '';
                });
            });
        }
    }

    // Rebuild size pills when variant changes
    function rebuildSizePills(card, variantId) {
        var sizesByVariant = {};
        try { sizesByVariant = JSON.parse(card.dataset.sizesByVariant || '{}'); } catch(x){}
        var sizes = sizesByVariant[variantId];
        if (!sizes || !sizes.length) return;

        var sizeContainer = card.querySelector('[data-group="size"]');
        if (!sizeContainer) return;

        var html = '';
        for (var i = 0; i < sizes.length; i++) {
            var s = sizes[i];
            html += '<button class="pc-pill' + (i === 0 ? ' active' : '') + '" data-id="' + s.id + '" data-price="' + s.price + '">' + s.label + '</button>';
        }
        sizeContainer.innerHTML = html;
    }

    // Pill click
    document.addEventListener('click', function(e) {
        var pill = e.target.closest('.pc-pill');
        if (!pill) return;

        var pills = pill.parentElement;
        pills.querySelectorAll('.pc-pill').forEach(function(p){ p.classList.remove('active'); });
        pill.classList.add('active');

        var card = pill.closest('.product-card');
        if (!card) return;

        var group = pills.dataset.group;
        var id = pill.dataset.id;

        // If variant changed, rebuild size pills and swap image
        if (group === 'variant') {
            rebuildSizePills(card, id);

            // Image swap
            var img = card.querySelector('.pc-main-img');
            if (img) {
                var imageMap = null;
                try { imageMap = JSON.parse(card.dataset.variantImages); } catch(x){}
                if (imageMap && imageMap[id]) {
                    img.style.opacity = '0';
                    setTimeout(function(){
                        img.src = imageMap[id];
                        img.style.opacity = '1';
                    }, 150);
                }
            }
        }

        recalcPrice(card);
    });

    // Quantity buttons
    document.addEventListener('click', function(e) {
        var btn = e.target.closest('.pc-qty-btn');
        if (!btn) return;
        var row = btn.closest('.pc-qty-row');
        var val = row.querySelector('.pc-qty-val');
        var n = parseInt(val.textContent) || 1;
        if (btn.dataset.dir === 'plus') n++;
        if (btn.dataset.dir === 'minus' && n > 1) n--;
        var unit = val.dataset.unit || '';
        if (unit) {
            val.innerHTML = n + ' <small class="pc-qty-unit">' + unit + '</small>';
        } else {
            val.textContent = n;
        }
        var card = btn.closest('.product-card');
        if (card) recalcPrice(card);
    });

    // Add to cart handler
    document.addEventListener('click', function(e) {
        var btn = e.target.closest('[data-action="add-cart"]');
        if (!btn) return;
        e.preventDefault();

        var card = btn.closest('.product-card');
        if (!card) return;

        var productId = parseInt(card.dataset.productId || btn.dataset.id) || 0;
        var productName = card.querySelector('.pc-info-name')?.textContent || '';
        var img = card.querySelector('.pc-main-img')?.src || '';
        
        var variantName = '', variantId = 0;
        var vActive = card.querySelector('[data-group="variant"] .pc-pill.active');
        if (vActive) { variantName = vActive.textContent.trim(); variantId = parseInt(vActive.dataset.id) || 0; }

        var sizeLabel = '', sizeId = 0;
        var sActive = card.querySelector('[data-group="size"] .pc-pill.active');
        if (sActive) { sizeLabel = sActive.textContent.trim(); sizeId = parseInt(sActive.dataset.id) || 0; }

        var priceEl = card.querySelector('.pc-info-price');
        var qtyEl = card.querySelector('.pc-qty-val');
        var qty = parseInt(qtyEl?.textContent) || 1;
        var unitPrice = parseFloat(priceEl?.dataset.unitPrice) || parseFloat(priceEl?.textContent?.replace(/[^0-9.]/g, '')) || 0;

        var cartVariantId = productId * 1000 + variantId;

        Cart.add({
            variantId: cartVariantId,
            sizeId: sizeId,
            productName: productName,
            qualityName: variantName,
            typeName: '',
            sizeLabel: sizeLabel,
            unitPrice: unitPrice,
            quantity: qty,
            image: img,
            productId: productId
        });

        var origText = btn.innerHTML;
        btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> ADDED!';
        btn.style.borderColor = '#2D6A4F';
        btn.style.color = '#2D6A4F';
        btn.style.background = 'rgba(45,106,79,0.06)';
        setTimeout(function() {
            btn.innerHTML = origText;
            btn.style.borderColor = '';
            btn.style.color = '';
            btn.style.background = '';
        }, 1500);
    });

    // Quick buy handler
    document.addEventListener('click', function(e) {
        var btn = e.target.closest('[data-action="buy-now"]');
        if (!btn) return;
        e.preventDefault();
        e.stopPropagation();

        var card = btn.closest('.product-card');
        if (!card) return;

        var productId = parseInt(card.dataset.productId || btn.dataset.id) || 0;
        var productName = card.querySelector('.pc-info-name')?.textContent || '';
        var img = card.querySelector('.pc-main-img')?.src || '';
        
        var variantName = '', variantId = 0;
        var vActive = card.querySelector('[data-group="variant"] .pc-pill.active');
        if (vActive) { variantName = vActive.textContent.trim(); variantId = parseInt(vActive.dataset.id) || 0; }

        var sizeLabel = '', sizeId = 0;
        var sActive = card.querySelector('[data-group="size"] .pc-pill.active');
        if (sActive) { sizeLabel = sActive.textContent.trim(); sizeId = parseInt(sActive.dataset.id) || 0; }

        var priceEl = card.querySelector('.pc-info-price');
        var qtyEl = card.querySelector('.pc-qty-val');
        var qty = parseInt(qtyEl?.textContent) || 1;
        var unitPrice = parseFloat(priceEl?.dataset.unitPrice) || parseFloat(priceEl?.textContent?.replace(/[^0-9.]/g, '')) || 0;
        var cartVariantId = productId * 1000 + variantId;

        var items = Cart.getItems();
        var found = false;
        for (var i = 0; i < items.length; i++) {
            if (items[i].variantId === cartVariantId && items[i].sizeId === sizeId) {
                items[i].quantity += qty;
                found = true;
                break;
            }
        }
        if (!found) {
            items.push({
                variantId: cartVariantId, sizeId: sizeId, productId: productId,
                productName: productName, qualityName: variantName, typeName: '',
                sizeLabel: sizeLabel, unitPrice: unitPrice, quantity: qty, image: img
            });
        }
        localStorage.setItem('cart', JSON.stringify(items));

        Cart.closeDrawer();
        
        if (typeof Router !== 'undefined') {
            Router.navigate('checkout');
        } else {
            window.location.href = '#checkout';
        }
    });
})();
