/* =========================================================================
   SearchResults.jsx — the working search experience.
   Reads ?q= from the URL, searches the pages table (title match) and lists
   results that link to the edge-rendered guides. On a miss, it offers an
   explicit "Build it with Iris" action (a user click, never auto-on-load —
   crawlers hitting /search?q= must not trigger a paid build). The build calls
   iris-realtime, then redirects to the new guide.
   ========================================================================= */

const SB_URL = "https://xkquhthyfqdcbktyigyu.supabase.co";
const SB_ANON = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhrcXVodGh5ZnFkY2JrdHlpZ3l1Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzY4MDEzMjcsImV4cCI6MjA5MjM3NzMyN30.N4faHMUv_gkRzJ_okqDIoGD4uBIdpSLQ9mwDdpdZAbE";

function sbGet(pathAndQuery) {
  return fetch(`${SB_URL}/rest/v1/${pathAndQuery}`, {
    headers: { apikey: SB_ANON, Authorization: `Bearer ${SB_ANON}` },
  }).then((r) => (r.ok ? r.json() : null)).catch(() => null);
}

function withSlash(slug) {
  if (!slug) return "/";
  const s = slug.startsWith("/") ? slug : `/${slug}`;
  return s.endsWith("/") ? s : `${s}/`;
}
function toLabel(seg) {
  return (seg || "").split("-").map((w) => (w ? w[0].toUpperCase() + w.slice(1) : w)).join(" ");
}
function laneCat(slug) {
  const parts = (slug || "").split("/").filter(Boolean);
  const off = parts[0] === "es" ? 1 : 0;
  return [parts[off], parts[off + 1]].filter(Boolean).map(toLabel).join(" · ");
}

const SRCH_CSS = `
.srch { max-width: 980px; margin: 0 auto; padding: 56px 24px 100px; }
.srch__bar { display: flex; gap: 0; border: 1px solid var(--line); background: var(--paper); margin-bottom: 14px; }
.srch__bar input { flex: 1; border: 0; padding: 18px 20px; font-family: "JetBrains Mono", monospace; font-size: 15px; color: var(--ink); background: transparent; outline: none; }
.srch__bar button { border: 0; background: var(--forest); color: #fff; padding: 0 26px; font-family: "JetBrains Mono", monospace; font-size: 12px; letter-spacing: 0.16em; cursor: pointer; }
.srch__meta { font-family: "JetBrains Mono", monospace; font-size: 12px; letter-spacing: 0.08em; color: var(--mute); margin: 0 0 28px; }
.srch__list { display: flex; flex-direction: column; border-top: 1px solid var(--line); }
.srch__row { display: block; text-decoration: none; color: inherit; padding: 22px 4px; border-bottom: 1px solid var(--line); transition: background .25s ease, padding .25s ease; }
.srch__row:hover { background: var(--fog); padding-left: 14px; }
.srch__cat { font-family: "JetBrains Mono", monospace; font-size: 11px; letter-spacing: 0.18em; text-transform: uppercase; color: var(--forest-2); margin-bottom: 8px; }
.srch__t { font-family: "Inter Tight", sans-serif; font-weight: 600; font-size: 21px; line-height: 1.25; color: var(--ink); }
.srch__t .arr { color: var(--mute); }
.srch__empty { border: 1px solid var(--line); background: var(--fog); padding: 40px; text-align: center; }
.srch__empty h2 { font-family: "Inter Tight", sans-serif; font-size: 26px; margin: 0 0 10px; color: var(--ink); }
.srch__empty p { color: var(--mute); margin: 0 0 22px; line-height: 1.6; }
.srch__build { border: 0; background: var(--forest); color: #fff; padding: 14px 28px; font-family: "JetBrains Mono", monospace; font-size: 12px; letter-spacing: 0.16em; cursor: pointer; }
.srch__build:disabled { opacity: 0.6; cursor: default; }
.srch__hold { font-family: "Newsreader", serif; font-style: italic; font-size: 17px; line-height: 1.6; color: var(--ink-2); max-width: 46ch; margin: 0 auto; }
`;

