let allData = [], currentTag = '', currentStatus = '', searchTerm = '', compareMode = false, compareIds = new Set();

async function load() {
    let url = '/api/dashboard/experiments?';
    if (currentTag) url += `tag=${currentTag}&`;
    if (currentStatus) url += `status=${currentStatus}&`;
    const res = await fetch(url);
    const data = await res.json();
    allData = data.experiments || [];
    renderCards(allData);
    renderTags(data.tags || {});
    renderHeatmap(data.activity || {});
}

function renderCards(items) {
    let filtered = items;
    if (searchTerm) {
        const s = searchTerm.toLowerCase();
        filtered = items.filter(e => e.title.toLowerCase().includes(s) || e.version.toLowerCase().includes(s) || (e.content||'').toLowerCase().includes(s));
    }
    if (!filtered.length) { document.getElementById('cardList').innerHTML = '<div class="empty">Không có experiment nào</div>'; return; }
    document.getElementById('cardList').innerHTML = filtered.map(e => {
        const d = new Date(e.created_at);
        const date = `${d.getDate()}/${d.getMonth()+1}/${d.getFullYear()}`;
        return `
        <div class="exp-card ${e.pinned ? 'pinned' : ''}">
            <div class="card-actions">
                <button onclick="pinExp('${e.id}')" title="Pin">📌</button>
                <button onclick="editExp('${e.id}')" title="Edit">✎</button>
                <button class="del" onclick="deleteExp('${e.id}','${esc(e.title)}')" title="Xóa">✕</button>
            </div>
            <div class="card-top">
                ${compareMode ? `<input type="checkbox" class="cmp-check" onchange="toggleCompare('${e.id}', this)" ${compareIds.has(e.id)?'checked':''}>`:''}
                <span class="card-ver">${e.version}</span>
                <span class="card-status s-${e.status}">${e.status}</span>
                <span class="card-date">${date}</span>
            </div>
            <div class="card-title">${e.title}</div>
            ${e.content ? `<div class="card-desc">${e.content}</div>` : ''}
            ${e.model_name ? `<div class="card-model">${e.model_name}</div>` : ''}
            ${(e.tags||[]).length ? `<div class="card-tags">${e.tags.map(t=>`<span class="card-tag">#${t}</span>`).join('')}</div>` : ''}
            <div class="metrics">
                ${e.score != null ? `<div class="metric"><span class="metric-label">Score</span><span class="metric-val ${e.score>=8?'mv-good':e.score>=7?'':'mv-bad'}">${e.score}</span></div>` : ''}
                ${e.latency_avg != null ? `<div class="metric"><span class="metric-label">Latency</span><span class="metric-val ${e.latency_avg<=1800?'mv-good':e.latency_avg<=2200?'':'mv-bad'}">${e.latency_avg}ms</span></div>` : ''}
                ${e.cost_per_req != null ? `<div class="metric"><span class="metric-label">Cost/req</span><span class="metric-val ${e.cost_per_req<=0.003?'mv-good':e.cost_per_req<=0.008?'':'mv-bad'}">$${e.cost_per_req}</span></div>` : ''}
                ${e.error_rate != null ? `<div class="metric"><span class="metric-label">Error</span><span class="metric-val ${e.error_rate<=1?'mv-good':e.error_rate<=2?'mv-warn':'mv-bad'}">${e.error_rate}%</span></div>` : ''}
            </div>
        </div>`;
    }).join('');
}

function renderTags(tags) {
    document.getElementById('tagList').innerHTML = Object.entries(tags).map(([t,c]) =>
        `<span class="tag-chip ${currentTag===t?'active':''}" onclick="filterTag('${t}')">#${t}<span class="tag-count">${c}</span></span>`
    ).join('');
}

function renderHeatmap(activity) {
    // Last 12 weeks
    const today = new Date(); const cells = [];
    for (let i = 83; i >= 0; i--) {
        const d = new Date(today); d.setDate(d.getDate() - i);
        const key = d.toISOString().split('T')[0];
        const count = activity[key] || 0;
        const level = count === 0 ? '' : count === 1 ? 'l1' : count === 2 ? 'l2' : count <= 4 ? 'l3' : 'l4';
        cells.push(`<div class="hm-cell ${level}" title="${key}: ${count}"></div>`);
    }
    const m1 = new Date(today); m1.setDate(m1.getDate()-83);
    document.getElementById('heatmap').innerHTML = `
        <div class="hm-month"><span>${m1.toLocaleDateString('vi',{month:'short'})}</span><span>${today.toLocaleDateString('vi',{month:'short'})}</span></div>
        <div class="hm-grid">${cells.join('')}</div>`;
}

