// ═══════════════════════════════════════
// SHOPPING CART LOGIC (localStorage)
// ═══════════════════════════════════════
let cartItems = JSON.parse(localStorage.getItem('canifa_cart') || '[]');

function saveCart() {
    localStorage.setItem('canifa_cart', JSON.stringify(cartItems));
}

// ═══════════════════════════════════════════════════════
// SIZE PICKER MODAL — Shows sizes + stock qty before adding to cart
// ═══════════════════════════════════════════════════════
let _sizeModalProduct = null;

async function showSizePickerModal(productStr) {
    let product;
    try {
        product = typeof productStr === 'string' ? JSON.parse(decodeURIComponent(productStr)) : productStr;
    } catch(e) {
        console.error("Invalid product data", e);
        return;
    }
    
    _sizeModalProduct = product;
    const modal = document.getElementById('sizeModal');
    const overlay = document.getElementById('sizeModalOverlay');
    const body = document.getElementById('sizeModalBody');

    // Hiển thị modal với trạng thái loading
    modal.classList.add('show');
    overlay.classList.add('show');
    body.innerHTML = `
        <div style="padding: 50px 20px; text-align: center; color: #fff;">
            <div style="display:inline-block;width:30px;height:30px;border:3px solid rgba(255,255,255,0.2);border-top-color:#be1e2d;border-radius:50%;animation:spin 1s linear infinite;"></div>
            <div style="margin-top:16px;font-size:0.95em;color:#aaa;">Đang tải thông tin sản phẩm...</div>
        </div>
    `;

    // Lấy thông tin full từ hệ thống (kèm sizes và colors)
    try {
        const lookupResp = await fetch(`/api/product/lookup?skus=${product.sku}`);
        if (lookupResp.ok) {
            const lookupData = await lookupResp.json();
            if (lookupData.products && lookupData.products.length > 0) {
                const fullProduct = lookupData.products[0];
                // Merge product details, ưu tiên giữ giá/tên từ LLM nếu có
                product = { ...fullProduct, ...product, sizes: fullProduct.sizes, colors: fullProduct.colors };
                _sizeModalProduct = product;
            }
        }
    } catch (e) {
        console.warn('Failed to fetch full product details', e);
    }

    const price = product.sale_price || product.price || 0;
    const originalPrice = product.price || 0;
    const hasDiscount = price < originalPrice && price > 0;
    const priceHTML = hasDiscount
        ? `<span style="text-decoration:line-through;color:#999;font-size:0.85em">${originalPrice.toLocaleString('vi-VN')}đ</span> <span style="color:var(--canifa-red,#be1e2d);font-weight:700;font-size:1.1em">${price.toLocaleString('vi-VN')}đ</span>`
        : `<span style="color:var(--canifa-red,#be1e2d);font-weight:700;font-size:1.1em">${price > 0 ? price.toLocaleString('vi-VN') + 'đ' : 'Liên hệ'}</span>`;

    body.innerHTML = `
        <div class="size-modal-product">
            <img src="${product.thumbnail_image_url || product.image || ''}" alt="${product.name}" class="size-modal-img" onerror="this.src='https://via.placeholder.com/100x130?text=No+Img'">
            <div class="size-modal-info">
                <div class="size-modal-name">${product.name}</div>
                <div class="size-modal-sku">Mã: ${product.sku}</div>
                <div class="size-modal-price">${priceHTML}</div>
            </div>
        </div>
        ${product.colors && product.colors.length > 0 ? `
        <div class="size-modal-section">
            <div class="size-modal-label">Màu sắc: <span id="sizeModalColorName" style="color:#aaa;font-weight:normal;">${product.color || product.colors[0]?.color || ''}</span></div>
            <div class="size-modal-colors">
                ${product.colors.map((c, i) => `
                    <div class="size-modal-color-dot ${i === 0 ? 'active' : ''}"
                         style="background:${c.hex || '#888'}"
                         title="${c.color || ''}"
                         onclick="selectModalColor(this, '${(c.color || '').replace(/'/g, '')}')"
                    ></div>
                `).join('')}
            </div>
        </div>` : ''}
        <div class="size-modal-section">
            <div class="size-modal-label">Kích cỡ: <span class="size-modal-hint" id="sizeModalHint">Vui lòng chọn size</span></div>
            <div class="size-modal-sizes" id="sizeModalSizes">
                <div style="color:#999;font-size:0.85em;padding:8px 0">
                    <div style="display:inline-block;width:14px;height:14px;border:2px solid rgba(255,255,255,0.2);border-top-color:#fff;border-radius:50%;animation:spin 1s linear infinite;vertical-align:middle;margin-right:6px"></div>
                    Đang kiểm tra tồn kho...
                </div>
            </div>
        </div>
        <button class="size-modal-add-btn" id="sizeModalAddBtn" disabled onclick="addFromModal()">
            THÊM VÀO GIỎ HÀNG
        </button>
    `;

    // Fetch stock per size
    if (product.sizes && product.sizes.length > 0) {
        fetchSizeStock(product);
    } else {
        document.getElementById('sizeModalSizes').innerHTML = '<div style="color:#999;font-size:0.85em;padding:8px 0;">Sản phẩm không có thông tin Kích Cỡ.</div>';
    }
}

