/**
 * Local Storage based cart manager scoped per sale slug with Delivery Option calculation
 */
let cartSlug = '';
let cartItems = [];

function initCart(slug) {
    cartSlug = slug;
    loadCart();
    renderCart();
}

function getCartStorageKey() {
    return 'cart_' + cartSlug;
}

function loadCart() {
    try {
        const stored = localStorage.getItem(getCartStorageKey());
        cartItems = stored ? JSON.parse(stored) : [];
    } catch (e) {
        cartItems = [];
    }
}

function saveCart() {
    try {
        localStorage.setItem(getCartStorageKey(), JSON.stringify(cartItems));
    } catch (e) {}
    renderCart();
}

function addToCart(saleItemId, name, price, imageUrl, maxStock) {
    const existing = cartItems.find(i => i.sale_item_id === saleItemId);
    if (existing) {
        if (existing.quantity < maxStock) {
            existing.quantity++;
        } else {
            alert('Cannot add more. Reached max available stock (' + maxStock + ').');
            return;
        }
    } else {
        cartItems.push({
            sale_item_id: saleItemId,
            name: name,
            price: price,
            image: imageUrl,
            quantity: 1,
            maxStock: maxStock
        });
    }
    saveCart();
    toggleCart(true);
}

function updateQuantity(saleItemId, delta) {
    const item = cartItems.find(i => i.sale_item_id === saleItemId);
    if (!item) return;

    item.quantity += delta;
    if (item.quantity <= 0) {
        cartItems = cartItems.filter(i => i.sale_item_id !== saleItemId);
    } else if (item.quantity > item.maxStock) {
        item.quantity = item.maxStock;
        alert('Maximum available stock is ' + item.maxStock);
    }
    saveCart();
}

function removeFromCart(saleItemId) {
    cartItems = cartItems.filter(i => i.sale_item_id !== saleItemId);
    saveCart();
}

function renderCart() {
    const cartItemsEl = document.getElementById('cartItems');
    const cartEmptyEl = document.getElementById('cartEmpty');
    const cartTotalEl = document.getElementById('cartTotal');
    const checkoutBtn = document.getElementById('checkoutBtn');
    const cartBadge = document.getElementById('cartBadge');
    const cartFab = document.getElementById('cartFab');

    if (!cartItemsEl) return;

    const totalQty = cartItems.reduce((acc, i) => acc + i.quantity, 0);
    const totalPrice = cartItems.reduce((acc, i) => acc + (i.price * i.quantity), 0);

    if (cartBadge) cartBadge.textContent = totalQty;
    if (cartFab) cartFab.style.display = totalQty > 0 ? 'block' : 'none';

    if (cartItems.length === 0) {
        if (cartEmptyEl) cartEmptyEl.style.display = 'block';
        cartItemsEl.innerHTML = '<div class="empty-state"><p class="text-sm text-muted">Your cart is empty</p></div>';
        if (cartTotalEl) cartTotalEl.textContent = 'GHS 0.00';
        if (checkoutBtn) checkoutBtn.disabled = true;
        return;
    }

    if (cartEmptyEl) cartEmptyEl.style.display = 'none';
    if (checkoutBtn) checkoutBtn.disabled = false;
    if (cartTotalEl) cartTotalEl.textContent = 'GHS ' + totalPrice.toFixed(2);

    let html = '';
    cartItems.forEach(item => {
        html += `
        <div class="cart-item">
            ${item.image ? `<img src="${item.image}" class="cart-item__image" alt="">` : `<div class="cart-item__image" style="background:var(--color-border-light)"></div>`}
            <div class="cart-item__info">
                <div class="cart-item__name">${item.name}</div>
                <div class="cart-item__price">GHS ${Number(item.price).toFixed(2)}</div>
                <div class="cart-item__quantity">
                    <button class="cart-item__qty-btn" onclick="updateQuantity('${item.sale_item_id}', -1)">-</button>
                    <span class="text-sm font-semibold">${item.quantity}</span>
                    <button class="cart-item__qty-btn" onclick="updateQuantity('${item.sale_item_id}', 1)">+</button>
                    <button class="btn btn--ghost btn--sm" style="color:var(--color-error);margin-left:auto;" onclick="removeFromCart('${item.sale_item_id}')">Remove</button>
                </div>
            </div>
        </div>
        `;
    });

    cartItemsEl.innerHTML = html;
}

