const input = document.querySelector("[data-search-input]");
const results = document.querySelector("[data-search-results]");
const status = document.querySelector("[data-search-status]");

function escapeHTML(value) {
  return String(value)
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;");
}

async function loadSearch() {
  const response = await fetch("search-index.json");
  return response.json();
}

function scoreDocument(document, query) {
  const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
  const title = document.title.toLowerCase();
  const section = String(document.section || "").toLowerCase();
  const sourcePath = document.sourcePath.toLowerCase();
  const text = document.text.toLowerCase();
  let score = 0;
  for (const term of terms) {
    if (title.includes(term)) score += 8;
    if (section.includes(term)) score += 4;
    if (sourcePath.includes(term)) score += 3;
    if (text.includes(term)) score += 1;
  }
  return score;
}

function renderResults(documents, query) {
  if (!query.trim()) {
    results.innerHTML = "";
    status.textContent = "Type to search titles, sections, paths, and page text.";
    return;
  }
  const matches = documents
    .map((document) => ({ document, score: scoreDocument(document, query) }))
    .filter((entry) => entry.score > 0)
    .sort((a, b) => b.score - a.score)
    .slice(0, 12);
  status.textContent = matches.length ? `${matches.length} best matches` : "No matches found.";
  results.innerHTML = matches.map(({ document }) => `<li>
    <a href="${escapeHTML(document.url)}">${escapeHTML(document.title)}</a>
    <span>${escapeHTML(document.sectionLabel)} · ${escapeHTML(document.sourcePath)}</span>
    <p>${escapeHTML(document.excerpt)}</p>
  </li>`).join("");
}

if (input && results && status) {
  loadSearch().then((documents) => {
    input.disabled = false;
    input.placeholder = "Search product, hiring, pricing, incidents...";
    status.textContent = "Type to search titles, sections, paths, and page text.";
    input.addEventListener("input", () => renderResults(documents, input.value));
  }).catch(() => {
    status.textContent = "Search index could not be loaded.";
  });
}