async function fetchSizeStock(product) {
    const sizesContainer = document.getElementById('sizeModalSizes');
    try {
        const resp = await fetch('/api/stock/check', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ codes: product.sku, timeout_sec: 8 })
        });
        const data = await resp.json();

        // Build stock map: SKU-SIZE → quantity
        const stockMap = {};
        if (data.stock_responses) {
            for (const chunk of data.stock_responses) {
                const items = chunk?.data || chunk?.items || [];
                if (Array.isArray(items)) {
                    for (const item of items) {
                        const sku = item.sku || item.product_sku || '';
                        const qty = parseInt(item.qty || item.quantity || 0);
                        stockMap[sku.toUpperCase()] = qty;
                    }
                }
            }
        }

        // Render size buttons with stock qty
        let html = '';
        for (const size of product.sizes) {
            // Find stock for this size across all color variants
            const matchingKeys = Object.keys(stockMap).filter(k =>
                k.toUpperCase().endsWith('-' + size.toUpperCase())
            );
            const totalQty = matchingKeys.reduce((sum, k) => sum + (stockMap[k] || 0), 0);
            const inStock = totalQty > 0;

            html += `
                <button class="size-modal-size-btn ${inStock ? '' : 'out-of-stock'}"
                        data-size="${size}" data-qty="${totalQty}"
                        onclick="selectModalSize(this, '${size}', ${totalQty})"
                        ${!inStock ? 'disabled' : ''}>
                    <span class="size-label">${size}</span>
                    <span class="size-qty ${inStock ? 'in-stock' : 'no-stock'}">${inStock ? `Còn ${totalQty}` : 'Hết hàng'}</span>
                </button>
            `;
        }
        sizesContainer.innerHTML = html || '<div style="color:#999;font-size:0.85em">Không có thông tin size</div>';
    } catch (err) {
        console.error('Stock fetch error:', err);
        // Fallback: render sizes without stock info
        let html = '';
        for (const size of product.sizes) {
            html += `
                <button class="size-modal-size-btn"
                        data-size="${size}" data-qty="-1"
                        onclick="selectModalSize(this, '${size}', -1)">
                    <span class="size-label">${size}</span>
                </button>
            `;
        }
        sizesContainer.innerHTML = html;
    }
}

let _selectedSize = null;
let _selectedSizeQty = 0;

function selectModalSize(btn, size, qty) {
    document.querySelectorAll('.size-modal-size-btn.selected').forEach(b => b.classList.remove('selected'));
    btn.classList.add('selected');
    _selectedSize = size;
    _selectedSizeQty = qty;
    const addBtn = document.getElementById('sizeModalAddBtn');
    addBtn.disabled = false;
    addBtn.textContent = `THÊM VÀO GIỎ HÀNG — Size ${size}`;
}

