class Cart {
    constructor() {
        this.items = [];
        this.loadFromStorage();
        this.updateCartCounter();
    }

    init() {
        this.updateCartCounter();
        this.setupEventListeners();
        // Solo cargar contenido si el sidebar existe
        if (document.getElementById('cart-sidebar')) {
            this.loadCartContent();
        }
    }

    loadFromStorage() {
        try {
            this.items = JSON.parse(localStorage.getItem('cart')) || [];
        } catch (error) {
            console.error('Error al cargar carrito:', error);
            this.items = [];
        }
    }

    saveToStorage() {
        try {
            localStorage.setItem('cart', JSON.stringify(this.items));
            this.updateCartCounter();
        } catch (error) {
            console.error('Error al guardar carrito:', error);
        }
    }

    addItem(productId, name, brand = 'DIAMOND', image = 'default.png', quantity = 1, colorInfo = null, price = 0) {
        // Convertir productId a string para consistencia
        productId = String(productId);

        // Crear un identificador único que incluya el color si existe
        let uniqueId = productId;
        let displayName = name;

        if (colorInfo && colorInfo.id) {
            uniqueId = `${productId}_${colorInfo.id}`;
            displayName = `${name} - ${colorInfo.nombre}`;
        }

        const existingItem = this.items.find(item => item.uniqueId === uniqueId);

        if (existingItem) {
            existingItem.quantity += quantity;
        } else {
            this.items.push({
                id: productId,
                uniqueId: uniqueId,
                name: displayName,
                originalName: name,
                brand: brand,
                image: image,
                quantity: quantity,
                price: price, // ✅ Agregar precio
                colorInfo: colorInfo
            });
        }

        this.saveToStorage();
        this.loadCartContent();
        this.showAddedMessage(displayName, brand, image);
    }

    removeItem(uniqueId) {
        this.items = this.items.filter(item => item.uniqueId !== uniqueId);
        this.saveToStorage();
        this.loadCartContent();
    }

    updateQuantity(uniqueId, newQuantity) {
        const item = this.items.find(item => item.uniqueId === uniqueId);
        if (item) {
            if (newQuantity <= 0) {
                this.removeItem(uniqueId);
            } else {
                item.quantity = newQuantity;
                this.saveToStorage();
                this.loadCartContent();
            }
        }
    }

    calculateTotal() {
        return this.items.reduce((total, item) => {
            return total + ((item.price || 0) * item.quantity);
        }, 0);
    }

    updateCartTotal() {
        const total = this.calculateTotal();
        const totalElement = document.getElementById('cart-total');

        if (totalElement) {
            if (total > 0) {
                totalElement.innerHTML = `PRECIO TOTAL: $${this.formatPrice(total)}`;
                totalElement.style.display = 'block';
            } else {
                totalElement.innerHTML = 'PRECIO TOTAL: Por cotización';
                totalElement.style.display = 'block';
            }
        }
    }

