// Shopping Cart Manager
class CartManager {
    constructor() {
        this.items = [];
        this.loadCart();
        this.setupEventListeners();
    }

    loadCart() {
        const saved = localStorage.getItem('cart');
        if (saved) {
            this.items = JSON.parse(saved);
            this.updateBadge();
        }
    }

    saveCart() {
        localStorage.setItem('cart', JSON.stringify(this.items));
        this.updateBadge();
    }

    addItem(foodItem, quantity = 1) {
        const existingItem = this.items.find(item => item.id === foodItem.id);

        if (existingItem) {
            existingItem.quantity += quantity;
        } else {
            this.items.push({
                id: foodItem.id,
                name: foodItem.name,
                price: foodItem.price,
                image_url: foodItem.image_url,
                quantity: quantity
            });
        }

        this.saveCart();
        // this.showToast(`${foodItem.name} added to cart`, 'success');
    }

    removeItem(foodId) {
        this.items = this.items.filter(item => item.id !== foodId);
        this.saveCart();
        this.renderCart();
    }

    updateQuantity(foodId, quantity) {
        const item = this.items.find(item => item.id === foodId);
        if (item) {
            if (quantity <= 0) {
                this.removeItem(foodId);
            } else {
                item.quantity = quantity;
                this.saveCart();
                this.renderCart();
            }
        }
    }

    clearCart() {
        this.items = [];
        this.saveCart();
        this.renderCart();
        // this.showToast('Cart cleared', 'info');
    }

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

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

    updateBadge() {
        const badge = document.getElementById('cartBadge');
        const count = this.getItemCount();

        if (badge) {
            if (count > 0) {
                badge.textContent = count;
                badge.classList.remove('hidden');
            } else {
                badge.classList.add('hidden');
            }
        }
    }

    setupEventListeners() {
        // Cart button
        const cartBtn = document.getElementById('cartBtn');
        if (cartBtn) {
            cartBtn.addEventListener('click', () => this.openCart());
        }

        // Close cart
        const closeCartBtn = document.getElementById('closeCartBtn');
        if (closeCartBtn) {
            closeCartBtn.addEventListener('click', () => this.closeCart());
        }

        // Clear cart
        const clearCartBtn = document.getElementById('clearCartBtn');
        if (clearCartBtn) {
            clearCartBtn.addEventListener('click', () => {
                if (confirm('Clear all items from cart?')) {
                    this.clearCart();
                }
            });
        }

        // Checkout
        const checkoutBtn = document.getElementById('checkoutBtn');
        if (checkoutBtn) {
            checkoutBtn.addEventListener('click', () => this.openCheckout());
        }

        // Close modal on background click
        const cartModal = document.getElementById('cartModal');
        if (cartModal) {
            cartModal.addEventListener('click', (e) => {
                if (e.target === cartModal) {
                    this.closeCart();
                }
            });
        }
    }

    openCart() {
        this.renderCart();
        const modal = document.getElementById('cartModal');
        if (modal) {
            modal.classList.add('active');
        }
    }

    closeCart() {
        const modal = document.getElementById('cartModal');
        if (modal) {
            modal.classList.remove('active');
        }
    }

    renderCart() {
        const container = document.getElementById('cartItems');
        if (!container) return;

        if (this.items.length === 0) {
            container.innerHTML = `
        <div class="text-center" style="padding: 2rem;">
          <div style="font-size: 4rem; margin-bottom: 1rem;">🛒</div>
          <p style="color: var(--gray-500);">Your cart is empty</p>
        </div>
      `;
            return;
        }

        const itemsHTML = this.items.map(item => `
      <div class="cart-item" style="display: flex; gap: 1rem; padding: 1rem; border-bottom: 1px solid var(--gray-200);">
        <img src="${item.image_url || '/images/placeholder.png'}" 
             alt="${item.name}" 
             style="width: 80px; height: 80px; object-fit: cover; border-radius: var(--radius-md);">
        <div style="flex: 1;">
          <h4 style="margin: 0 0 0.5rem 0;">${item.name}</h4>
          <p style="color: var(--primary-orange); font-weight: 700; margin: 0;">₹${item.price}</p>
        </div>
        <div style="display: flex; flex-direction: column; align-items: center; gap: 0.5rem;">
          <div style="display: flex; align-items: center; gap: 0.5rem;">
            <button class="btn btn-sm" onclick="cart.updateQuantity('${item.id}', ${item.quantity - 1})">-</button>
            <span style="min-width: 2rem; text-align: center; font-weight: 700;">${item.quantity}</span>
            <button class="btn btn-sm" onclick="cart.updateQuantity('${item.id}', ${item.quantity + 1})">+</button>
          </div>
          <button class="btn btn-sm btn-danger" onclick="cart.removeItem('${item.id}')">Remove</button>
        </div>
      </div>
    `).join('');

        const total = this.getTotal();

        container.innerHTML = `
      ${itemsHTML}
      <div style="padding: 1rem; background: var(--gray-50); border-radius: var(--radius-md); margin-top: 1rem;">
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span style="font-size: 1.25rem; font-weight: 700;">Total:</span>
          <span style="font-size: 1.5rem; font-weight: 700; color: var(--primary-orange);">₹${total.toFixed(2)}</span>
        </div>
      </div>
    `;
    }

