/* ==============================================
   Node Panel — Edit / Save
   ============================================== */
function editNode() {
  document.getElementById('np-edit-btn').style.display = 'none';
  document.getElementById('np-edit-actions').style.display = 'flex';
  document.querySelector('.np-content').style.display = 'none';
  document.querySelector('.np-title').style.display = 'none';
  document.getElementById('np-edit-fields').style.display = '';
  const labelInput = document.getElementById('np-title-input');
  labelInput.value = window._currentNodeLabel || '';
  labelInput.style.display = '';
  const contentEdit = document.getElementById('np-content-edit');
  contentEdit.value = window._currentNodeContent || '';
  contentEdit.style.display = '';

  // Populate type dropdown
  const typeSel = document.getElementById('np-edit-type');
  const types = [
    ['objective','测试目标'],['entry_point','攻击入口'],['vulnerability','漏洞'],['privilege_escalation','提权漏洞'],
    ['exploitation','漏洞利用'],['attack_step','攻击步骤'],['reconnaissance','信息收集'],
    ['exfiltration','数据外传'],['impact','影响评估'],['host','主机'],['service','服务'],['credential','凭据'],['finding','发现']
  ];
  typeSel.innerHTML = types.map(t => '<option value="'+t[0]+'"'+(t[0]===window._currentNodeType?' selected':'')+'>'+t[1]+'</option>').join('');
  // Set verdict/evidence defaults
  document.getElementById('np-edit-verdict').value = window._currentNodeVerdict || '';
  document.getElementById('np-edit-evidence').value = window._currentNodeEvidence || '';
}

function cancelEdit() {
  document.getElementById('np-edit-btn').style.display = '';
  document.getElementById('np-edit-actions').style.display = 'none';
  document.getElementById('np-edit-fields').style.display = 'none';
  document.querySelector('.np-content').style.display = '';
  document.querySelector('.np-title').style.display = '';
  document.getElementById('np-title-input').style.display = 'none';
  document.getElementById('np-content-edit').style.display = 'none';
}

async function saveNode() {
  const id = window._currentNodeId;
  if (!id || !currentProject) return;
  const label = document.getElementById('np-title-input').value.trim();
  const content = document.getElementById('np-content-edit').value;
  const nodeType = document.getElementById('np-edit-type').value;
  const verdict = document.getElementById('np-edit-verdict').value;
  const evidence = document.getElementById('np-edit-evidence').value;
  if (!label) { toast('节点名称不能为空'); return; }
  const props = { content: content || '' };
  if (verdict) props.verdict = verdict;
  if (evidence) props.evidence = evidence;
  const body = { label, node_type: nodeType, properties: props };
  try {
    const res = await fetch(API+'/projects/'+currentProject+'/nodes/'+id, {
      method: 'PUT',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify(body)
    });
    const j = await res.json();
    if (!j.success) { toast('保存失败: '+(j.error||'')); return; }
    cancelEdit();
    // Update the displayed content and title
    document.querySelector('.np-title').textContent = label;
    const md = content || '';
    const contentEl = document.querySelector('.np-content');
    if (!md.trim()) {
      contentEl.innerHTML = '<div class="np-empty"><div class="np-empty-icon">📝</div><p class="np-empty-title">尚未添加详细说明</p><p class="np-empty-hint">使用 CLI 的 <code>--content</code> 参数为节点添加 Markdown 文档</p></div>';
    } else {
      const html = marked && marked.parse ? marked.parse(md) : (md.replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g,'<br>'));
      contentEl.innerHTML = html;
      if (typeof hljs !== 'undefined') {
        contentEl.querySelectorAll('pre code').forEach(block => hljs.highlightElement(block));
      }
    }
    window._currentNodeLabel = label;
    window._currentNodeContent = md;
    // Update cy node label
    const node = cy.getElementById(id);
    if (node.length) { node.data('label', label); node.style('label', label); }
    toast('已保存');
  } catch(e) { toast('保存失败: '+e.message); }
}
