/**
 * Checkout Logic
 */

document.addEventListener('DOMContentLoaded', () => {
    const cartItemsContainer = document.getElementById('cartItems');
    const subtotalEl = document.getElementById('subtotal');
    const totalAmountEl = document.getElementById('totalAmount');
    const btnPlaceOrder = document.getElementById('btnPlaceOrder');

    const checkoutMobile = document.getElementById('checkoutMobile');
    const checkoutAddress = document.getElementById('checkoutAddress');
    const checkoutNotes = document.getElementById('checkoutNotes');

    let cart = JSON.parse(localStorage.getItem('anj_cart') || '[]');

    // Auth Check
    const user = Auth.getCurrentUser();
    if (!user) {
        // Save current location and redirect to login
        localStorage.setItem('anj_login_redirect', 'checkout.html');
        window.location.href = 'login.html';
        return;
    }

    // Pre-fill user data
    checkoutMobile.value = user.mobile || '';
    checkoutAddress.value = user.address || '';

    renderCart();

    function renderCart() {
        if (!cart.length) {
            cartItemsContainer.innerHTML = `
                <div class="py-10 text-center">
                    <p class="text-slate-400">Your cart is empty.</p>
                    <a href="products.html" class="inline-block mt-4 text-primary font-bold">Browse Products</a>
                </div>
            `;
            updateSummary(0);
            btnPlaceOrder.disabled = true;
            btnPlaceOrder.classList.add('opacity-50', 'cursor-not-allowed');
            return;
        }

        let total = 0;
        cartItemsContainer.innerHTML = cart.map((item, index) => {
            total += item.price * item.quantity;
            return `
                <div class="flex items-center gap-4 py-4">
                    <div class="w-16 h-16 bg-slate-100 rounded-lg overflow-hidden shrink-0">
                        <img src="${item.image || 'https://images.unsplash.com/photo-1586769852044-692d6e3522b0?auto=format&fit=crop&q=80&w=100'}" 
                             class="w-full h-full object-cover">
                    </div>
                    <div class="flex-1">
                        <h3 class="font-bold text-slate-900 leading-tight">${item.name}</h3>
                        <p class="text-xs text-slate-400 uppercase tracking-tighter">${item.type}</p>
                    </div>
                    <div class="flex items-center gap-2">
                        <button onclick="updateQty(${index}, -1)" class="w-8 h-8 flex items-center justify-center border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors">
                            <i class="fas fa-minus text-[10px]"></i>
                        </button>
                        <span class="w-6 text-center font-bold text-sm">${item.quantity}</span>
                        <button onclick="updateQty(${index}, 1)" class="w-8 h-8 flex items-center justify-center border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors">
                            <i class="fas fa-plus text-[10px]"></i>
                        </button>
                    </div>
                    <div class="text-right min-w-[80px]">
                        <p class="font-bold text-slate-900">₹${(item.price * item.quantity).toLocaleString()}</p>
                        <button onclick="removeItem(${index})" class="text-[10px] text-red-500 font-bold hover:underline">Remove</button>
                    </div>
                </div>
            `;
        }).join('');

        updateSummary(total);
    }

    function updateSummary(total) {
        subtotalEl.innerText = `₹${total.toLocaleString()}`;
        totalAmountEl.innerText = `₹${total.toLocaleString()}`;
    }

    window.updateQty = (index, delta) => {
        cart[index].quantity += delta;
        if (cart[index].quantity < 1) {
            removeItem(index);
        } else {
            saveCart();
            renderCart();
        }
    };

    window.removeItem = (index) => {
        cart.splice(index, 1);
        saveCart();
        renderCart();
    };

    function saveCart() {
        localStorage.setItem('anj_cart', JSON.stringify(cart));
    }

    btnPlaceOrder.addEventListener('click', async () => {
        const mobile = checkoutMobile.value.trim();
        const address = checkoutAddress.value.trim();
        const notes = checkoutNotes.value.trim();

        if (mobile.length !== 10) {
            alert('Please enter a valid 10-digit mobile number');
            return;
        }

        // Only require address if there's a physical product in cart
        const hasPhysical = cart.some(item => item.type === 'physical');
        if (hasPhysical && !address) {
            alert('Address is required for physical products');
            return;
        }

        try {
            btnPlaceOrder.disabled = true;
            btnPlaceOrder.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Placing Order...';

            const payload = {
                items: cart.map(i => ({ product_id: i.product_id, quantity: i.quantity })),
                shipping_address: address,
                contact_mobile: mobile,
                notes: notes
            };

            const result = await API.Orders.place(payload);

            if (result.success) {
                // Clear cart
                cart = [];
                saveCart();

                // Redirect to success or dashboard
                alert('Order placed successfully! We will contact you soon for payment.');
                window.location.href = 'dashboard.html';
            } else {
                throw new Error(result.message);
            }

        } catch (err) {
            console.error(err);
            alert('Failed to place order: ' + err.message);
            btnPlaceOrder.disabled = false;
            btnPlaceOrder.innerHTML = 'Place Order <i class="fas fa-chevron-right"></i>';
        }
    });
});