function toggleCart(forceOpen = false) {
    const drawer = document.getElementById('cartDrawer');
    const overlay = document.getElementById('cartOverlay');
    if (!drawer || !overlay) return;

    if (forceOpen) {
        drawer.classList.add('is-open');
        overlay.classList.add('is-open');
    } else {
        drawer.classList.toggle('is-open');
        overlay.classList.toggle('is-open');
    }
}

function updateCheckoutTotal() {
    const itemsSubtotal = cartItems.reduce((acc, i) => acc + (i.price * i.quantity), 0);
    let deliveryFee = 0;

    const selectedOpt = document.querySelector('input[name="delivery_option_id"]:checked');
    if (selectedOpt && selectedOpt.dataset.fee) {
        deliveryFee = parseFloat(selectedOpt.dataset.fee) || 0;
    }

    const grandTotal = itemsSubtotal + deliveryFee;
    const totalEl = document.getElementById('checkoutTotal');
    if (totalEl) totalEl.textContent = 'GHS ' + grandTotal.toFixed(2);
}

function goToCheckout() {
    toggleCart(false);
    updateCheckoutTotal();
    document.getElementById('checkoutModal').classList.add('is-open');
}

function closeCheckout() {
    document.getElementById('checkoutModal').classList.remove('is-open');
}

function formatGhanaPhoneInput(inputEl) {
    let raw = inputEl.value.replace(/\D/g, '');
    if (raw.startsWith('233')) raw = raw.substring(3);
    if (raw.startsWith('0')) raw = raw.substring(1);
    if (raw.length > 9) raw = raw.substring(0, 9);
    inputEl.value = raw;
}

async function submitCheckout(e) {
    e.preventDefault();
    const form = e.target;
    const errorEl = document.getElementById('checkoutError');
    const submitBtn = document.getElementById('submitCheckoutBtn');

    submitBtn.disabled = true;
    submitBtn.textContent = 'Processing...';
    errorEl.classList.add('hidden');

    const selectedDelivery = form.querySelector('input[name="delivery_option_id"]:checked');
    const deliveryOptionId = selectedDelivery ? selectedDelivery.value : null;
    const deliveryAddress = form.delivery_address ? form.delivery_address.value : '';

    let phoneVal = form.buyer_phone.value.replace(/\D/g, '');
    if (phoneVal.startsWith('233')) phoneVal = phoneVal.substring(3);
    if (phoneVal.startsWith('0')) phoneVal = phoneVal.substring(1);
    const formattedPhone = '+233' + phoneVal;

    try {
        const resp = await fetch(`/sale/${cartSlug}/checkout/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': CSRF_TOKEN,
            },
            body: JSON.stringify({
                buyer_name: form.buyer_name.value,
                buyer_phone: formattedPhone,
                buyer_email: form.buyer_email.value,
                delivery_option_id: deliveryOptionId,
                delivery_address: deliveryAddress,
                items: cartItems.map(i => ({
                    sale_item_id: i.sale_item_id,
                    quantity: i.quantity
                }))
            })
        });

        const data = await resp.json();
        if (data.success) {
            window.location.href = data.authorization_url;
        } else {
            errorEl.textContent = data.error || 'Checkout failed. Please try again.';
            errorEl.classList.remove('hidden');
        }
    } catch (err) {
        errorEl.textContent = 'Network error. Please try again.';
        errorEl.classList.remove('hidden');
    }

    submitBtn.disabled = false;
    submitBtn.textContent = 'Pay Now';
}
