// ══════════════════════════════════════════════════════
// STATE
// ══════════════════════════════════════════════════════
let testCases = []
let results = []
let running = false
let stopFlag = false

const STORAGE_KEY = 'regression_test_cases'
const DEFAULT_CASES = [
  "Toi muon mua ao di lam, khong biet chon mau gi?",
  "Shop co vay du tiec khong?",
  "Ngan sach 500k mua duoc gi?",
  "Co ao polo nam size XL khong?",
  "Gia ao khoac mua dong bao nhieu?",
  "Co chuong trinh khuyen mai gi khong?",
  "Giao hang mat bao lau?",
  "Chinh sach doi tra the nao?",
  "Toi muon mua quan jeans nu",
  "Size chart cua Canifa nhu the nao?",
]

// ══════════════════════════════════════════════════════
// INIT
// ══════════════════════════════════════════════════════
function init() {
  const saved = localStorage.getItem(STORAGE_KEY)
  if (saved) {
    try { testCases = JSON.parse(saved) } catch { testCases = [] }
  }
  if (!testCases.length) {
    testCases = DEFAULT_CASES.map((q, i) => ({ id: Date.now() + i, question: q }))
  }
  renderAll()
}

function save() { localStorage.setItem(STORAGE_KEY, JSON.stringify(testCases)) }

// ══════════════════════════════════════════════════════
// RENDER
// ══════════════════════════════════════════════════════
function renderAll() {
  renderTestCases()
  renderTopBtns()
  renderResults()
  save()
}

function renderTestCases() {
  document.getElementById('tcCount').textContent = testCases.length
  const el = document.getElementById('tcBody')
  if (!testCases.length) {
    el.innerHTML = '<p style="text-align:center;color:#8D6E63;font-size:12px;padding:20px">Chua co test case. Bam "+ Them" de tao.</p>'
    return
  }
  el.innerHTML = `<table class="tc-table">
    <thead><tr><th style="width:40px">#</th><th>Cau hoi</th><th style="width:60px"></th></tr></thead>
    <tbody>${testCases.map((tc, i) => `
      <tr>
        <td style="font-family:monospace;color:#8D6E63;font-size:12px">${i + 1}</td>
        <td><input class="tc-input" value="${escHtml(tc.question)}" onchange="updateCase(${tc.id}, this.value)" placeholder="Nhap cau hoi..."></td>
        <td><button class="btn btn-del btn-sm" onclick="deleteCase(${tc.id})">x</button></td>
      </tr>
    `).join('')}</tbody>
  </table>`
}

function renderTopBtns() {
  const el = document.getElementById('topBtns')
  if (running) {
    el.innerHTML = `<button class="btn btn-stop" onclick="stopRun()">Stop</button>`
  } else {
    el.innerHTML = `<button class="btn btn-run" onclick="runAll()" ${testCases.length === 0 ? 'disabled' : ''}>Run All (${testCases.length})</button>`
  }
}

function renderResults() {
  if (!results.length) {
    document.getElementById('resultsSection').style.display = 'none'
    document.getElementById('stats').style.display = 'none'
    return
  }
  document.getElementById('resultsSection').style.display = ''
  document.getElementById('stats').style.display = 'flex'

  const ok = results.filter(r => r.status === 'success').length
  const fail = results.filter(r => r.status === 'error').length
  const latencies = results.filter(r => r.latency_ms).map(r => r.latency_ms)
  const avgMs = latencies.length ? Math.round(latencies.reduce((s,v)=>s+v,0) / latencies.length) : null

  document.getElementById('statTotal').textContent = results.length
  document.getElementById('statPass').textContent = ok
  document.getElementById('statFail').textContent = fail
  document.getElementById('statAvgMs').textContent = avgMs ? avgMs + 'ms' : '—'

  const el = document.getElementById('resultsList')
  el.innerHTML = results.map((r, i) => `
    <div class="result-row ${r.status === 'error' ? 'error' : ''}">
      <div class="result-header" onclick="toggleResult(${i})">
        <div class="result-num ${r.status === 'success' ? 'ok' : 'err'}">${i + 1}</div>
        <div class="result-question">${escHtml(r.question)}</div>
        ${r.latency_ms ? `<div class="result-latency">${Math.round(r.latency_ms)}ms</div>` : ''}
        <div style="font-size:11px;color:${r.status === 'success' ? '#059669' : '#DC2626'};font-weight:700">${r.status === 'success' ? 'OK' : 'FAIL'}</div>
        <div style="font-size:14px;color:#8D6E63;transition:transform .15s" id="arrow-${i}">&#9660;</div>
      </div>
      <div class="result-body" id="body-${i}">
        <div class="result-response">${escHtml(r.response)}</div>
        ${r.trace_id ? `<p style="font-size:10px;color:#8D6E63;margin-top:6px;font-family:monospace">trace: ${r.trace_id}</p>` : ''}
      </div>
    </div>
  `).join('')
}

