let faqs = [];
let currentPage = 1;
const PAGE_SIZE = 30;
let searchTimer = null;

function esc(s) { return s ? s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;') : ''; }
function truncate(s, n) { return s && s.length > n ? s.substring(0, n) + '…' : s; }

async function loadStats() {
    try {
        const r = await fetch('/api/faqs/stats');
        const d = await r.json();
        document.getElementById('statTotal').textContent = d.total || 0;
        document.getElementById('statOriginals').textContent = d.originals || 0;
        document.getElementById('statVariants').textContent = d.variants || 0;
        document.getElementById('statCategories').textContent = (d.by_category || []).length;
        // populate category filter
        const sel = document.getElementById('filterCat');
        const current = sel.value;
        sel.innerHTML = '<option value="">Tất cả danh mục</option>';
        (d.by_category || []).forEach(c => {
            sel.innerHTML += `<option value="${esc(c.category)}" ${c.category === current ? 'selected' : ''}>${esc(c.category)} (${c.cnt})</option>`;
        });
    } catch(e) { console.error('Stats error', e); }
}

async function loadFaqs() {
    const cat = document.getElementById('filterCat').value;
    const search = document.getElementById('searchInput').value.trim();
    const variants = document.getElementById('showVariants').checked;
    let url = `/api/faqs?page=${currentPage}&limit=${PAGE_SIZE}`;
    if (cat) url += `&category=${encodeURIComponent(cat)}`;
    if (search) url += `&search=${encodeURIComponent(search)}`;
    if (!variants) url += `&variants=false`;

    try {
        const r = await fetch(url);
        const d = await r.json();
        faqs = d.faqs || [];
        renderTable(faqs, d.total || 0);
    } catch(e) { console.error('Load error', e); }
}

function renderTable(items, total) {
    const body = document.getElementById('faqBody');
    if (!items.length) {
        body.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:40px;color:var(--m)">Không tìm thấy FAQ nào.</td></tr>';
        document.getElementById('pagination').innerHTML = '';
        return;
    }
    const offset = (currentPage - 1) * PAGE_SIZE;
    body.innerHTML = items.map((f, i) => `
        <tr>
            <td style="color:var(--m)">${offset + i + 1}</td>
            <td><div class="q-text">${esc(f.question)}</div></td>
            <td><div class="a-text" title="${esc(f.answer)}">${esc(truncate(f.answer, 80))}</div></td>
            <td><span class="cat-tag">${esc(f.category)}</span></td>
            <td>${f.is_variant ? '<span class="badge-cat badge-variant">Biến thể</span>' : '<span class="badge-cat badge-original">Gốc</span>'}</td>
            <td>
                ${!f.is_variant ? `<button class="act-btn gen-badge" onclick="generateVariants('${f.id}')" title="AI sinh biến thể"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/></svg> Generate</button>` : ''}
                <button class="act-btn" onclick="editFaq('${f.id}')" title="Sửa"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></button>
                <button class="act-btn" onclick="deleteFaq('${f.id}')" title="Xoá"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg></button>
            </td>
        </tr>
    `).join('');

    // Pagination
    const totalPages = Math.ceil(total / PAGE_SIZE);
    const pag = document.getElementById('pagination');
    if (totalPages <= 1) { pag.innerHTML = ''; return; }
    let html = '';
    for (let p = 1; p <= totalPages; p++) {
        html += `<button class="page-btn ${p === currentPage ? 'active' : ''}" onclick="goPage(${p})">${p}</button>`;
    }
    pag.innerHTML = html;
}

function goPage(p) { currentPage = p; loadFaqs(); }
function debounceSearch() { clearTimeout(searchTimer); searchTimer = setTimeout(() => { currentPage = 1; loadFaqs(); }, 300); }

// ── Modal ──
function openAddModal() {
    document.getElementById('faqModal').classList.add('show');
    document.getElementById('editId').value = '';
    document.getElementById('fQuestion').value = '';
    document.getElementById('fAnswer').value = '';
    document.getElementById('fCategory').value = 'chung';
    document.getElementById('modalTitle').innerHTML = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:middle;margin-right:4px;color:var(--primary)"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> Thêm FAQ';
}
function closeModal() { document.getElementById('faqModal').classList.remove('show'); }

function editFaq(id) {
    const f = faqs.find(x => x.id === id);
    if (!f) return;
    document.getElementById('faqModal').classList.add('show');
    document.getElementById('editId').value = id;
    document.getElementById('fQuestion').value = f.question;
    document.getElementById('fAnswer').value = f.answer;
    document.getElementById('fCategory').value = f.category;
    document.getElementById('modalTitle').innerHTML = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:middle;margin-right:4px;color:var(--primary)"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg> Sửa FAQ';
}

async function saveFaq() {
    const id = document.getElementById('editId').value;
    const body = {
        question: document.getElementById('fQuestion').value.trim(),
        answer: document.getElementById('fAnswer').value.trim(),
        category: document.getElementById('fCategory').value,
    };
    if (!body.question || !body.answer) { alert('Vui lòng điền đầy đủ câu hỏi và trả lời'); return; }
    try {
        await fetch(id ? `/api/faqs/${id}` : '/api/faqs', {
            method: id ? 'PUT' : 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(body)
        });
        closeModal();
        await loadStats();
        await loadFaqs();
    } catch(e) { alert('Lỗi: ' + e.message); }
}

async function deleteFaq(id) {
    if (!confirm('Xoá FAQ này và tất cả biến thể liên quan?')) return;
    try {
        await fetch(`/api/faqs/${id}`, { method: 'DELETE' });
        await loadStats();
        await loadFaqs();
    } catch(e) { alert('Lỗi: ' + e.message); }
}

// ── AI Generation ──
async function generateVariants(faqId) {
    const btn = event.target;
    const ogText = btn.innerHTML;
    btn.innerHTML = '⏳ Đang sinh...';
    btn.disabled = true;
    try {
        const r = await fetch('/api/faqs/generate-variants', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ faq_id: faqId, count: 20 })
        });
        const d = await r.json();
        if (d.status === 'success') {
            alert(`✅ Đã sinh ${d.inserted} biến thể!`);
            await loadStats();
            await loadFaqs();
        } else {
            alert('Lỗi: ' + JSON.stringify(d));
        }
    } catch(e) {
        alert('Lỗi AI: ' + e.message);
    } finally {
        btn.innerHTML = ogText;
        btn.disabled = false;
    }
}