function selectModalColor(dot, colorName) {
    document.querySelectorAll('.size-modal-color-dot.active').forEach(d => d.classList.remove('active'));
    dot.classList.add('active');
    const nameEl = document.getElementById('sizeModalColorName');
    if (nameEl) nameEl.textContent = colorName;
}

function addFromModal() {
    if (!_sizeModalProduct || !_selectedSize) return;
    const product = _sizeModalProduct;
    const activeColor = document.querySelector('.size-modal-color-dot.active');
    const colorName = activeColor ? activeColor.title : (product.color || '');

    addToCart({
        sku: product.sku,
        cartKey: `${product.sku}:${_selectedSize}:${colorName}`,
        name: product.name,
        size: _selectedSize,
        color: colorName,
        price: product.sale_price || product.price || 0,
        originalPrice: product.price || 0,
        image: product.thumbnail_image_url || product.image || ''
    });

    closeSizeModal();
}

function closeSizeModal() {
    document.getElementById('sizeModal').classList.remove('show');
    document.getElementById('sizeModalOverlay').classList.remove('show');
    _sizeModalProduct = null;
    _selectedSize = null;
    _selectedSizeQty = 0;
}

function addToCart(product) {
    const key = product.cartKey || product.sku;
    if (cartItems.find(item => (item.cartKey || item.sku) === key)) {
        showCartToast('⚠️ Sản phẩm đã có trong giỏ!');
        return;
    }
    cartItems.push(product);
    saveCart();
    updateCartUI();
    const sizeInfo = product.size ? ` - Size ${product.size}` : '';
    const colorInfo = product.color ? ` - ${product.color}` : '';
    const priceStr = product.price ? ` · ${(product.price / 1000).toFixed(0)}k` : '';
    showCartToast(`✅ ${product.name.substring(0, 25)}${sizeInfo}${colorInfo}${priceStr}`);
}

function removeFromCart(key) {
    cartItems = cartItems.filter(item => (item.cartKey || item.sku) !== key);
    saveCart();
    updateCartUI();
}

function clearCart() {
    cartItems = [];
    saveCart();
    updateCartUI();
    toggleCart();
}

function toggleCart() {
    const drawer = document.getElementById('cartDrawer');
    const overlay = document.getElementById('cartOverlay');
    drawer.classList.toggle('open');
    overlay.classList.toggle('show');
}

