const API = '/api/test/db-search';

        async function search() {
            const results = document.getElementById('results');
            const stats = document.getElementById('stats');
            results.innerHTML = '<div class="loading">⏳ Querying DB...</div>';
            stats.textContent = '';

            const body = {
                description: document.getElementById('description').value || null,
                product_name: document.getElementById('product_name').value || null,
                magento_ref_code: document.getElementById('magento_ref_code').value || null,
                gender_by_product: document.getElementById('gender').value || null,
                age_by_product: document.getElementById('age').value || null,
                master_color: document.getElementById('color').value || null,
                price_min: parseInt(document.getElementById('price_min').value) || null,
                price_max: parseInt(document.getElementById('price_max').value) || null,
                discount_min: parseInt(document.getElementById('discount_min').value) || null,
                discount_max: parseInt(document.getElementById('discount_max').value) || null,
                discovery_mode: document.getElementById('discovery_mode').value || null,
            };

            try {
                const t0 = Date.now();
                const res = await fetch(API, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(body)
                });
                const data = await res.json();
                const elapsed = Date.now() - t0;

                if (data.error) {
                    results.innerHTML = `<div class="empty-state"><div class="icon">❌</div><p>${data.error}</p></div>`;
                    return;
                }

                const products = data.products || [];
                stats.innerHTML = `<span>${products.length}</span> sản phẩm • <span>${elapsed}ms</span> • embed: <span>${data.embed_ms || 0}ms</span> • db: <span>${data.db_ms || 0}ms</span>`;

                // SQL Preview
                if (data.sql_preview) {
                    const sqlEl = document.getElementById('sqlPreview');
                    sqlEl.style.display = 'block';
                    sqlEl.textContent = data.sql_preview;
                }

                if (products.length === 0) {
                    results.innerHTML = '<div class="empty-state"><div class="icon">📭</div><p>Không tìm thấy sản phẩm nào</p></div>';
                    return;
                }

                results.innerHTML = '<div class="product-grid">' + products.map(p => {
                    const discount = p.discount_percent ? `<span class="discount-badge">-${Math.round(p.discount_percent)}%</span>` : '';
                    const originalPrice = p.original_price && p.original_price > p.sale_price
                        ? `<span class="price-original">${Number(p.original_price).toLocaleString()}đ</span>` : '';
                    const score = p.similarity_score ? `<span class="score">Score: ${Number(p.similarity_score).toFixed(3)}</span>` : '';
                    const sold = p.quantity_sold ? `<span class="sold">Sold: ${Number(p.quantity_sold).toLocaleString()}</span>` : '';
                    const img = p.product_image_url_thumbnail
                        ? `<img src="${p.product_image_url_thumbnail}" alt="${p.product_name}" onerror="this.style.display='none'">`
                        : '';

                    return `<div class="product-card">
        ${img}
        <div class="product-name">${p.product_name || '?'}</div>
        <div class="product-code">${p.magento_ref_code || p.internal_ref_code || '?'}</div>
        <div class="product-price">
          <span class="price-sale">${Number(p.sale_price || 0).toLocaleString()}đ</span>
          ${originalPrice} ${discount}
        </div>
        <div class="product-meta">
          ${score} ${sold}
          <span>${p.gender_by_product || '?'}</span>
          <span>${p.age_by_product || '?'}</span>
          <span>${p.master_color || '?'}</span>
          <span>${p.product_line_vn || '?'}</span>
          ${p.size_scale ? `<span>Size: ${p.size_scale}</span>` : ''}
        </div>
      </div>`;
                }).join('') + '</div>';
            } catch (e) {
                results.innerHTML = `<div class="empty-state"><div class="icon">💥</div><p>Error: ${e.message}</p></div>`;
            }
        }

        function clearForm() {
            document.querySelectorAll('input, select').forEach(el => {
                if (el.tagName === 'SELECT') el.selectedIndex = 0;
                else el.value = '';
            });
            document.getElementById('results').innerHTML = '<div class="empty-state"><div class="icon">🔎</div><p>Nhập tiêu chí và bấm Search để query trực tiếp DB</p></div>';
            document.getElementById('stats').textContent = '';
            document.getElementById('sqlPreview').style.display = 'none';
        }

        // Enter key to search
        document.addEventListener('keydown', e => { if (e.key === 'Enter') search(); });