async function batchGenerate() {
    const cat = document.getElementById('filterCat').value;
    const msg = cat ? `Sinh biến thể AI cho tất cả FAQ gốc trong danh mục "${cat}"?` : 'Sinh biến thể AI cho TẤT CẢ FAQ gốc? (có thể mất vài phút)';
    if (!confirm(msg)) return;

    const btn = document.getElementById('btnBatch');
    btn.innerHTML = '⏳ Đang xử lý...';
    btn.disabled = true;
    try {
        const r = await fetch('/api/faqs/batch-generate', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ category: cat || null, count_per_faq: 10 })
        });
        const d = await r.json();
        alert(`✅ Đã xử lý ${d.originals_processed} FAQ gốc, sinh ${d.total_variants_inserted} biến thể.${d.errors?.length ? `\n⚠️ ${d.errors.length} lỗi.` : ''}`);
        await loadStats();
        await loadFaqs();
    } catch(e) {
        alert('Lỗi: ' + e.message);
    } finally {
        btn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/></svg> Batch AI';
        btn.disabled = false;
    }
}

// ── Simulator ──
async function simulateMatch() {
    const query = document.getElementById('simQuery').value.trim();
    if (!query) return;
    
    const btn = document.getElementById('btnSim');
    const resDiv = document.getElementById('simResults');
    const metaDiv = document.getElementById('simMeta');
    
    btn.innerHTML = '⏳ Đang Match...';
    btn.disabled = true;
    resDiv.innerHTML = '<div style="text-align:center;padding:20px"><div class="spinner"></div></div>';
    
    try {
        const r = await fetch('/api/faqs/simulate-match', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ query })
        });
        const d = await r.json();
        
        metaDiv.textContent = `⚡ Search Time: ${d.elapsed_ms || 0}ms`;
        
        if (!d.matches || !d.matches.length) {
            resDiv.innerHTML = '<div style="text-align:center;color:var(--error);font-size:12px;padding:20px">Không có kết quả Match nào > 5%.</div>';
            return;
        }
        
        resDiv.innerHTML = d.matches.map(m => `
            <div class="sim-card">
                <span class="sim-score">${m.score}%</span>
                <div class="sim-q">${esc(m.question)}</div>
                <div class="sim-a" title="${esc(m.answer)}">${esc(m.answer)}</div>
                <div style="margin-top:6px">
                    <span class="cat-tag">${esc(m.category)}</span>
                    ${m.is_variant ? '<span class="badge-cat badge-variant" style="transform:scale(0.85);transform-origin:left">Biến thể</span>' : '<span class="badge-cat badge-original" style="transform:scale(0.85);transform-origin:left">Gốc</span>'}
                </div>
            </div>
        `).join('');
    } catch(e) {
        resDiv.innerHTML = `<div style="color:var(--error);font-size:12px">Lỗi: ${e.message}</div>`;
    } finally {
        btn.innerHTML = '🔍 Test Match';
        btn.disabled = false;
    }
}

document.addEventListener('keydown', e => { 
    if (e.key === 'Escape') closeModal(); 
    if (e.key === 'Enter' && e.ctrlKey && document.activeElement.id === 'simQuery') {
        simulateMatch();
    }
});

// ── Init ──
(async () => {
    await loadStats();
    await loadFaqs();
})();