function SearchApp() {
  const url = new URL(window.location.href);
  const q0 = (url.searchParams.get("q") || "").trim();
  const lang = (url.searchParams.get("lang") || "en").trim();
  const [q, setQ] = React.useState(q0);
  const [state, setState] = React.useState({ loading: !!q0, results: null });
  const [build, setBuild] = React.useState({ status: "idle", msg: "" });

  React.useEffect(() => {
    const tick = () => {
      const now = new Date();
      const f = (n) => String(n).padStart(2, "0");
      const clock = document.getElementById("tickerClock");
      if (clock) clock.textContent = `NYC · ${f(now.getHours())}:${f(now.getMinutes())}:${f(now.getSeconds())}`;
      const fsess = document.getElementById("fsess");
      if (fsess) fsess.textContent = `${f(now.getHours())}${f(now.getMinutes())}.${f(now.getSeconds())}`;
    };
    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, []);

  React.useEffect(() => {
    if (!q0) { setState({ loading: false, results: [] }); return; }
    const words = q0.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((w) => w.length > 2);
    const phrase = q0.replace(/[%,()]/g, " ");
    const ors = [`title.ilike.*${phrase}*`, ...words.map((w) => `title.ilike.*${w}*`)];
    const qstr = `pages?select=slug,title,lane,category&language=eq.${encodeURIComponent(lang)}&or=(${encodeURIComponent(ors.join(","))})&order=created_at.desc&limit=30`;
    sbGet(qstr).then((rows) => {
      // Rank: phrase match first, then by word-hit count.
      const ranked = (rows || []).map((r) => {
        const t = (r.title || "").toLowerCase();
        let score = t.includes(q0.toLowerCase()) ? 100 : 0;
        words.forEach((w) => { if (t.includes(w)) score += 1; });
        return { ...r, score };
      }).sort((a, b) => b.score - a.score);
      setState({ loading: false, results: ranked });
    });
  }, []);

  function submit(e) {
    if (e) e.preventDefault();
    const v = q.trim();
    if (v) window.location.href = `/search/?q=${encodeURIComponent(v)}${lang !== "en" ? `&lang=${lang}` : ""}`;
  }

  async function buildWithIris() {
    setBuild({ status: "building", msg: "If this is taking a second, you were probably the first person to ever search this. Iris is building it right now. In 8 languages. So thank you." });
    try {
      const res = await fetch(`${SB_URL}/functions/v1/iris-realtime`, {
        method: "POST",
        headers: { "Content-Type": "application/json", apikey: SB_ANON, Authorization: `Bearer ${SB_ANON}` },
        body: JSON.stringify({ query: q0, language: lang }),
      });
      const data = await res.json();
      if ((data.status === "built" || data.status === "existing") && data.page && data.page.slug) {
        window.location.href = withSlash(data.page.slug);
        return;
      }
      if (typeof data.message === "string" && data.message.startsWith("REFUSE")) {
        setBuild({ status: "refused", msg: "Iris can't build that one — it falls outside what we can responsibly answer (specific investment, tax, or legal advice). Try rephrasing toward the general how-to." });
        return;
      }
      setBuild({ status: "error", msg: "Iris couldn't build that one just now. Try again in a moment, or rephrase your search." });
    } catch {
      setBuild({ status: "error", msg: "Iris couldn't build that one just now. Try again in a moment, or rephrase your search." });
    }
  }

  const results = state.results || [];
  return (
    <div className="site" data-lane="personal">
      <style>{SRCH_CSS}</style>
      <Ticker />
      <Nav lane="personal" setLane={() => {}} />
      <main className="srch">
        <form className="srch__bar" onSubmit={submit}>
          <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="how to…" aria-label="Search" />
          <button type="submit">SEARCH</button>
        </form>

        {!q0 ? (
          <p className="srch__meta">Type a question and Iris finds the guide — or builds it.</p>
        ) : state.loading ? (
          <p className="srch__meta">Searching the index…</p>
        ) : results.length ? (
          <>
            <p className="srch__meta">{results.length} result{results.length === 1 ? "" : "s"} for "{q0}"</p>
            <div className="srch__list">
              {results.map((r) => (
                <a key={r.slug} className="srch__row" href={withSlash(r.slug)}>
                  <div className="srch__cat">{laneCat(r.slug)}</div>
                  <div className="srch__t">{r.title} <span className="arr">→</span></div>
                </a>
              ))}
            </div>
          </>
        ) : (
          <div className="srch__empty">
            {build.status === "idle" ? (
              <>
                <h2>No guide for "{q0}" yet.</h2>
                <p>Iris hasn't built this one. Want her to write it now? It takes a few seconds — and it'll be live in 8 languages.</p>
                <button className="srch__build" onClick={buildWithIris}>BUILD IT WITH IRIS →</button>
              </>
            ) : (
              <p className="srch__hold">{build.msg}</p>
            )}
          </div>
        )}
      </main>
      <Footer />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<SearchApp />);
