/* global React, ARCHIVE, ARCHIVE_TEXT */
const { useState: useStateS, useEffect: useEffectS, useRef: useRefS } = React;

// ============================================================
// AI SEARCH — calls /api/claude, grounds responses in the
// archive, and returns a typed JSON payload.
// ============================================================

const SYSTEM_PROMPT = `You are the search engine for Atishay Jain's portfolio.
Atishay is a Senior Product Designer, currently at Harness. Previously: Product Designer at Tessell (Jan 2024 – Oct 2025), Founding Designer at Martian (Jan 2023 – Jan 2024). IIT Guwahati grad, based in Bengaluru.

You answer ONLY from the archive below. If a question is outside the archive, say so — do not invent.
Keep responses short, confident, editorial. No marketing fluff. No emoji. No markdown.
Write in third person ("Atishay did X") — this is his portfolio's AI, not Atishay himself.

ARCHIVE:
${ARCHIVE_TEXT}

Respond with STRICT JSON matching this schema:
{
  "title": "Short editorial headline that directly answers the question, max 10 words",
  "body": "2-4 short paragraphs. Use inline citation tokens like [[cite:tessell-productE]] to attribute claims. Every non-trivial factual sentence must have one citation.",
  "projects": ["list", "of", "project", "ids"],
  "offArchive": false
}

Valid citation IDs:
- tessell-productE, tessell-db-provisioning, martian-portfolio, martian-design-strategies  (work)
- copy-translator, market-scanner, ds-generator  (side)
- about, how-i-ship, leadership, contact  (sections)

Return JSON only. No prose before or after. No code fence.`;

async function queryClaude(userQuery) {
  const prompt = `${SYSTEM_PROMPT}\n\nUSER QUERY: ${userQuery}`;
  try {
    const res = await fetch("/api/claude", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ prompt }),
    });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const { text: raw } = await res.json();
    const clean = raw.replace(/```json\s*|\s*```/g, "").trim();
    const parsed = JSON.parse(clean);
    return parsed;
  } catch (e) {
    console.error("AI parse failed:", e);
    return {
      title: "The archive stayed silent.",
      body: "Something went wrong. Try a shorter or simpler query. [[cite:contact]]",
      projects: [],
      offArchive: true,
    };
  }
}

// ============================================================
// Citation map — maps cite IDs to section/page refs
// ============================================================
const CITE_MAP = {
  "tessell-productE": { label: "Selected Work · ProductE", page: 2 },
  "tessell-db-provisioning": { label: "Selected Work · Tessell DB Provisioning", page: 6 },
  "martian-portfolio": { label: "Selected Work · Martian Portfolio", page: 10 },
  "martian-design-strategies": { label: "Selected Work · Design Strategies at Martian", page: 14 },
  "copy-translator": { label: "Side Projects · Copy Translator", page: 19 },
  "market-scanner": { label: "Side Projects · Market Scanner", page: 20 },
  "ds-generator": { label: "Side Projects · DS Generator", page: 21 },
  "about": { label: "About", page: 22 },
  "how-i-ship": { label: "How I Ship", page: 26 },
  "leadership": { label: "Leadership", page: 30 },
  "contact": { label: "Contact", page: 34 },
};

function renderBodyWithCitations(body, onCite) {
  const parts = [];
  const regex = /\[\[cite:([a-z0-9-]+)\]\]/gi;
  let lastIdx = 0;
  let match;
  let key = 0;
  while ((match = regex.exec(body)) !== null) {
    if (match.index > lastIdx) parts.push({ type: "text", text: body.slice(lastIdx, match.index), key: key++ });
    parts.push({ type: "cite", id: match[1], key: key++ });
    lastIdx = regex.lastIndex;
  }
  if (lastIdx < body.length) parts.push({ type: "text", text: body.slice(lastIdx), key: key++ });

  const paragraphs = [[]];
  parts.forEach((p) => {
    if (p.type === "text") {
      const chunks = p.text.split(/\n\n+/);
      chunks.forEach((c, i) => {
        if (i > 0) paragraphs.push([]);
        if (c) paragraphs[paragraphs.length - 1].push({ ...p, text: c });
      });
    } else {
      paragraphs[paragraphs.length - 1].push(p);
    }
  });

  const citeOrder = [];
  parts.forEach((p) => {
    if (p.type === "cite" && !citeOrder.includes(p.id)) citeOrder.push(p.id);
  });

  return paragraphs.map((para, pi) => (
    <p key={pi}>
      {para.map((p) => {
        if (p.type === "text") return <React.Fragment key={p.key}>{p.text}</React.Fragment>;
        const num = citeOrder.indexOf(p.id) + 1;
        const meta = CITE_MAP[p.id];
        if (!meta) return null;
        return (
          <sup
            key={p.key}
            className="cite"
            onClick={() => onCite && onCite(p.id)}
            title={`${meta.label} · p.${String(meta.page).padStart(2, "0")}`}
          >
            [{String(num).padStart(2, "0")}]
          </sup>
        );
      })}
    </p>
  ));
}

Object.assign(window, { queryClaude, renderBodyWithCitations, CITE_MAP, SYSTEM_PROMPT });
