class CartManager {
    constructor(app) {
        this.app = app;
        this.cart = this.loadCart();
        this.init();
    }

    init() {
        this.updateCartIcon();
        this.setupEventListeners();
    }

    setupEventListeners() {
        document.addEventListener('click', (e) => {
            const cartPanel = document.getElementById('cart-panel');

            // Show/hide cart
            if (e.target.closest('#cart-btn')) {
                e.preventDefault();
                this.toggleCart();
            } else if (cartPanel && cartPanel.classList.contains('active') && !e.target.closest('#cart-panel')) {
                // Hide if click is outside
                this.hideCart();
            }

            // Actions within the cart
            if (e.target.closest('#cart-panel')) {
                // Remove item
                if (e.target.closest('.cart-item-remove')) {
                    const productId = e.target.closest('[data-product-id]').dataset.productId;
                    this.removeFromCart(productId);
                }
                // Checkout
                if (e.target.closest('#checkout-btn')) {
                    this.handleCheckout();
                }
            }
        });

        document.addEventListener('change', (e) => {
            // Update quantity
            if (e.target.classList.contains('cart-item-quantity')) {
                const productId = e.target.closest('[data-product-id]').dataset.productId;
                const newQuantity = parseInt(e.target.value, 10);
                this.updateQuantity(productId, newQuantity);
            }
        });
    }

    loadCart() {
        const cartData = localStorage.getItem('mabangaCart');
        return cartData ? JSON.parse(cartData) : {};
    }

    saveCart() {
        localStorage.setItem('mabangaCart', JSON.stringify(this.cart));
        this.updateCartIcon();
        this.renderCart();
    }

    addToCart(product, quantity = 1) {
        if (this.cart[product.id]) {
            this.cart[product.id].quantity += quantity;
        } else {
            this.cart[product.id] = {
                ...product,
                quantity: quantity
            };
        }
        this.saveCart();
        this.showCart();
        console.log('Added to cart:', product.name);
    }

    removeFromCart(productId) {
        delete this.cart[productId];
        this.saveCart();
    }

    updateQuantity(productId, quantity) {
        if (this.cart[productId]) {
            if (quantity > 0) {
                this.cart[productId].quantity = quantity;
            } else {
                delete this.cart[productId];
            }
            this.saveCart();
        }
    }

    getCartItems() {
        return Object.values(this.cart);
    }

    getTotal() {
        return this.getCartItems().reduce((total, item) => {
            return total + (item.price * item.quantity);
        }, 0);
    }

    updateCartIcon() {
        const cartBtn = document.getElementById('cart-btn');
        if (!cartBtn) return;

        const badge = cartBtn.querySelector('.notification-badge');
        const count = this.getCartItems().reduce((sum, item) => sum + item.quantity, 0);

        badge.textContent = count;
        badge.style.display = count > 0 ? 'flex' : 'none';
    }

    toggleCart() {
        const cartPanel = document.getElementById('cart-panel');
        if (cartPanel && cartPanel.classList.contains('active')) {
            this.hideCart();
        } else {
            this.showCart();
        }
    }

    showCart() {
        let cartPanel = document.getElementById('cart-panel');
        if (!cartPanel) {
            const cartTemplate = document.getElementById('cart-panel-template');
            if (cartTemplate) {
                document.body.insertAdjacentHTML('beforeend', cartTemplate.innerHTML);
                cartPanel = document.getElementById('cart-panel');
            }
        }
        this.renderCart();
        setTimeout(() => cartPanel.classList.add('active'), 10);
    }

    hideCart() {
        const cartPanel = document.getElementById('cart-panel');
        if (cartPanel) {
            cartPanel.classList.remove('active');
        }
    }

    renderCart() {
        const itemsContainer = document.getElementById('cart-items');
        const summaryContainer = document.getElementById('cart-summary');
        if (!itemsContainer || !summaryContainer) return;

        const items = this.getCartItems();

        if (items.length === 0) {
            itemsContainer.innerHTML = '<div class="empty-state p-2">Your cart is empty.</div>';
            summaryContainer.style.display = 'none';
            return;
        }

        summaryContainer.style.display = 'block';

        itemsContainer.innerHTML = items.map(item => `
            <div class="cart-item" data-product-id="${item.id}">
                <img src="${item.image || 'assets/images/default-shop.jpg'}" alt="${item.name}" class="cart-item-image">
                <div class="cart-item-details">
                    <div class="cart-item-name">${item.name}</div>
                    <div class="cart-item-price">$${parseFloat(item.price).toFixed(2)}</div>
                </div>
                <div class="cart-item-actions">
                    <input type="number" class="cart-item-quantity" value="${item.quantity}" min="1" max="99">
                    <button class="cart-item-remove">&times;</button>
                </div>
            </div>
        `).join('');

        const subtotal = this.getTotal();
        // In a real app, shipping would be calculated
        const shipping = subtotal > 0 ? 5.00 : 0;
        const total = subtotal + shipping;

        summaryContainer.innerHTML = `
            <div class="summary-item"><span>Subtotal</span><span>$${subtotal.toFixed(2)}</span></div>
            <div class="summary-item"><span>Shipping</span><span>$${shipping.toFixed(2)}</span></div>
            <div class="summary-item total"><span>Total</span><span>$${total.toFixed(2)}</span></div>
            <button id="checkout-btn" class="btn-primary mt-2">Checkout</button>
        `;
    }

    async handleCheckout() {
        if (this.getCartItems().length === 0) {
            alert("Your cart is empty.");
            return;
        }

        try {
            const response = await fetch('api/orders/create.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ items: this.getCartItems() })
            });

            const result = await response.json();
            if (result.success) {
                alert('Order placed successfully! Your order ID is ' + result.order_id);
                this.cart = {};
                this.saveCart();
                this.hideCart();
                this.app.loadPage('orders');
            } else {
                throw new Error(result.message);
            }
        } catch (error) {
            console.error('Checkout failed:', error);
            alert('Checkout failed: ' + error.message);
        }
    }
}