    openCheckout() {
        if (this.items.length === 0) {
            this.showToast('Cart is empty', 'warning');
            return;
        }

        this.closeCart();
        this.renderCheckout();

        const modal = document.getElementById('checkoutModal');
        if (modal) {
            modal.classList.add('active');
        }
    }

    closeCheckout() {
        const modal = document.getElementById('checkoutModal');
        if (modal) {
            modal.classList.remove('active');
        }
    }

    async renderCheckout() {
        // Load saved payment details
        try {
            const response = await fetch('/api/payments/saved', {
                headers: window.auth.getAuthHeaders()
            });

            if (response.ok) {
                const data = await response.json();
                if (data.payment) {
                    this.fillPaymentForm(data.payment);
                }
            }
        } catch (error) {
            console.error('Error loading payment details:', error);
        }

        // Render order summary totals
        const subtotal = this.getTotal();
        const subtotalEl = document.getElementById('checkoutSubtotal');
        const totalEl = document.getElementById('checkoutTotal');

        if (subtotalEl) subtotalEl.textContent = `₹${subtotal.toFixed(2)}`;
        if (totalEl) totalEl.textContent = `₹${subtotal.toFixed(2)}`;

        // Setup payment method toggle
        const paymentMethod = document.getElementById('paymentMethod');
        const upiDetails = document.getElementById('upiDetails');
        const cardDetails = document.getElementById('cardDetails');

        if (paymentMethod) {
            // Remove existing listener to prevent duplicates
            const newPaymentMethod = paymentMethod.cloneNode(true);
            paymentMethod.parentNode.replaceChild(newPaymentMethod, paymentMethod);

            newPaymentMethod.addEventListener('change', (e) => {
                if (e.target.value === 'upi') {
                    upiDetails?.classList.remove('hidden');
                    cardDetails?.classList.add('hidden');
                } else if (e.target.value === 'card') {
                    upiDetails?.classList.add('hidden');
                    cardDetails?.classList.remove('hidden');
                } else {
                    upiDetails?.classList.add('hidden');
                    cardDetails?.classList.add('hidden');
                }
            });

            // Trigger initial state
            newPaymentMethod.dispatchEvent(new Event('change'));
        }

        // Setup form submission
        const placeOrderBtn = document.getElementById('placeOrderBtn');
        if (placeOrderBtn) {
            // Use onclick to overwrite any existing listeners
            placeOrderBtn.onclick = (e) => {
                e.preventDefault();
                this.placeOrder();
            };
        }

        // Setup cancel button
        const cancelBtn = document.getElementById('cancelCheckoutBtn');
        if (cancelBtn) {
            cancelBtn.onclick = () => this.closeCheckout();
        }

        const closeBtn = document.getElementById('closeCheckoutBtn');
        if (closeBtn) {
            closeBtn.onclick = () => this.closeCheckout();
        }
    }

    fillPaymentForm(payment) {
        const methodSelect = document.getElementById('paymentMethod');
        const nameInput = document.getElementById('paymentName');
        const mobileInput = document.getElementById('paymentMobile');
        const upiInput = document.getElementById('paymentUpiId');
        const cardInput = document.getElementById('paymentCardNumber');

        if (methodSelect) methodSelect.value = payment.payment_method;
        if (nameInput) nameInput.value = payment.name || '';
        if (mobileInput) mobileInput.value = payment.mobile || '';
        if (upiInput && payment.upi_id) upiInput.value = payment.upi_id;
        if (cardInput && payment.card_last4) cardInput.value = payment.card_last4;

        // Trigger change event to show/hide fields
        methodSelect?.dispatchEvent(new Event('change'));
    }

    async placeOrder() {
        const form = document.getElementById('checkoutForm');
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }

        const paymentMethod = document.getElementById('paymentMethod').value;
        const name = document.getElementById('paymentName').value;
        const mobile = document.getElementById('paymentMobile').value;
        const upiId = document.getElementById('paymentUpiId')?.value;
        const cardLast4 = document.getElementById('paymentCardNumber')?.value;

        const orderData = {
            items: this.items.map(item => ({
                food_id: item.id,
                quantity: item.quantity
            })),
            payment_method: paymentMethod,
            payment_details: {
                name,
                mobile,
                upi_id: upiId,
                card_last4: cardLast4
            }
        };

        this.showLoading(true);

        try {
            const response = await fetch('/api/orders', {
                method: 'POST',
                headers: window.auth.getAuthHeaders(),
                body: JSON.stringify(orderData)
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.error || 'Failed to place order');
            }

            // Clear cart
            this.clearCart();
            this.closeCheckout();

            // Show success message
            this.showToast('Order placed successfully!', 'success');

            // Switch to orders view
            setTimeout(() => {
                if (window.app) {
                    window.app.switchView('orders');
                }
            }, 1000);

        } catch (error) {
            console.error('Place order error:', error);
            this.showToast(error.message || 'Failed to place order', 'error');
        } finally {
            this.showLoading(false);
        }
    }

    showLoading(show) {
        const overlay = document.getElementById('loadingOverlay');
        if (overlay) {
            if (show) {
                overlay.classList.remove('hidden');
            } else {
                overlay.classList.add('hidden');
            }
        }
    }

    showToast(message, type = 'info') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;

        const container = document.getElementById('toastContainer');
        if (container) {
            container.appendChild(toast);
            setTimeout(() => toast.remove(), 3000);
        }
    }
}

// Initialize cart
const cart = new CartManager();

// Export for global use
window.cart = cart;