function filterTag(tag) { currentTag = currentTag === tag ? '' : tag; load(); }
function filterStatus(el, status) {
    currentStatus = status;
    document.querySelectorAll('.status-row').forEach(r => r.classList.remove('active'));
    el.classList.add('active');
    load();
}
function doSearch() { searchTerm = document.getElementById('searchInput').value; renderCards(allData); }
function esc(s) { return (s||'').replace(/'/g,"\\'"); }

function toggleCompareMode() {
    compareMode = !compareMode;
    compareIds.clear();
    document.getElementById('compareToggle').classList.toggle('active', compareMode);
    document.getElementById('compareBar').classList.toggle('visible', compareMode);
    document.getElementById('compareView').innerHTML = '';
    renderCards(allData);
}
function toggleCompare(id, cb) {
    if (cb.checked) { if (compareIds.size >= 2) { cb.checked = false; return; } compareIds.add(id); }
    else compareIds.delete(id);
    document.getElementById('cmpText').textContent = `Đã chọn ${compareIds.size}/2`;
    document.getElementById('cmpBtn').disabled = compareIds.size !== 2;
}
async function runCompare() {
    const [id1, id2] = [...compareIds];
    const res = await fetch(`/api/dashboard/experiments/compare?id1=${id1}&id2=${id2}`);
    const data = await res.json();
    if (!data.experiments || data.experiments.length < 2) return;
    const [a, b] = data.experiments;
    const rows = [
        ['Score', a.score, b.score, true],
        ['Latency (ms)', a.latency_avg, b.latency_avg, false],
        ['Cost/req ($)', a.cost_per_req, b.cost_per_req, false],
        ['Error (%)', a.error_rate, b.error_rate, false],
    ];
    document.getElementById('compareView').innerHTML = `
        <div class="compare-view">
            <div class="cmp-col">
                <h3>${a.version} — ${a.title}</h3>
                <div class="card-model">${a.model_name||'-'}</div>
                ${rows.map(([l,va])=>`<div class="cmp-row"><span class="cmp-label">${l}</span><span class="cmp-val">${va??'-'}</span></div>`).join('')}
            </div>
            <div class="cmp-col">
                <h3>${b.version} — ${b.title}</h3>
                <div class="card-model">${b.model_name||'-'}</div>
                ${rows.map(([l,,vb,higher])=>{
                    const va = rows.find(r=>r[0]===l)[1];
                    let cls = '';
                    if(va!=null&&vb!=null){cls=higher?(vb>va?'cmp-better':vb<va?'cmp-worse':''):(vb<va?'cmp-better':vb>va?'cmp-worse':'');}
                    return `<div class="cmp-row"><span class="cmp-label">${l}</span><span class="cmp-val ${cls}">${vb??'-'}</span></div>`;
                }).join('')}
            </div>
        </div>`;
    toggleCompareMode();
}

async function pinExp(id) { await fetch(`/api/dashboard/experiments/${id}/pin`,{method:'PATCH'}); load(); }
async function deleteExp(id,t) { if(!confirm(`Xóa "${t}"?`))return; await fetch(`/api/dashboard/experiments/${id}`,{method:'DELETE'}); load(); }
async function editExp(id) {
    const e = allData.find(x=>x.id===id); if(!e)return;
    const title = prompt('Tên:', e.title); if(title===null)return;
    const content = prompt('Mô tả:', e.content||''); if(content===null)return;
    const score = prompt('Score (0-10):', e.score||'');
    const body = {title, content};
    if(score) body.score = parseFloat(score);
    await fetch(`/api/dashboard/experiments/${id}`,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
    load();
}
async function addExperiment() {
    const version = prompt('Version (vd: v2.3):'); if(!version)return;
    const title = prompt('Tên thử nghiệm:'); if(!title)return;
    const content = prompt('Mô tả chi tiết:') || '';
    const model_name = prompt('Model (vd: gemini-3.1-flash-lite):') || '';
    const tagsStr = prompt('Tags (cách nhau bằng dấu phẩy, vd: model,prompt):') || '';
    const tags = tagsStr ? tagsStr.split(',').map(t=>t.trim()) : [];
    const score = prompt('Score (0-10, để trống nếu chưa có):');
    const body = {version, title, content, model_name, tags, status:'draft'};
    if(score) body.score = parseFloat(score);
    await fetch('/api/dashboard/experiments',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
    load();
}

load();