/* ─────────────────────────────────────────────────────────────
   15  OPC UA Write
───────────────────────────────────────────────────────────── */
async function wrWriteTag() {
  const nodeId = document.getElementById('wr-nodeid').value.trim();
  const value = parseFloat(document.getElementById('wr-value').value);
  if (!nodeId) return log('wr-log', [{ c: 'err', t: '❌ Node ID를 입력하세요.' }]);
  if (isNaN(value)) return log('wr-log', [{ c: 'err', t: '❌ 유효한 숫자를 입력하세요.' }]);

  try {
    const d = await api('POST', '/api/points/write', { nodeId, value });
    log('wr-log', [
      { c: d.success ? 'ok' : 'err', t: (d.success ? '✅ ' : '❌ ') + 'Write ' + esc(nodeId) + ' = ' + value + ' → ' + esc(d.status) },
      ...(d.error ? [{ c: 'err', t: '   Error: ' + esc(d.error) }] : [])
    ]);
  } catch (e) {
    log('wr-log', [{ c: 'err', t: '❌ ' + e.message }]);
  }
}

async function wrSetMode() {
  const nodeId = document.getElementById('wr-mode-nodeid').value.trim();
  const mode = document.getElementById('wr-mode').value;
  if (!nodeId) return log('wr-log', [{ c: 'err', t: '❌ Node ID를 입력하세요.' }]);

  try {
    const d = await api('POST', '/api/points/mode', { nodeId, mode });
    log('wr-log', [
      { c: d.success ? 'ok' : 'err', t: (d.success ? '✅ ' : '❌ ') + 'Mode ' + esc(nodeId) + ' → ' + mode + ' (enum=' + d.enumValue + ') ' + esc(d.status) },
      ...(d.error ? [{ c: 'err', t: '   Error: ' + esc(d.error) }] : [])
    ]);
  } catch (e) {
    log('wr-log', [{ c: 'err', t: '❌ ' + e.message }]);
  }
}

async function wrControlOp() {
  const tagName = document.getElementById('wr-ctrl-tag').value.trim();
  const opValue = parseFloat(document.getElementById('wr-ctrl-op').value);
  const restoreAuto = document.getElementById('wr-ctrl-restore').checked;
  if (!tagName) return log('wr-log', [{ c: 'err', t: '❌ 태그명을 입력하세요.' }]);
  if (isNaN(opValue)) return log('wr-log', [{ c: 'err', t: '❌ 유효한 OP 값을 입력하세요.' }]);

  try {
    const d = await api('POST', '/api/points/control', { tagName, opValue, restoreAuto });
    const lines = [];
    if (d.steps) {
      for (const s of d.steps) {
        lines.push({ c: s.success ? 'ok' : 'err', t: (s.success ? '✅ ' : '❌ ') + s.step + ': ' + esc(s.nodeId) + ' → ' + esc(s.status) + (s.value !== undefined ? ' (value=' + s.value + ')' : '') });
        if (s.error) lines.push({ c: 'err', t: '   Error: ' + esc(s.error) });
      }
    }
    lines.unshift({ c: d.success ? 'ok' : 'err', t: (d.success ? '✅ ' : '❌ ') + '통합 제어 ' + esc(tagName) + ' OP=' + opValue + (d.error ? ' — ' + esc(d.error) : '') });
    log('wr-log', lines);
  } catch (e) {
    log('wr-log', [{ c: 'err', t: '❌ ' + e.message }]);
  }
}

async function wrReadTag() {
  const nodeId = document.getElementById('wr-read-nodeid').value.trim();
  if (!nodeId) return;

  try {
    const d = await api('POST', '/api/points/read', { nodeId });
    const box = document.getElementById('wr-read-result');
    if (d.success) {
      box.innerHTML = `
        <div class="kv"><span class="kk">Node ID</span><span class="kv2">${esc(d.nodeId)}</span></div>
        <div class="kv"><span class="kk">Value</span><span class="kv2 ok">${esc(d.value)}</span></div>
        <div class="kv"><span class="kk">Status</span><span class="kv2">${esc(d.statusCode)}</span></div>
        <div class="kv"><span class="kk">Timestamp</span><span class="kv2">${d.timestamp ? new Date(d.timestamp).toLocaleString('ko-KR') : '-'}</span></div>
      `;
    } else {
      box.innerHTML = `<div class="kv"><span class="kk">Error</span><span class="kv2 err">${esc(d.error || 'Unknown')}</span></div>`;
    }
  } catch (e) {
    document.getElementById('wr-read-result').innerHTML = `<div class="kv"><span class="kk">Error</span><span class="kv2 err">${esc(e.message)}</span></div>`;
  }
}
