var Cart = (function() {
    'use strict';

    var STORAGE_KEY = 'cart';

    var formatMoney = Bridge.formatMoney;
    function getItems() {
        try {
            var data = localStorage.getItem(STORAGE_KEY);
            return data ? JSON.parse(data) : [];
        } catch (e) {
            return [];
        }
    }

    function saveItems(items) {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(items));
        updateBadge();
        dispatchUpdate();
    }

    function add(item) {
        var items = getItems();
        var existing = null;
        for (var i = 0; i < items.length; i++) {
            if (items[i].variantId === item.variantId && items[i].sizeId === item.sizeId) {
                existing = i;
                break;
            }
        }

        if (existing !== null) {
            items[existing].quantity += (item.quantity || 1);
        } else {
            items.push({
                variantId: item.variantId,
                sizeId: item.sizeId,
                productId: item.productId || 0,
                productName: item.productName || '',
                qualityName: item.qualityName || '',
                typeName: item.typeName || '',
                sizeLabel: item.sizeLabel || '',
                unitPrice: parseFloat(item.unitPrice) || 0,
                quantity: item.quantity || 1,
                image: item.image || ''
            });
        }

        saveItems(items);
        openDrawer();
    }

    function remove(variantId, sizeId) {
        var items = getItems();
        items = items.filter(function(item) {
            return !(item.variantId === variantId && item.sizeId === sizeId);
        });
        saveItems(items);
        renderDrawer();
    }

    function updateQty(variantId, sizeId, qty) {
        var items = getItems();
        for (var i = 0; i < items.length; i++) {
            if (items[i].variantId === variantId && items[i].sizeId === sizeId) {
                if (qty <= 0) {
                    items.splice(i, 1);
                } else {
                    items[i].quantity = qty;
                }
                break;
            }
        }
        saveItems(items);
        renderDrawer();
    }

    function getCount() {
        var items = getItems();
        var count = 0;
        for (var i = 0; i < items.length; i++) {
            count += items[i].quantity;
        }
        return count;
    }

    function getTotal() {
        var items = getItems();
        var total = 0;
        for (var i = 0; i < items.length; i++) {
            total += items[i].unitPrice * items[i].quantity;
        }
        return total;
    }

    function clear() {
        localStorage.removeItem(STORAGE_KEY);
        updateBadge();
        renderDrawer();
        dispatchUpdate();
    }

    function openDrawer() {
        var el = document.getElementById('cart-drawer');
        if (!el) return;
        renderDrawer();
        el.classList.add('open');
        document.body.style.overflow = 'hidden';
    }

    function closeDrawer() {
        var el = document.getElementById('cart-drawer');
        if (!el) return;
        el.classList.remove('open');
        document.body.style.overflow = '';
    }

    function renderDrawer() {
        var container = document.getElementById('cart-items');
        var totalEl = document.getElementById('cart-total');
        var emptyEl = document.getElementById('cart-empty');
        var footer = document.getElementById('cart-footer');

        if (!container) return;

        var items = getItems();

        if (items.length === 0) {
            container.innerHTML = '';
            if (emptyEl) emptyEl.style.display = 'flex';
            if (totalEl) totalEl.textContent = '$0.00';
            if (footer) footer.style.display = 'none';
            return;
        }

        if (emptyEl) emptyEl.style.display = 'none';
        if (footer) footer.style.display = 'block';

        var html = '';
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var lineTotal = formatMoney(item.unitPrice * item.quantity);

            html += '<div class="cart-item">';
            if (item.image) {
                html += '<img class="cart-item-img" src="' + escapeAttr(item.image) + '" alt="">';
            }
            html += '<div class="cart-item-info">';
            
            var nameLine = escapeHtml(item.productName);
            var variant = item.typeName || item.qualityName;
            if (variant) nameLine += ' <span class="cart-item-variant">(' + escapeHtml(variant) + ')</span>';
            html += '<div class="cart-item-name">' + nameLine + '</div>';
            
            if (item.sizeLabel) {
                html += '<div class="cart-item-meta">› Packaging: ' + escapeHtml(item.sizeLabel) + '</div>';
            }
            html += '<div class="cart-item-meta">› Qty: ' + item.quantity + ' × ' + formatMoney(item.unitPrice) + '</div>';
            
            html += '</div>';
            
            html += '<div class="cart-item-actions">';
            html += '<div class="cart-item-line-total">' + lineTotal + '</div>';
            html += '<div class="cart-qty">';
            html += '<button class="cart-qty-btn" onclick="Cart.updateQty(' + item.variantId + ',' + item.sizeId + ',' + (item.quantity - 1) + ')">−</button>';
            html += '<span class="cart-qty-val">' + item.quantity + '</span>';
            html += '<button class="cart-qty-btn" onclick="Cart.updateQty(' + item.variantId + ',' + item.sizeId + ',' + (item.quantity + 1) + ')">+</button>';
            html += '</div>';
            html += '<button class="cart-remove-btn" onclick="Cart.remove(' + item.variantId + ',' + item.sizeId + ')">Remove</button>';
            html += '</div>';
            html += '</div>';
        }

        container.innerHTML = html;
        if (totalEl) totalEl.textContent = formatMoney(getTotal());
    }

    function updateBadge() {
        var badge = document.getElementById('cart-badge');
        if (!badge) return;
        var count = getCount();
        badge.textContent = count > 0 ? count : '';
        badge.style.display = count > 0 ? 'inline-flex' : 'none';
    }

    function dispatchUpdate() {
        try {
            var event = new CustomEvent('cart-updated', { detail: { count: getCount(), total: getTotal() } });
            document.dispatchEvent(event);
        } catch (e) {}
    }

    function escapeHtml(text) {
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(text));
        return div.innerHTML;
    }

    function escapeAttr(text) {
        return text.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }

    document.addEventListener('DOMContentLoaded', function() {
        updateBadge();
    });

    return {
        add: add,
        remove: remove,
        updateQty: updateQty,
        getItems: getItems,
        getCount: getCount,
        getTotal: getTotal,
        clear: clear,
        openDrawer: openDrawer,
        closeDrawer: closeDrawer,
        renderDrawer: renderDrawer
    };
})();
