/* ── OPC UA 서버 ─────────────────────────────────────────────── */
paneInit.opcsvr = srvLoad;

let _srvPollTimer = null;

async function srvLoad() {
  try {
    const s = await api('GET', '/api/opcserver/status');
    _srvRender(s);
  } catch (e) {
    srvLog([{ c:'err', t:`상태 조회 실패: ${e.message}` }]);
  }
}

async function srvStart() {
  srvLog([{ c:'info', t:'OPC UA 서버 시작 중...' }]);
  try {
    const r = await api('POST', '/api/opcserver/start');
    srvLog([{ c: r.success ? 'ok' : 'err', t: r.message }]);
    await srvLoad();
    _srvStartPoll();
  } catch (e) {
    srvLog([{ c:'err', t:`시작 실패: ${e.message}` }]);
  }
}

async function srvStop() {
  srvLog([{ c:'info', t:'OPC UA 서버 중지 중...' }]);
  try {
    const r = await api('POST', '/api/opcserver/stop');
    srvLog([{ c: r.success ? 'ok' : 'err', t: r.message }]);
    _srvStopPoll();
    await srvLoad();
  } catch (e) {
    srvLog([{ c:'err', t:`중지 실패: ${e.message}` }]);
  }
}

async function srvRebuild() {
  srvLog([{ c:'info', t:'주소 공간 재구성 중...' }]);
  try {
    const r = await api('POST', '/api/opcserver/rebuild');
    srvLog([{ c: r.success ? 'ok' : 'err', t: `재구성 완료 — ${r.nodeCount}개 노드` }]);
    await srvLoad();
  } catch (e) {
    srvLog([{ c:'err', t:`재구성 실패: ${e.message}` }]);
  }
}

function _srvRender(s) {
  const dot  = document.getElementById('srv-dot');
  const txt  = document.getElementById('srv-status-txt');
  const meta = document.getElementById('srv-meta');
  const ndot = document.getElementById('opcsvr-dot');

  if (s.running) {
    dot.className  = 'dot grn';
    txt.textContent = '● 실행 중';
    if (ndot) ndot.className = 'nb grn';
  } else {
    dot.className  = 'dot';
    txt.textContent = '○ 중지됨';
    if (ndot) ndot.className = 'nb';
  }

  const started = s.startedAt ? new Date(s.startedAt).toLocaleString('ko-KR') : '—';
  meta.innerHTML =
    `<span>엔드포인트: <b>${esc(s.endpointUrl || '—')}</b></span>` +
    `<span>접속 클라이언트: <b>${s.connectedClientCount}</b></span>` +
    `<span>노드 수: <b>${s.nodeCount}</b></span>` +
    `<span>시작 시각: <b>${started}</b></span>`;
}

function srvLog(lines) {
  log('srv-log', lines);
}

function _srvStartPoll() {
  _srvStopPoll();
  _srvPollTimer = setInterval(srvLoad, 5000);
}

function _srvStopPoll() {
  if (_srvPollTimer) { clearInterval(_srvPollTimer); _srvPollTimer = null; }
}
