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

async function evtLoadTags() {
  const statusEl = document.getElementById('evt-tag-status');
  statusEl.textContent = '⏳ 조회 중...';
  try {
    const d = await api('GET', '/api/event-history/digital-tags');
    const tags = d.data || [];
    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 params = new URLSearchParams();
  if (tag)       params.set('tagName',   tag);
  if (eventType) params.set('eventType', eventType);
  if (area)      params.set('area',      area);
  if (subArea)   params.set('subArea',   subArea);
  params.set('limit', limit);
  if (fromRaw) params.set('from', new Date(fromRaw).toISOString());
  if (toRaw)   params.set('to',   new Date(toRaw).toISOString());

  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('GET', `/api/event-history?${params}`);
    if (!d.success) throw new Error(d.error || '조회 실패');
    infoEl.textContent = `총 ${d.count}건`;
    tableEl.innerHTML = _evtBuildTable(d.data);
    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 params = new URLSearchParams();
  if (area)    params.set('area',    area);
  if (subArea) params.set('subArea', subArea);
  if (fromRaw) params.set('from', new Date(fromRaw).toISOString());
  if (toRaw)   params.set('to',   new Date(toRaw).toISOString());

  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('GET', `/api/event-history/summary?${params}`);
    if (!d.success) throw new Error(d.error || '조회 실패');
    content.innerHTML = _evtBuildSummary(d.data);
  } 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(data) {
  if (!data || !data.length)
    return '<div style="padding:12px;color:var(--t2)">데이터 없음</div>';
  return `<div class="evt-summary-grid">${data.map(s => `
    <div class="evt-summary-item">
      <div class="evt-summary-section">${esc(s.subArea)}</div>
      <div class="evt-summary-counts">
        <div class="evt-count">${_evtBadge('TRIP')} <strong>${s.tripCount}</strong></div>
        <div class="evt-count">${_evtBadge('RUN')} <strong>${s.runCount}</strong></div>
        <div class="evt-count">${_evtBadge('ALARM')} <strong>${s.alarmCount}</strong></div>
        <div class="evt-count">${_evtBadge('CHANGE')} <strong>${s.changeCount}</strong></div>
      </div>
      <div class="evt-total">합계 <strong>${s.totalEvents}</strong>건</div>
    </div>`).join('')}</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 = '';
}
