---
import SiteLayout from "../../layouts/SiteLayout.astro";
---
<SiteLayout title="Recherche">
  <h1>Recherche</h1>
  <p>Recherche plein texte (statique) dans les pages “édition-livre”.</p>

  <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin:12px 0 18px;">
    <label>
      <span style="display:block;font-size:12px;opacity:0.85;">Terme</span>
      <input id="q" type="search" placeholder="Ex: archicratie, régulation, inertie…" style="padding:8px 10px;min-width:280px;">
    </label>

    <label>
      <span style="display:block;font-size:12px;opacity:0.85;">Édition</span>
      <select id="edition" style="padding:8px 10px;">
        <option value="">Toutes</option>
        <option value="archicratie">Archicratie</option>
        <option value="traite">Traité</option>
        <option value="ia">Cas IA</option>
        <option value="glossaire">Glossaire</option>
        <option value="atlas">Atlas</option>
      </select>
    </label>

    <label>
      <span style="display:block;font-size:12px;opacity:0.85;">Niveau</span>
      <select id="level" style="padding:8px 10px;">
        <option value="">Tous</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
    </label>
  </div>

  <div id="status" style="margin:10px 0;opacity:0.9;"></div>
  <ol id="results" style="padding-left:18px;"></ol>

  <script is:inline>
(() => {
  const q = document.getElementById("q");
  const ed = document.getElementById("edition");
  const lv = document.getElementById("level");
  const status = document.getElementById("status");
  const results = document.getElementById("results");

  let pfPromise = null;

  async function getPagefind() {
    if (pfPromise) return pfPromise;
    pfPromise = (async () => {
      try {
        const pagefind = await import("/pagefind/pagefind.js");
        // init facultatif, mais accélère si on clique dans l’input
        await pagefind.init?.();
        return pagefind;
      } catch {
        return null;
      }
    })();
    return pfPromise;
  }

  function currentFilters() {
    const filters = {};
    if (ed.value) filters.edition = ed.value;
    if (lv.value) filters.level = lv.value;
    return Object.keys(filters).length ? filters : null;
  }

  function clearResults() {
    results.innerHTML = "";
  }

  function setStatus(msg) {
    status.textContent = msg;
  }

  async function runSearch() {
    const term = q.value.trim();
    if (!term) {
      setStatus("Tape un terme pour chercher.");
      clearResults();
      return;
    }

    const pagefind = await getPagefind();
    if (!pagefind) {
      setStatus("Index de recherche indisponible. Fais `npm run build` puis `npm run preview`.");
      clearResults();
      return;
    }

    const opts = {};
    const filters = currentFilters();
    if (filters) opts.filters = filters;

    setStatus("Recherche…");
    const search = await pagefind.debouncedSearch(term, opts, 250);
    if (search === null) return;

    const items = await Promise.all(search.results.slice(0, 20).map(r => r.data()));
    setStatus(`${items.length} résultat(s) (sur ${search.results.length}).`);

    results.innerHTML = "";
    for (const item of items) {
      const li = document.createElement("li");
      li.style.marginBottom = "12px";

      const a = document.createElement("a");
      a.href = item.url;
      a.textContent = item.meta?.title || item.url;

      const meta = document.createElement("div");
      meta.style.fontSize = "12px";
      meta.style.opacity = "0.85";
      const edv = item.meta?.edition ? `édition: ${item.meta.edition}` : "";
      const lv = item.meta?.level ? `niveau: ${item.meta.level}` : "";
      const v = item.meta?.version ? `v${item.meta.version}` : "";
      meta.textContent = [edv, lv, v].filter(Boolean).join(" · ");

      const ex = document.createElement("div");
      ex.style.marginTop = "6px";
      ex.innerHTML = item.excerpt || "";

      li.appendChild(a);
      if (meta.textContent) li.appendChild(meta);
      li.appendChild(ex);
      results.appendChild(li);
    }
  }

  // Précharge quand focus => UX meilleure
  q.addEventListener("focus", () => { getPagefind(); });

  q.addEventListener("input", runSearch);
  ed.addEventListener("change", runSearch);
  lv.addEventListener("change", runSearch);

  setStatus("Tape un terme pour chercher.");
})();
  </script>
</SiteLayout>