    formatPrice(price) {
        return new Intl.NumberFormat('es-MX', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        }).format(price);
    }

    getTotalItems() {
        return this.items.reduce((total, item) => total + item.quantity, 0);
    }

    updateCartCounter() {
        const cartCounter = document.querySelector('.nav-span');
        if (cartCounter) {
            cartCounter.textContent = this.getTotalItems();
        }
    }

    setupEventListeners() {
        // Event listener para abrir carrito
        const cartIcon = document.querySelector('.nav-a[href*="carrito"]');
        if (cartIcon) {
            cartIcon.addEventListener('click', (e) => {
                e.preventDefault();
                this.openSidebar();
            });
        }

        // Event listeners para cerrar carrito
        const closeBtn = document.getElementById('close-cart');
        const overlay = document.getElementById('cart-overlay');

        if (closeBtn) {
            closeBtn.addEventListener('click', () => this.closeSidebar());
        }

        if (overlay) {
            overlay.addEventListener('click', () => this.closeSidebar());
        }

        // Cerrar con Escape
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.closeSidebar();
            }
        });
    }

    openSidebar() {
        const sidebar = document.getElementById('cart-sidebar');
        const overlay = document.getElementById('cart-overlay');

        if (sidebar && overlay) {
            sidebar.classList.add('open');
            overlay.classList.add('open');
            document.body.style.overflow = 'hidden';
            this.loadCartContent();
        }
    }

    closeSidebar() {
        const sidebar = document.getElementById('cart-sidebar');
        const overlay = document.getElementById('cart-overlay');

        if (sidebar && overlay) {
            sidebar.classList.remove('open');
            overlay.classList.remove('open');
            document.body.style.overflow = '';
        }
    }

    loadCartContent() {
        const cartBody = document.querySelector('.cart-body');
        if (!cartBody) return;

        if (this.items.length === 0) {
            cartBody.innerHTML = `
                <div class="empty-cart">
                    <i class="fa-solid fa-cart-shopping" style="font-size: 3rem; color: #ccc; margin-bottom: 1rem;"></i>
                    <p>Tu carrito está vacío</p>
                    <a href="productos.php" class="btn-cart">Ver productos</a>
                </div>
            `;
            this.updateCartTotal();
            return;
        }

        let cartHTML = '';
        this.items.forEach(item => {
            cartHTML += this.generateCartItemHTML(item);
        });

        cartBody.innerHTML = cartHTML;
        this.updateCartTotal(); // ✅ Actualizar total

        // Esperar un poco antes de configurar los listeners
        setTimeout(() => {
            this.setupCartItemListeners();
        }, 100);
    }

    generateCartItemHTML(item) {
        const imageSrc = item.image && item.image !== 'default.png' ?
            `sistema/img/productos/${item.image}` :
            'sistema/img/productos/default.png';

        const itemPrice = item.price || 0;
        const itemTotal = itemPrice * item.quantity;

        return `
            <div class="cart-div" data-product-id="${item.uniqueId}">
                <div class="row align-items-center">
                    <div class="col-6">
                        <img src="${imageSrc}" alt="${item.name}" class="cart-img" 
                             onerror="this.src='sistema/img/productos/default.png'">
                    </div>
                    <div class="col-6">
                        <div class="cart-div2">
                            <p class="cart-product-name">${item.name}</p>
                            <p class="cart-product-brand">${item.brand}</p>
                            <p class="cart-product-total" style="font-size: 0.8rem;">Total: $${this.formatPrice(itemTotal)}</p>
                            <div class="cart-cantidad">
                                <button type="button" class="cart-minus-btn" data-product-id="${item.uniqueId}">-</button>
                                <input type="number" value="${item.quantity}" class="cart-input" 
                                       data-product-id="${item.uniqueId}" min="1" readonly>
                                <button type="button" class="cart-plus-btn" data-product-id="${item.uniqueId}">+</button>
                            </div>
                        </div>
                        <button class="cart-remove-btn" data-product-id="${item.uniqueId}">×</button>
                    </div>
                </div>
            </div>
        `;
    }

    setupCartItemListeners() {
        // Limpiar listeners anteriores
        this.removeExistingListeners();

        // Botones de restar cantidad
        const minusButtons = document.querySelectorAll('.cart-minus-btn');
        minusButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                const uniqueId = e.target.getAttribute('data-product-id');
                const input = document.querySelector(`input.cart-input[data-product-id="${uniqueId}"]`);
                const currentQuantity = parseInt(input.value);
                this.updateQuantity(uniqueId, currentQuantity - 1);
            });
        });

        // Botones de sumar cantidad
        const plusButtons = document.querySelectorAll('.cart-plus-btn');
        plusButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                const uniqueId = e.target.getAttribute('data-product-id');
                const input = document.querySelector(`input.cart-input[data-product-id="${uniqueId}"]`);
                const currentQuantity = parseInt(input.value);
                this.updateQuantity(uniqueId, currentQuantity + 1);
            });
        });

        // Botones de eliminar
        const removeButtons = document.querySelectorAll('.cart-remove-btn');
        removeButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                const uniqueId = e.target.getAttribute('data-product-id');
                this.removeItem(uniqueId);
            });
        });
    }

    removeExistingListeners() {
        // Clonar y reemplazar elementos para eliminar listeners anteriores
        const oldButtons = document.querySelectorAll('.cart-minus-btn, .cart-plus-btn, .cart-remove-btn');
        oldButtons.forEach(oldButton => {
            const newButton = oldButton.cloneNode(true);
            oldButton.parentNode.replaceChild(newButton, oldButton);
        });
    }

    showAddedMessage(productName, productBrand = 'DIAMOND', productImage = 'default.png') {
        // Remover modal anterior si existe
        const existingModal = document.querySelector('.cart-added-modal');
        if (existingModal) {
            existingModal.remove();
        }

        // Crear modal de confirmación
        const modal = document.createElement('div');
        modal.className = 'cart-added-modal';

        // Determinar la ruta de la imagen
        const imageSrc = productImage && productImage !== 'default.png' ?
            `sistema/img/productos/${productImage}` :
            'sistema/img/productos/default.png';

        modal.innerHTML = `
        <div class="cart-added-modal-header">
            <i class="fa-solid fa-check"></i>
            <span>Agregado al carrito</span>
            <button class="cart-added-modal-close">&times;</button>
        </div>
        <div class="cart-added-modal-body">
            <img src="${imageSrc}" alt="${productName}" class="cart-added-modal-image"
                 onerror="this.src='sistema/img/productos/default.png'">
            <div class="cart-added-modal-info">
                <p class="cart-added-modal-name">${productName}</p>
                <p class="cart-added-modal-brand">${productBrand}</p>
            </div>
        </div>
    `;

        document.body.appendChild(modal);

        // Configurar botón de cerrar
        const closeBtn = modal.querySelector('.cart-added-modal-close');
        closeBtn.addEventListener('click', () => {
            hideModal(modal);
        });

        // Mostrar modal
        setTimeout(() => {
            modal.classList.add('show');
        }, 100);

        // Ocultar modal después de 4 segundos
        setTimeout(() => {
            hideModal(modal);
        }, 4000);

        function hideModal(modalElement) {
            modalElement.classList.remove('show');
            setTimeout(() => {
                if (modalElement.parentNode) {
                    modalElement.parentNode.removeChild(modalElement);
                }
            }, 400);
        }
    }
}

// Inicializar carrito cuando se carga el DOM
let cart;
document.addEventListener('DOMContentLoaded', function () {
    cart = new Cart();
    cart.init();

    // Debug temporal para verificar que se carga correctamente
    console.log('Carrito inicializado con items:', cart.items);
});