/* ═══════════════════════════════════════════════════════════════════
   Global Search
   ═══════════════════════════════════════════════════════════════════ */
function toggleSearch() {
  const dd = document.getElementById('search-dropdown');
  const isOpen = dd.classList.contains('open');
  if (isOpen) {
    closeSearch();
  } else {
    dd.classList.add('open');
    document.getElementById('search-input').focus();
  }
}

function closeSearch() {
  document.getElementById('search-dropdown').classList.remove('open');
  document.getElementById('search-input').value = '';
  document.getElementById('search-results').innerHTML = '<div class="search-empty">输入关键词搜索所有项目的节点</div>';
}

function onSearchInput(val) {
  clearTimeout(searchDebounceTimer);
  if (!val.trim()) {
    document.getElementById('search-results').innerHTML = '<div class="search-empty">输入关键词搜索所有项目的节点</div>';
    return;
  }
  searchDebounceTimer = setTimeout(() => doSearch(val.trim()), 300);
}

async function doSearch(q) {
  const resultsEl = document.getElementById('search-results');
  resultsEl.innerHTML = '<div class="search-empty">搜索中...</div>';
  try {
    const data = await apiFetch(API + '/search?q=' + encodeURIComponent(q));
    const results = data.results || data || [];
    if (!results || results.length === 0) {
      resultsEl.innerHTML = '<div class="search-empty">未找到匹配结果</div>';
      return;
    }
    resultsEl.innerHTML = results.map(r => {
      const ctx = r.match_context || r.content_preview || '';
      const highlighted = ctx.replace(new RegExp('(' + escRegex(q) + ')', 'gi'), '<mark>$1</mark>');
      return '<div class="search-result-item" onclick="jumpToSearchResult(\'' + (r.project_id || '') + '\',\'' + (r.node_id || r.id || '') + '\')">' +
        '<div class="search-result-project">📁 ' + escHtml(r.project_name || '未知项目') + '</div>' +
        '<div class="search-result-label">' + escHtml(r.label || r.node_label || '') + '</div>' +
        (highlighted ? '<div class="search-result-context">' + highlighted + '</div>' : '') +
      '</div>';
    }).join('');
  } catch (e) {
    resultsEl.innerHTML = '<div class="search-empty">搜索失败</div>';
  }
}

function jumpToSearchResult(projectId, nodeId) {
  closeSearch();
  if (projectId && projectId !== currentProject) {
    selectProject(projectId);
  }
  setTimeout(() => {
    if (cy && nodeId) {
      const node = cy.getElementById(nodeId);
      if (node.length) {
        cy.animate({
          fit: { eles: node, padding: 80 },
          duration: 400,
        });
        setTimeout(() => node.trigger('tap'), 450);
      }
    }
  }, 600);
}

// Close search on outside click
document.addEventListener('click', (e) => {
  const dd = document.getElementById('search-dropdown');
  const btn = document.getElementById('btn-search');
  if (dd.classList.contains('open') && !dd.contains(e.target) && !btn.contains(e.target)) {
    closeSearch();
  }
});

// Close search on Escape
document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape') {
    const dd = document.getElementById('search-dropdown');
    if (dd.classList.contains('open')) closeSearch();
  }
});