// ══════════════════════════════════════════════════════
// TEST CASE MANAGEMENT
// ══════════════════════════════════════════════════════
function addCase() {
  testCases.push({ id: Date.now(), question: '' })
  renderAll()
  // Focus the new input
  setTimeout(() => {
    const inputs = document.querySelectorAll('.tc-input')
    if (inputs.length) inputs[inputs.length - 1].focus()
  }, 50)
}

function updateCase(id, val) {
  testCases = testCases.map(tc => tc.id === id ? { ...tc, question: val } : tc)
  save()
}

function deleteCase(id) {
  testCases = testCases.filter(tc => tc.id !== id)
  renderAll()
}

function exportCases() {
  const blob = new Blob([JSON.stringify(testCases, null, 2)], { type: 'application/json' })
  const a = document.createElement('a')
  a.href = URL.createObjectURL(blob)
  a.download = `test-cases-${new Date().toISOString().slice(0,10)}.json`
  a.click()
}

function importCases() {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.json'
  input.onchange = async e => {
    try {
      const text = await e.target.files[0].text()
      const data = JSON.parse(text)
      if (Array.isArray(data)) {
        testCases = data.map((item, i) => ({
          id: Date.now() + i,
          question: typeof item === 'string' ? item : item.question || ''
        }))
        renderAll()
      }
    } catch (err) { alert('Invalid JSON file') }
  }
  input.click()
}

// ══════════════════════════════════════════════════════
// URL PRESETS
// ══════════════════════════════════════════════════════
function setUrl(el, url) {
  document.getElementById('targetUrl').value = url
  document.querySelectorAll('.preset-chip').forEach(c => c.classList.remove('active'))
  el.classList.add('active')
}

// ══════════════════════════════════════════════════════
// RUN TESTS
// ══════════════════════════════════════════════════════
async function runAll() {
  if (running) return
  const url = document.getElementById('targetUrl').value.trim()
  if (!url) { alert('Nhap target URL truoc'); return }

  const validCases = testCases.filter(tc => tc.question.trim())
  if (!validCases.length) { alert('Chua co test case nao'); return }

  running = true; stopFlag = false; results = []
  document.getElementById('progressSection').style.display = ''
  renderTopBtns(); renderResults()

  for (let i = 0; i < validCases.length; i++) {
    if (stopFlag) break

    const tc = validCases[i]
    const pct = ((i + 1) / validCases.length * 100).toFixed(0)
    document.getElementById('progressLabel').textContent = `Testing #${i + 1}: "${tc.question.slice(0, 50)}..."`
    document.getElementById('progressCount').textContent = `${i + 1}/${validCases.length}`
    document.getElementById('progressFill').style.width = pct + '%'

    try {
      const start = Date.now()
      const resp = await fetch('/api/regression-test/run', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          target_url: url,
          test_cases: [{ id: tc.id, question: tc.question }],
          timeout: 60
        })
      })
      const data = await resp.json()
      if (data.results?.length) {
        results.push(data.results[0])
      }
    } catch (e) {
      results.push({ id: tc.id, question: tc.question, status: 'error', response: e.message, trace_id: '', latency_ms: null })
    }

    renderResults()
  }

  document.getElementById('progressSection').style.display = 'none'
  document.getElementById('progressLabel').textContent = 'Done!'
  running = false; stopFlag = false
  renderAll()
}

function stopRun() {
  stopFlag = true; running = false
  document.getElementById('progressSection').style.display = 'none'
  renderAll()
}

// ══════════════════════════════════════════════════════
// RESULT EXPAND/COLLAPSE
// ══════════════════════════════════════════════════════
function toggleResult(i) {
  const body = document.getElementById('body-' + i)
  const arrow = document.getElementById('arrow-' + i)
  if (body.classList.contains('open')) {
    body.classList.remove('open')
    arrow.style.transform = 'rotate(0deg)'
  } else {
    body.classList.add('open')
    arrow.style.transform = 'rotate(180deg)'
  }
}

function expandAll() {
  results.forEach((_, i) => {
    document.getElementById('body-' + i)?.classList.add('open')
    const a = document.getElementById('arrow-' + i); if (a) a.style.transform = 'rotate(180deg)'
  })
}

function collapseAll() {
  results.forEach((_, i) => {
    document.getElementById('body-' + i)?.classList.remove('open')
    const a = document.getElementById('arrow-' + i); if (a) a.style.transform = 'rotate(0deg)'
  })
}

// ══════════════════════════════════════════════════════
// HELPERS
// ══════════════════════════════════════════════════════
function escHtml(s) { const d = document.createElement('div'); d.textContent = s || ''; return d.innerHTML }

// ══════════════════════════════════════════════════════
// INIT
// ══════════════════════════════════════════════════════
init()