async function runStress() {
  const url = document.getElementById('cfgUrl').value.trim()
  const total = parseInt(document.getElementById('cfgTotal').value) || 20
  const concurrent = parseInt(document.getElementById('cfgConcurrent').value) || 5
  const qStr = document.getElementById('cfgQuestions').value.trim()
  const questions = qStr.split('\n').map(q => q.trim()).filter(q => q)

  if (!url) return alert("Nhập URL")
  if (!questions.length) return alert("Nhập ít nhất 1 câu hỏi")

  const btn = document.getElementById('btnRun')
  const prog = document.getElementById('progressWrap')
  const resCard = document.getElementById('resultsCard')

  btn.disabled = true
  btn.textContent = "ĐANG CHẠY..."
  prog.style.display = "block"
  resCard.style.opacity = "0.4"
  resCard.style.pointerEvents = "none"

  document.getElementById('progressText').textContent = `Đang bắn ${concurrent} req cùng lúc (tổng: ${total})...`

  try {
    const resp = await fetch('/api/stress-test/run', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ target_url: url, total, concurrent, questions })
    })

    const data = await resp.json()
    if (data.status === 'success') {
      renderResults(data)
    } else {
      alert("Lỗi: " + data.message)
    }
  } catch (e) {
    alert("Lỗi kết nối: " + e.message)
  }

  btn.disabled = false
  btn.textContent = "BẮN TEST 🔥"
  prog.style.display = "none"
  resCard.style.opacity = "1"
  resCard.style.pointerEvents = "auto"
}

function renderResults(data) {
  const s = data.stats
  document.getElementById('rTotal').textContent = s.total
  document.getElementById('rRps').textContent = s.rps

  const errEl = document.getElementById('rErr')
  errEl.textContent = s.error_rate + '%'
  if (s.error_rate > 0) {
    errEl.style.color = '#DC2626'
    document.getElementById('boxErr').style.background = '#FEF2F2'
  } else {
    errEl.style.color = '#059669'
    document.getElementById('boxErr').style.background = '#F0FDF4'
    document.getElementById('boxErr').style.borderColor = '#A7F3D0'
  }

  document.getElementById('lAvg').textContent = s.avg_ms ? s.avg_ms + 'ms' : '—'
  document.getElementById('lMin').textContent = s.min_ms ? s.min_ms + 'ms' : '—'
  document.getElementById('lMax').textContent = s.max_ms ? s.max_ms + 'ms' : '—'
  document.getElementById('lP95').textContent = s.p95_ms ? s.p95_ms + 'ms' : '—'

  const tbody = document.getElementById('resBody')
  tbody.innerHTML = data.results.map(r => `
    <tr>
      <td style="font-family:monospace;font-weight:700">#${r.id}</td>
      <td style="font-family:monospace;color:#991b1b">${r.latency_ms||0}</td>
      <td><span class="${r.status==='success'?'status-ok':'status-err'}">${r.status==='success'?200:r.status_code}</span></td>
      <td style="max-width:200px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${esc(r.question)}</td>
      <td style="max-width:300px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-family:monospace">${esc(r.response_preview)}</td>
    </tr>
  `).join('')
}

function esc(s) { const d=document.createElement('div'); d.textContent=s||''; return d.innerHTML}