/* ─────────────────────────────────────────────────────────────
    12  이벤트 히스토리
───────────────────────────────────────────────────────────── */

async function evtLoadTags() {
  const statusEl = document.getElementById('evt-tag-status');
  statusEl.textContent = '⏳ 조회 중...';
  try {
    const pts = await api('GET', '/api/realtime/points');
    const tags = pts.filter(p => (p.LiveValue ?? '').startsWith('{'));
    const sel = document.getElementById('ef-tag');
    sel.innerHTML = '<option value="">— 전체 태그 —</option>' +
      tags.map(t => `<option value="${esc(t.TagName)}">${esc(t.TagName)}</option>`).join('');
    statusEl.textContent = `✅ ${tags.length}개`;
  } catch (e) {
    statusEl.textContent = `❌ ${e.message}`;
  }
}

async function evtQuery() {
  const tag       = document.getElementById('ef-tag').value;
  const eventType = document.getElementById('ef-event-type').value;
  const area      = document.getElementById('ef-area').value.trim();
  const subArea   = document.getElementById('ef-subarea').value.trim();
  const limit     = document.getElementById('ef-limit').value || 500;
  const fromRaw   = document.getElementById('hf-evt-from').value;
  const toRaw     = document.getElementById('hf-evt-to').value;

  const body = {
    tagName:   tag    || null,
    eventType: eventType || null,
    area:      area   || null,
    subArea:   subArea   || null,
    limit:     parseInt(limit),
    from:      fromRaw ? new Date(fromRaw).toISOString() : null,
    to:        toRaw   ? new Date(toRaw).toISOString()   : null
  };

  const infoEl  = document.getElementById('evt-result-info');
  const tableEl = document.getElementById('evt-table');
  infoEl.textContent = '⏳ 조회 중...';
  infoEl.classList.remove('hidden');
  tableEl.classList.add('hidden');

  try {
    const d = await api('POST', '/api/events/query', body);
    infoEl.textContent = `총 ${d.length}건`;
    tableEl.innerHTML = _evtBuildTable(d);
    tableEl.classList.remove('hidden');
  } catch (e) {
    infoEl.textContent = `❌ ${e.message}`;
  }
}

async function evtSummary() {
  const area    = document.getElementById('ef-area').value.trim();
  const subArea = document.getElementById('ef-subarea').value.trim();
  const fromRaw = document.getElementById('hf-evt-from').value;
  const toRaw   = document.getElementById('hf-evt-to').value;

  const card    = document.getElementById('evt-summary-card');
  const content = document.getElementById('evt-summary-content');
  content.textContent = '⏳ 집계 중...';
  card.classList.remove('hidden');

  try {
    const d = await api('POST', '/api/events/query', {
      area: area || null, subArea: subArea || null,
      from: fromRaw ? new Date(fromRaw).toISOString() : null,
      to: toRaw ? new Date(toRaw).toISOString() : null,
      limit: 500
    });
    const byType = {};
    d.forEach(r => { byType[r.EventType] = (byType[r.EventType] || 0) + 1; });
    content.innerHTML = _evtBuildSummary(byType, d.length);
  } catch (e) {
    content.textContent = `❌ ${e.message}`;
  }
}

function _evtBadge(t) {
  const cls = { TRIP:'trip', RUN:'run', ALARM:'alarm', NORMAL:'normal', CHANGE:'change' }[t] || 'change';
  return `<span class="evt-badge ${cls}">${esc(t)}</span>`;
}

function _evtFmtTime(dt) {
  if (!dt) return '—';
  return new Date(dt).toLocaleString('ko-KR', {
    year:'numeric', month:'2-digit', day:'2-digit',
    hour:'2-digit', minute:'2-digit', second:'2-digit', hour12:false
  });
}

function _evtBuildTable(rows) {
  if (!rows || !rows.length)
    return '<div style="padding:24px;text-align:center;color:var(--t2)">데이터 없음</div>';
  const html = rows.map(r => `
    <tr>
      <td style="white-space:nowrap;color:var(--t2);font-family:var(--fm);font-size:11px">${_evtFmtTime(r.EventTime)}</td>
      <td><code style="font-size:11px;color:var(--blu)">${esc(r.TagName)}</code></td>
      <td>${_evtBadge(r.EventType)}</td>
      <td style="color:var(--t2)">${esc(r.PrevValue ?? '—')}</td>
      <td style="color:var(--t0);font-weight:600">${esc(r.CurrValue)}</td>
      <td>${r.Area    ? `<span class="nm-cls">${esc(r.Area)}</span>`    : '—'}</td>
      <td>${r.SubArea ? `<span class="nm-cls">${esc(r.SubArea)}</span>` : '—'}</td>
      <td style="font-family:var(--fm);font-size:11px;color:var(--t2)">${r.DurationSeconds != null ? r.DurationSeconds + 's' : '—'}</td>
    </tr>`).join('');
  return `
    <table>
      <thead><tr>
        <th>시간</th>
        <th>태그명</th>
        <th>이벤트</th>
        <th>이전값</th>
        <th>현재값</th>
        <th>Area</th>
        <th>Sub Area</th>
        <th>지속(초)</th>
      </tr></thead>
      <tbody>${html}</tbody>
    </table>`;
}

function _evtBuildSummary(byType, total) {
  const keys = ['TRIP', 'RUN', 'ALARM', 'CHANGE', 'NORMAL'];
  const html = keys.map(k => byType[k]
    ? `<span style="margin-right:12px">${_evtBadge(k)} <strong>${byType[k]}</strong></span>`
    : '').join('');
  return `<div style="padding:12px">${html}<hr style="margin:8px 0;border-color:var(--bd)"/>합계 <strong>${total}</strong>건</div>`;
}

function evtReset() {
  document.getElementById('ef-tag').value        = '';
  document.getElementById('ef-event-type').value = '';
  document.getElementById('ef-area').value        = '';
  document.getElementById('ef-subarea').value     = '';
  document.getElementById('ef-limit').value       = '500';
  dtClearField('evt-from');
  dtClearField('evt-to');
  document.getElementById('evt-result-info').classList.add('hidden');
  document.getElementById('evt-table').classList.add('hidden');
  document.getElementById('evt-summary-card').classList.add('hidden');
  document.getElementById('evt-tag-status').textContent = '';
}