function updateCartUI() {
    const badge = document.getElementById('cartBadge');
    const itemsContainer = document.getElementById('cartItems');
    const totalEl = document.getElementById('cartTotal');
    const sendBtn = document.getElementById('cartSendBtn');
    const clearBtn = document.getElementById('cartClearBtn');

    if (!badge) return;

    if (cartItems.length > 0) {
        badge.style.display = 'flex';
        badge.textContent = cartItems.length;
    } else {
        badge.style.display = 'none';
    }

    if (cartItems.length === 0) {
        itemsContainer.innerHTML = '<div class="cart-empty">Giỏ hàng trống. Thêm sản phẩm yêu thích!</div>';
        sendBtn.disabled = true;
        clearBtn.disabled = true;
        totalEl.textContent = '0đ';
        return;
    }

    sendBtn.disabled = false;
    clearBtn.disabled = false;

    let html = '';
    let total = 0;
    cartItems.forEach((item, idx) => {
        const qty = item.qty || 1;
        const price = item.price || 0;
        total += price * qty;
        const priceStr = price > 0 ? price.toLocaleString('vi-VN') + 'đ' : 'Liên hệ';
        const origStr = (item.originalPrice && item.originalPrice > price)
            ? `<span style="text-decoration:line-through;color:#888;font-size:0.8em;margin-left:6px">${item.originalPrice.toLocaleString('vi-VN')}đ</span>` : '';
        const removeKey = item.cartKey || item.sku;

        let detailBadges = '';
        if (item.color) {
            detailBadges += `<span style="display:inline-flex;align-items:center;gap:3px;background:rgba(255,255,255,0.1);border:1px solid rgba(255,255,255,0.15);padding:2px 8px;border-radius:10px;font-size:0.75em;">🎨 ${item.color}</span> `;
        }
        if (item.size) {
            detailBadges += `<span style="display:inline-flex;align-items:center;gap:3px;background:rgba(255,255,255,0.1);border:1px solid rgba(255,255,255,0.15);padding:2px 8px;border-radius:10px;font-size:0.75em;">📏 ${item.size}</span> `;
        }

        html += `
            <div class="cart-item">
                <img src="${item.image || 'https://via.placeholder.com/60'}" alt="${item.name}"
                     onerror="this.src='https://via.placeholder.com/60?text=No+Img'">
                <div class="cart-item-info">
                    <div class="cart-item-name">${item.name}</div>
                    <div class="cart-item-price">${priceStr}${origStr}</div>
                    <div style="margin-top:3px;">${detailBadges || `<span style="font-size:0.75em;color:#888;">SKU: ${item.sku}</span>`}</div>
                    <div style="display:flex;align-items:center;gap:8px;margin-top:5px;">
                        <button onclick="changeCartQty(${idx}, -1)" style="width:24px;height:24px;border:1px solid rgba(255,255,255,0.2);background:rgba(255,255,255,0.08);color:#fff;border-radius:6px;cursor:pointer;font-size:14px;display:flex;align-items:center;justify-content:center;">−</button>
                        <span style="min-width:20px;text-align:center;font-weight:600;font-size:0.9em;">${qty}</span>
                        <button onclick="changeCartQty(${idx}, 1)" style="width:24px;height:24px;border:1px solid rgba(255,255,255,0.2);background:rgba(255,255,255,0.08);color:#fff;border-radius:6px;cursor:pointer;font-size:14px;display:flex;align-items:center;justify-content:center;">+</button>
                    </div>
                </div>
                <button class="cart-item-remove" onclick="removeFromCart('${removeKey}')">✕</button>
            </div>`;
    });
    itemsContainer.innerHTML = html;
    totalEl.textContent = total > 0 ? total.toLocaleString('vi-VN') + 'đ' : '0đ';
}

function sendCartToBot() {
    if (cartItems.length === 0) return;
    const skuList = cartItems.map(i => {
        const qty = i.qty || 1;
        const details = [i.size, i.color].filter(Boolean).join('/');
        return `[${i.sku}] ${i.name}${details ? ' (' + details + ')' : ''} x${qty}`;
    }).join(', ');
    const msg = `Mình muốn đặt hàng: ${skuList}`;
    
    const inputEl = document.getElementById('chatInput');
    if(inputEl) inputEl.value = msg;
    
    toggleCart();
    
    if (typeof sendMessage === 'function') {
        sendMessage();
    } else if (typeof sendMsg === 'function') {
        sendMsg();
    }
}

function changeCartQty(idx, delta) {
    if (idx < 0 || idx >= cartItems.length) return;
    const item = cartItems[idx];
    const newQty = (item.qty || 1) + delta;
    if (newQty < 1) return;
    item.qty = newQty;
    saveCart();
    updateCartUI();
}

function showCartToast(text) {
    const toast = document.getElementById('cartToast');
    if (!toast) return;
    toast.textContent = text;
    toast.classList.add('show');
    setTimeout(() => toast.classList.remove('show'), 2000);
}

// Init cart UI on page load if elements exist
document.addEventListener('DOMContentLoaded', () => {
    if(document.getElementById('cartDrawer')) {
        updateCartUI();
    }
});

// Also run immediately in case DOM is already loaded (e.g. script at bottom of body)
if (document.readyState !== 'loading') {
    updateCartUI();
}
