let allRows = [];
let activeFilter = 'all';

async function loadData() {
  const limit = document.getElementById('limitSelect').value;
  document.getElementById('tableBody').innerHTML =
    '<tr><td colspan="8"><div class="empty-state"><div class="icon spin">⏳</div><div>Loading from Postgres…</div></div></td></tr>';

  try {
    const res = await fetch(`/api/lead/dashboard?limit=${limit}`);
    const data = await res.json();
    allRows = data.data || [];
    updateStats(allRows);
    applyFilter();
    document.getElementById('lastRefresh').textContent = '↺ ' + new Date().toLocaleTimeString('vi-VN');
  } catch (e) {
    document.getElementById('tableBody').innerHTML =
      `<tr><td colspan="8"><div class="empty-state"><div class="icon">❌</div><div>${e.message}</div></div></td></tr>`;
  }
}

function updateStats(rows) {
  const convs = new Set(rows.map(r => r.conv_id)).size;
  const devices = new Set(rows.map(r => r.device_id)).size;
  const aiCount = rows.filter(r => !r.is_human).length;
  document.getElementById('statTotal').textContent = rows.length;
  document.getElementById('statConvs').textContent = convs;
  document.getElementById('statDevices').textContent = devices;
  document.getElementById('statAI').textContent = aiCount;
}

function setFilter(f) {
  activeFilter = f;
  ['fAll','fHuman','fAI'].forEach(id => document.getElementById(id).classList.remove('active'));
  document.getElementById(f === 'all' ? 'fAll' : f === 'human' ? 'fHuman' : 'fAI').classList.add('active');
  applyFilter();
}

function applyFilter() {
  const q = document.getElementById('searchInput').value.toLowerCase();
  let rows = allRows;

  if (activeFilter === 'human') rows = rows.filter(r => r.is_human);
  if (activeFilter === 'ai') rows = rows.filter(r => !r.is_human);
  if (q) {
    rows = rows.filter(r =>
      (r.message || '').toLowerCase().includes(q) ||
      (r.conv_id || '').toLowerCase().includes(q) ||
      (r.device_id || '').toLowerCase().includes(q)
    );
  }

  renderTable(rows);
}

function renderTable(rows) {
  if (!rows.length) {
    document.getElementById('tableBody').innerHTML =
      '<tr><td colspan="8"><div class="empty-state"><div class="icon">📭</div><div>Không có dữ liệu</div></div></td></tr>';
    return;
  }

  const html = rows.map(r => {
    const isHuman = r.is_human;
    const badge = isHuman
      ? '<span class="badge badge-human">👤 Human</span>'
      : '<span class="badge badge-ai">🤖 AI</span>';

    // Parse message to get ai_response text (for AI rows)
    let displayMsg = r.message || '';
    let productCount = 0;
    let stageName = '—';

    if (!isHuman) {
      try {
        const parsed = JSON.parse(displayMsg);
        displayMsg = parsed.ai_response || displayMsg;
        productCount = Array.isArray(parsed.products) ? parsed.products.length : 0;
        const ls = parsed.lead_stage || {};
        stageName = ls.stage_name || ls.stage || (typeof ls === 'string' ? ls : '—');
      } catch (_) {
        // already plain text
      }
    }

    const shortConv = (r.conv_id || '').slice(0, 8) + '…';
    const shortDev = (r.device_id || '').slice(-8);
    const msgPreview = displayMsg.slice(0, 90) + (displayMsg.length > 90 ? '…' : '');
    const ts = r.created_at ? new Date(r.created_at).toLocaleString('vi-VN', {
      month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit'
    }) : '—';

    return `<tr>
      <td style="font-family:monospace;font-size:11px;color:var(--muted)">#${r.id}</td>
      <td>${badge}</td>
      <td>
        <span class="conv-id" title="${r.conv_id}" onclick="filterByConv('${r.conv_id}')">${shortConv}</span>
      </td>
      <td><span style="font-family:monospace;font-size:11px;color:var(--muted)">…${shortDev}</span></td>
      <td>
        <div class="msg-text" title="Click để xem đầy đủ" onclick="showDetail(${r.id})"
             style="cursor:pointer;max-width:420px">${escHtml(msgPreview)}</div>
      </td>
      <td>${productCount > 0 ? `<span class="product-count">📦 ${productCount}</span>` : '<span style="color:var(--muted)">—</span>'}</td>
      <td>${stageName !== '—' ? `<span class="badge badge-stage">${stageName}</span>` : '<span style="color:var(--muted)">—</span>'}</td>
      <td><span class="ts">${ts}</span></td>
    </tr>`;
  }).join('');

  document.getElementById('tableBody').innerHTML = html;
}

function filterByConv(convId) {
  document.getElementById('searchInput').value = convId;
  applyFilter();
}

function showDetail(rowId) {
  const row = allRows.find(r => r.id === rowId);
  if (!row) return;

  let content = row.message || '';
  try {
    const parsed = JSON.parse(content);
    content = JSON.stringify(parsed, null, 2);
  } catch (_) {}

  document.getElementById('modalTitle').textContent = (row.is_human ? '👤 Human' : '🤖 AI') + ` — msg #${rowId}`;
  document.getElementById('modalContent').textContent = content;
  document.getElementById('modalOverlay').classList.add('show');
}

function closeModal(e) {
  if (e.target === document.getElementById('modalOverlay')) {
    document.getElementById('modalOverlay').classList.remove('show');
  }
}

function escHtml(s) {
  return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

// Auto-refresh every 30s
loadData();
setInterval(loadData, 30000);