/* ═══════════════════════════════════════════════════════════════════
   Analysis Modal
   ═══════════════════════════════════════════════════════════════════ */
function showAnalysis(ai) {
  if (!currentProject) return;
  var overlay = document.getElementById('analysis-overlay');
  var content = document.getElementById('analysis-content');
  var label = ai ? 'AI 分析中…' : '加载中…';
  content.innerHTML =
    '<div class="analysis-skeleton">' +
      '<div class="skeleton-line"></div>' +
      '<div class="skeleton-line"></div>' +
      '<div class="skeleton-line"></div>' +
      '<div class="skeleton-line"></div>' +
      '<div class="skeleton-line"></div>' +
      '<div class="skeleton-line"></div>' +
    '</div>';
  overlay.classList.add('active');
  var url = API + '/projects/' + currentProject + '/analysis' + (ai ? '?ai=true' : '');
  fetch(url)
    .then(function(r) { return r.json(); })
    .then(function(j) {
      if (!j.success) {
        content.innerHTML = '<p style="color:var(--danger)">分析失败: ' + escHtml(j.error) + '</p>';
        return;
      }
      var d = j.data;
      var paths = d.attack_paths || [];
      var vulns = d.unexploited_vulns || [];
      var deads = d.dead_ends || [];
      var nexts = d.next_steps || [];
      var crosses = d.cross_connections || [];
      var total = paths.length + vulns.length + deads.length + nexts.length + crosses.length;

      if (total === 0) {
        content.innerHTML =
          '<div class="analysis-empty">' +
            '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">' +
              '<circle cx="12" cy="12" r="10"/>' +
              '<path d="M8 15h8"/>' +
              '<circle cx="9" cy="9" r="1" fill="currentColor" stroke="none"/>' +
              '<circle cx="15" cy="9" r="1" fill="currentColor" stroke="none"/>' +
            '</svg>' +
            '<div class="empty-title">暂无分析结果</div>' +
            '<div class="empty-desc">在攻击图中添加节点和连线后，点击分析按钮查看攻击路径、漏洞利用建议和跨分支关联。</div>' +
          '</div>';
        return;
      }

      var html = '';

      /* ── stats bar ─────────────────────────────── */
      html += '<div class="analysis-stats">';
      html += buildStatCard('paths', paths.length, '攻击路径',
        '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>');
      html += buildStatCard('vulns', vulns.length, '未利用漏洞',
        '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>');
      html += buildStatCard('dead', deads.length, '死路',
        '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>');
      html += buildStatCard('suggest', nexts.length, '下一步建议',
        '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>');
      html += buildStatCard('cross', crosses.length, '跨分支关联',
        '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>');
      html += '</div>';

      /* ── attack paths ──────────────────────────── */
      if (paths.length) {
        html += '<div class="analysis-section">';
        html += buildSectionToggle('attack-paths',
          '<svg class="section-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>',
          '攻击路径', paths.length);
        html += '<div class="section-body" id="section-attack-paths">';
        paths.forEach(function(p) {
          html += '<div class="path-flow">';
          var nodes = p.nodes || [];
          var edges = p.edge_labels || [];
          for (var i = 0; i < nodes.length; i++) {
            html += '<span class="path-step">';
            html += '<span class="path-badge">' + (i + 1) + '</span>';
            html += '<span class="path-label">' + escHtml(nodes[i].label) + '</span>';
            html += '</span>';
            if (i < edges.length) {
              html += '<span class="path-arrow"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg></span>';
              if (edges[i]) {
                html += '<span class="path-edge-label">' + escHtml(edges[i]) + '</span>';
                html += '<span class="path-arrow"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg></span>';
              }
            }
          }
          html += '</div>';
        });
        html += '</div></div>';
      }

      /* ── unexploited vulns ─────────────────────── */
      if (vulns.length) {
        html += '<div class="analysis-section">';
        html += buildSectionToggle('vulns',
          '<svg class="section-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
          '未利用漏洞', vulns.length);
        html += '<div class="section-body" id="section-vulns">';
        vulns.forEach(function(v) {
          html += '<div class="analysis-item vuln">';
          html += '<div class="item-header">';
          html += '<span class="label">' + escHtml(v.label) + '</span>';
          if (v.node_type) html += '<span class="type-badge">' + escHtml(v.node_type) + '</span>';
          html += '</div>';
          html += '</div>';
        });
        html += '</div></div>';
      }

      /* ── dead ends ─────────────────────────────── */
      if (deads.length) {
        html += '<div class="analysis-section">';
        html += buildSectionToggle('dead-ends',
          '<svg class="section-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>',
          '死路', deads.length);
        html += '<div class="section-body" id="section-dead-ends">';
        html += '<div class="section-desc">以下攻击路径已确认失败，需要寻找替代方案。</div>';
        deads.forEach(function(dd) {
          html += '<div class="analysis-item dead">';
          html += '<div class="item-header">';
          html += '<span class="label">' + escHtml(dd.label) + '</span>';
          if (dd.node_type) html += '<span class="type-badge">' + escHtml(dd.node_type) + '</span>';
          html += '</div>';
          html += '<div class="hint">verdict: failed</div>';
          html += '</div>';
        });
        html += '</div></div>';
      }

      /* ── next steps ────────────────────────────── */
      if (nexts.length) {
        html += '<div class="analysis-section">';
        html += buildSectionToggle('next-steps',
          '<svg class="section-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>',
          '下一步建议', nexts.length);
        html += '<div class="section-body" id="section-next-steps">';
        nexts.forEach(function(n) {
          var isAI = n.node_id && String(n.node_id).indexOf('ai-') === 0;
          html += '<div class="analysis-item next' + (isAI ? ' ai-suggestion' : '') + '">';
          html += '<div class="item-header">';
          html += '<span class="label">' + escHtml(n.label) + '</span>';
          if (isAI) {
            html += '<span class="ai-badge"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a4 4 0 0 1 4 4c0 1.95-1.4 3.58-3.25 3.93L12 22"/><path d="M12 2a4 4 0 0 0-4 4c0 1.95 1.4 3.58 3.25 3.93"/><path d="M4 13h16"/></svg>AI</span>';
          }
          if (n.node_type) html += '<span class="type-badge">' + escHtml(n.node_type) + '</span>';
          html += '</div>';
          if (n.from_path && n.from_path.length) {
            html += '<div class="breadcrumbs">';
            n.from_path.forEach(function(fp, idx) {
              if (idx > 0) html += '<span class="crumb-sep">›</span>';
              html += '<span>' + escHtml(fp) + '</span>';
            });
            html += '</div>';
          }
          if (n.suggestion) html += '<div class="hint">' + escHtml(n.suggestion) + '</div>';
          html += '</div>';
        });
        html += '</div></div>';
      }

      /* ── cross connections ─────────────────────── */
      if (crosses.length) {
        html += '<div class="analysis-section">';
        html += buildSectionToggle('cross-connections',
          '<svg class="section-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>',
          '跨分支关联', crosses.length);
        html += '<div class="section-body" id="section-cross-connections">';
        html += '<div class="section-desc">以下节点位于不同攻击分支，可能存在未发现的关联（如凭据复用、信息共享等）。</div>';
        crosses.forEach(function(cc) {
          html += '<div class="cross-card">';
          html += '<span class="cross-node">' + escHtml(cc.from_label) + '</span>';
          html += '<span class="cross-link"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg></span>';
          html += '<span class="cross-node">' + escHtml(cc.to_label) + '</span>';
          if (cc.reason) html += '<span class="cross-reason">' + escHtml(cc.reason) + '</span>';
          html += '</div>';
        });
        html += '</div></div>';
      }

      content.innerHTML = html;

      /* bind collapse toggles */
      var toggles = content.querySelectorAll('.section-toggle');
      for (var t = 0; t < toggles.length; t++) {
        toggles[t].addEventListener('click', function() {
          this.closest('.analysis-section').classList.toggle('collapsed');
        });
      }
    })
    .catch(function(e) {
      content.innerHTML = '<p style="color:var(--danger)">请求失败: ' + escHtml(e.message) + '</p>';
    });
}

function buildStatCard(cls, count, label, iconSvg) {
  return '<div class="stat-card">' +
    '<div class="stat-icon ' + cls + '">' + iconSvg + '</div>' +
    '<div><div class="stat-value">' + count + '</div><div class="stat-label">' + label + '</div></div>' +
  '</div>';
}

function buildSectionToggle(id, iconSvg, title, count) {
  return '<button class="section-toggle" data-target="section-' + id + '">' +
    '<svg class="section-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>' +
    iconSvg +
    '<span>' + title + '</span>' +
    '<span class="section-count">' + count + '</span>' +
  '</button>';
}

function hideAnalysis() {
  document.getElementById('analysis-overlay').classList.remove('active');
}
