// ═══════════════════════════════════════
// Lead Flow — Self-contained Product Popup
// click product card → popup → API stock → thêm giỏ hàng
// ═══════════════════════════════════════

(function () {
    'use strict';

    // ── State ──
    let _product = null;
    let _selectedSize = null;

    // ── DOM refs (lazy) ──
    function overlay() { return document.getElementById('lfOverlay'); }
    function popup()   { return document.getElementById('lfPopup'); }

    // ── Open popup ──
    window.openProductPopup = function (product) {
        // Normalize sizes
        let sizes = product.available_sizes || product.sizes || [];
        if (typeof sizes === 'string') {
            sizes = sizes.split('|').map(s => s.trim()).filter(Boolean);
        }

        _product = {
            sku:              product.sku || '',
            name:             product.name || '',
            price:            product.price || 0,
            original_price:   product.original_price || product.price || 0,
            image:            product.image || product.product_image_url_thumbnail || '',
            color:            product.color || product.master_color || '',
            colors:           product.colors || [],
            sizes:            sizes,
            url:              product.url || product.product_web_url || '#',
        };
        _selectedSize = null;

        _renderPopup(_product);
        _show();

        // Fetch full info từ lookup API → cập nhật colors + sizes nếu có
        if (_product.sku) {
            _fetchProductDetail(_product.sku);
        }
    };

    // ── Close popup ──
    window.closeProductPopup = function () {
        _hide();
    };

    // ── Internal: render popup content ──
    function _renderPopup(p) {
        const body = document.getElementById('lfPopupBody');
        if (!body) return;

        const hasDiscount = p.original_price && p.original_price > p.price && p.price > 0;
        const discPct = hasDiscount
            ? Math.round((1 - p.price / p.original_price) * 100)
            : 0;

        body.innerHTML = `
            <div class="lf-product-row">
                <img class="lf-product-img" src="${_esc(p.image)}" alt="${_esc(p.name)}"
                     onerror="this.src='';this.style.background='#2a2c35'">
                <div class="lf-product-info">
                    <div class="lf-product-name">${_esc(p.name)}</div>
                    <div class="lf-product-sku">SKU: ${_esc(p.sku)}</div>
                    <div class="lf-product-price">
                        ${p.price > 0 ? `<span class="lf-price-sale">${p.price.toLocaleString('vi-VN')}đ</span>` : ''}
                        ${hasDiscount ? `<span class="lf-price-orig">${p.original_price.toLocaleString('vi-VN')}đ</span>` : ''}
                        ${hasDiscount ? `<span class="lf-price-badge">-${discPct}%</span>` : ''}
                    </div>
                </div>
            </div>

            ${p.colors && p.colors.length > 0 ? `
            <div class="lf-section">
                <div class="lf-section-label">Màu sắc · <span id="lfColorName">${_esc(p.color || p.colors[0]?.color || '')}</span></div>
                <div class="lf-colors">
                    ${p.colors.map((c, i) => `
                        <div class="lf-color-dot ${i === 0 ? 'active' : ''}"
                             style="background:${c.hex || '#888'}"
                             title="${_esc(c.color || '')}"
                             onclick="window._lfSelectColor(this, '${_esc(c.color || '')}')"></div>
                    `).join('')}
                </div>
            </div>` : ''}

            <div class="lf-section">
                <div class="lf-section-label">Kích cỡ</div>
                <div class="lf-sizes" id="lfSizes">
                    ${p.sizes.length > 0
                        ? p.sizes.map(s => `
                            <button class="lf-size-btn" data-size="${_esc(s)}"
                                    onclick="window._lfSelectSize(this, '${_esc(s)}')">
                                <span class="lf-size-label">${_esc(s)}</span>
                                <span class="lf-size-qty" id="lfQty_${_esc(s)}">
                                    <span class="lf-spinner"></span>
                                </span>
                            </button>`).join('')
                        : '<span class="lf-size-stock-loading">Không có thông tin size</span>'
                    }
                </div>
            </div>

            <button class="lf-add-btn" id="lfAddBtn" onclick="window._lfAddToCart()" disabled>
                CHỌN SIZE ĐỂ THÊM VÀO GIỎ HÀNG
            </button>

            <a class="lf-detail-link" href="${_esc(p.url)}" target="_blank" rel="noopener">
                🔗 Xem chi tiết trên canifa.com
            </a>
        `;

        // Fetch stock nếu có sizes
        if (p.sizes.length > 0) {
            _fetchStock(p.sku, p.sizes);
        }
    }

    // ── Fetch product details từ lookup API ──
    async function _fetchProductDetail(sku) {
        try {
            const resp = await fetch(`/api/product/lookup?skus=${encodeURIComponent(sku)}`);
            if (!resp.ok) return;
            const data = await resp.json();
            const full = data.products && data.products[0];
            if (!full) return;

            // Merge: ưu tiên API cho sizes/colors, giữ cached price/name
            _product = {
                ..._product,
                sizes:  full.sizes  || _product.sizes,
                colors: full.colors || _product.colors,
            };

            // Re-render nếu popup vẫn mở
            if (overlay() && overlay().classList.contains('active')) {
                _renderPopup(_product);
            }
        } catch (e) {
            // ignore — đã có data từ chat
        }
    }

    // ── Fetch stock qty per size ──
    async function _fetchStock(sku, sizes) {
        try {
            const resp = await fetch('/api/stock/check', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ codes: sku, timeout_sec: 8 })
            });
            if (!resp.ok) throw new Error('stock api error');

            const data = await resp.json();

            // Build stockMap: "SKU-SIZE" → qty
            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 k = (item.sku || item.product_sku || '').toUpperCase();
                            stockMap[k] = parseInt(item.qty || item.quantity || 0);
                        }
                    }
                }
            }

            // Update qty labels
            for (const size of sizes) {
                const qtyEl = document.getElementById(`lfQty_${size}`);
                if (!qtyEl) continue;

                const matching = Object.keys(stockMap).filter(k =>
                    k.endsWith('-' + size.toUpperCase())
                );
                const qty = matching.reduce((s, k) => s + (stockMap[k] || 0), 0);
                const inStock = qty > 0;

                qtyEl.innerHTML = inStock
                    ? `<span class="lf-size-qty in-stock">Còn ${qty}</span>`
                    : `<span class="lf-size-qty no-stock">Hết hàng</span>`;

                const btn = document.querySelector(`.lf-size-btn[data-size="${size}"]`);
                if (btn && !inStock) {
                    btn.disabled = true;
                }
            }
        } catch (e) {
            // Fallback: remove spinners, keep buttons enabled
            const spinners = document.querySelectorAll('#lfSizes .lf-spinner');
            spinners.forEach(s => s.parentElement.textContent = '');
        }
    }

    // ── Select color ──
    window._lfSelectColor = function (dot, colorName) {
        document.querySelectorAll('.lf-color-dot').forEach(d => d.classList.remove('active'));
        dot.classList.add('active');
        const nameEl = document.getElementById('lfColorName');
        if (nameEl) nameEl.textContent = colorName;
    };

    // ── Select size ──
    window._lfSelectSize = function (btn, size) {
        if (btn.disabled) return;
        document.querySelectorAll('.lf-size-btn').forEach(b => b.classList.remove('selected'));
        btn.classList.add('selected');
        _selectedSize = size;

        const addBtn = document.getElementById('lfAddBtn');
        if (addBtn) {
            addBtn.disabled = false;
            addBtn.classList.add('ready');
            addBtn.textContent = `THÊM VÀO GIỎ HÀNG — Size ${size}`;
        }
    };

    // ── Add to cart ──
    window._lfAddToCart = function () {
        if (!_product || !_selectedSize) return;

        const activeDot = document.querySelector('.lf-color-dot.active');
        const colorName = activeDot ? activeDot.title : (_product.color || '');

        const cartItem = {
            sku:          _product.sku,
            cartKey:      `${_product.sku}:${_selectedSize}:${colorName}`,
            name:         _product.name,
            size:         _selectedSize,
            color:        colorName,
            price:        _product.price,
            originalPrice: _product.original_price,
            image:        _product.image,
            thumbnail_image_url: _product.image,
        };

        // Dùng addToCart từ cart.js nếu có, fallback localStorage
        if (typeof addToCart === 'function') {
            addToCart(cartItem);
        } else {
            _fallbackAddToCart(cartItem);
        }

        _hide();
    };

    // ── Fallback if cart.js not loaded ──
    function _fallbackAddToCart(item) {
        let cart = JSON.parse(localStorage.getItem('canifa_cart') || '[]');
        const key = item.cartKey || item.sku;
        if (cart.find(c => (c.cartKey || c.sku) === key)) {
            alert('⚠️ Sản phẩm đã có trong giỏ!');
            return;
        }
        cart.push(item);
        localStorage.setItem('canifa_cart', JSON.stringify(cart));
        // Update badge if exists
        const badge = document.getElementById('cartBadge');
        if (badge) { badge.textContent = cart.length; badge.style.display = 'flex'; }
        _toast(`✅ Đã thêm ${item.name.substring(0, 25)} - Size ${item.size}`);
    }

    // ── Toast ──
    function _toast(msg) {
        const t = document.getElementById('cartToast');
        if (!t) return;
        t.textContent = msg;
        t.classList.add('show');
        setTimeout(() => t.classList.remove('show'), 2200);
    }

    // ── Show/hide ──
    function _show() {
        const ov = overlay(); const pp = popup();
        if (ov) ov.classList.add('active');
        if (pp) pp.classList.add('active');
        document.body.style.overflow = 'hidden';
    }

    function _hide() {
        const ov = overlay(); const pp = popup();
        if (ov) ov.classList.remove('active');
        if (pp) pp.classList.remove('active');
        document.body.style.overflow = '';
        _product = null;
        _selectedSize = null;
    }

    // ── Escape HTML ──
    function _esc(str) {
        if (!str) return '';
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    // ── ESC key to close ──
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') closeProductPopup();
    });

})();
