/* ─────────────────────────────────────────────────────────────
    05  노드맵 대시보드
───────────────────────────────────────────────────────────── */
let _nmOffset = 0;
let _nmTotal  = 0;
let _nmLimit  = 100;

// 이름 드롭다운 옵션만 필요할 때 수동으로 불러오는 함수 (버튼 클릭 시)
async function nmLoadNames() {
  try {
    const n = await api('GET', '/api/nodemap/names');
    const nameOpts = '<option value="">— 선택 안 함 —</option>' +
      (n.names||[]).map(nm => `<option value="${esc(nm)}">${esc(nm)}</option>`).join('');
    ['nf-name-1','nf-name-2','nf-name-3','nf-name-4'].forEach(id => {
      const el = document.getElementById(id);
      const cur = el.value;
      el.innerHTML = nameOpts;
      if (cur) el.value = cur;
    });
  } catch (e) { console.error('nmLoadNames:', e); }
}

async function nmQuery(offset) {
  _nmOffset = offset ?? 0;
  _nmLimit  = parseInt(document.getElementById('nf-limit').value) || 100;

  const params = new URLSearchParams();
  const lvMin  = document.getElementById('nf-lv-min').value.trim();
  const lvMax  = document.getElementById('nf-lv-max').value.trim();
  const cls    = document.getElementById('nf-class').value;
  const nid    = document.getElementById('nf-nid').value.trim();
  const dtype  = document.getElementById('nf-dtype').value.trim();
  const selNames = ['nf-name-1','nf-name-2','nf-name-3','nf-name-4']
    .map(id => document.getElementById(id).value)
    .filter(Boolean);

  if (lvMin)  params.set('minLevel',  lvMin);
  if (lvMax)  params.set('maxLevel',  lvMax);
  if (cls)    params.set('nodeClass', cls);
  selNames.forEach(nm => params.append('names', nm));
  if (nid)    params.set('nodeId',    nid);
  if (dtype)  params.set('dataType',  dtype);
  params.set('limit',  _nmLimit);
  params.set('offset', _nmOffset);

  setGlobal('busy', '조회 중');
  try {
    const d = await api('GET', `/api/nodemap/query?${params}`);
    _nmTotal = d.total;

    // 결과 바
    const bar = document.getElementById('nm-result-bar');
    bar.classList.remove('hidden');
    const from = _nmOffset + 1;
    const to   = Math.min(_nmOffset + _nmLimit, _nmTotal);
    document.getElementById('nm-result-info').textContent =
      `총 ${_nmTotal.toLocaleString()}건 중 ${from.toLocaleString()}–${to.toLocaleString()}건`;

    const totalPages = Math.ceil(_nmTotal / _nmLimit) || 1;
    const curPage    = Math.floor(_nmOffset / _nmLimit) + 1;
    document.getElementById('nm-pg-info').textContent = `${curPage} / ${totalPages} 페이지`;
    document.getElementById('nm-pg-prev').disabled = _nmOffset === 0;
    document.getElementById('nm-pg-next').disabled = to >= _nmTotal;

    // 테이블 렌더
    const tbl = document.getElementById('nm-table');
    tbl.classList.remove('hidden');
    if (d.items?.length) {
      tbl.innerHTML = `
        <table>
          <thead>
            <tr>
              <th>ID</th><th>Level</th><th>Class</th>
              <th>Name</th><th>Node ID</th><th>Data Type</th>
            </tr>
          </thead>
          <tbody>
            ${d.items.map(r => `
              <tr>
                <td class="mut" style="font-size:11px">${r.id}</td>
                <td class="mono" style="text-align:center">${r.level}</td>
                <td><span class="nm-cls nm-cls-${(r.class||'').toLowerCase()}">${esc(r.class)}</span></td>
                <td>${esc(r.name)}</td>
                <td class="mut" style="font-size:11px;font-family:var(--fm)">${esc(r.nodeId)}</td>
                <td><span class="nm-dtype">${esc(r.dataType)}</span></td>
              </tr>
            `).join('')}
          </tbody>
        </table>
      `;
    } else {
      tbl.innerHTML = '<div style="padding:20px;color:var(--t2)">조건에 맞는 노드가 없습니다.</div>';
    }
    setGlobal('ok', `${_nmTotal.toLocaleString()}건`);
  } catch (e) {
    setGlobal('err', '조회 실패');
    console.error('nmQuery:', e);
  }
}

function nmPrev() {
  if (_nmOffset > 0) nmQuery(Math.max(0, _nmOffset - _nmLimit));
}
function nmNext() {
  if (_nmOffset + _nmLimit < _nmTotal) nmQuery(_nmOffset + _nmLimit);
}
function nmReset() {
  document.getElementById('nf-lv-min').value = '';
  document.getElementById('nf-lv-max').value = '';
  document.getElementById('nf-class').value  = '';
  document.getElementById('nf-nid').value    = '';
  document.getElementById('nf-dtype').value  = '';
  document.getElementById('nf-limit').value  = '100';
  ['nf-name-1','nf-name-2','nf-name-3','nf-name-4'].forEach(id => {
    document.getElementById(id).value = '';
  });
  // 초기화 후 자동 조회 없음
  document.getElementById('nm-result-bar').classList.add('hidden');
  document.getElementById('nm-table').classList.add('hidden');
}
