// Paper index / search

// Maps a paper id to the artboard id of its public dossier, if one exists.
// Only papers with a real dossier surface should navigate; the rest stay
// visually present but inert until their dossiers are built.
const dossierNavFor = (id) => ({
  seyfried: "dossier",
  "barcaui-chatgpt": "dossier-barcaui",
}[id] || "");

const PaperIndex = () => {
  const { papers, categories } = AOP_DATA;
  const [query, setQuery] = React.useState("");
  const [field, setField] = React.useState("all");

  const fields = ["all", ...new Set(papers.map((p) => p.field))];
  const filtered = papers.filter((p) => {
    if (field !== "all" && p.field !== field) return false;
    if (query && !(`${p.title} ${p.authors} ${p.tags.join(" ")}`.toLowerCase().includes(query.toLowerCase()))) return false;
    return true;
  }).slice().sort((a, b) => {
    const rank = (p) => p.id === "barcaui-chatgpt" ? 0 : p.id === "seyfried" ? 1 : 2;
    return rank(a) - rank(b);
  });

  // Split the visible list into published dossiers vs. catalog-only stubs.
  // Published rows are clickable and show real qCounts; catalog-only rows
  // render with the "Not yet published" status line and an inert cursor.
  const published = filtered.filter((p) => dossierNavFor(p.id));
  const inProgress = filtered.filter((p) => !dossierNavFor(p.id));

  const renderRow = (p) => {
    const route = dossierNavFor(p.id);
    const isPublished = !!route;
    return (
      <article key={p.id} className="paper-row" data-nav={route} style={{ cursor: isPublished ? "pointer" : "default" }}>
        <div className="yr">{p.year}</div>
        <div>
          <h3>{p.title}</h3>
          <div className="auth">{p.authors}</div>
          <p style={{ fontSize: 14.5, color: "var(--ink-2)", margin: "0 0 10px", maxWidth: 720, lineHeight: 1.5 }}>
            {p.summary.length > 220 ? p.summary.slice(0, 220) + "…" : p.summary}
          </p>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", alignItems: "center" }}>
            <span className="meta" style={{ color: "var(--ink-2)", marginRight: 6 }}>{p.field}</span>
            {p.tags.slice(0, 4).map((t) => <Tag key={t}>{t}</Tag>)}
          </div>
        </div>
        <div className="qcounts">
          {isPublished ? (
            <React.Fragment>
              <div style={{ fontSize: 22, color: "var(--ink)", fontFamily: "var(--serif)", lineHeight: 1, marginBottom: 4 }}>{p.qCounts.published}</div>
              <div style={{ marginBottom: 10 }}>published questions</div>
              <div style={{ paddingTop: 10, borderTop: "1px dashed var(--rule)" }}>updated {p.added}</div>
            </React.Fragment>
          ) : (
            <div className="meta" style={{ color: "var(--ink-3)", fontStyle: "italic" }}>Not yet published</div>
          )}
        </div>
      </article>
    );
  };

  return (
    <div className="frame">
      <TopNav active="library" />

      <header style={{ maxWidth: 1180, margin: "0 auto", padding: "48px 40px 24px", borderBottom: "1px solid var(--ink)" }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>§ The library · {papers.length} papers · 162 questions</div>
        <h1 style={{ fontFamily: "var(--serif)", fontSize: 44, fontWeight: 500, letterSpacing: "-0.02em", margin: "0 0 24px", lineHeight: 1.1 }}>
          Browse every paper in the library.
        </h1>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 240px", gap: 16 }}>
          <div style={{ position: "relative" }}>
            <input
              className="field field--lg"
              placeholder="Search by title, author, DOI, or tag…"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
            />
            <span className="kbd" style={{ position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)" }}>⌘ K</span>
          </div>
          <select className="field field--lg" value={field} onChange={(e) => setField(e.target.value)}>
            {fields.map((f) => <option key={f} value={f}>{f === "all" ? "All fields" : f}</option>)}
          </select>
        </div>
      </header>

      <main style={{ maxWidth: 1180, margin: "0 auto", padding: "24px 40px 60px" }}>
        <div style={{ display: "flex", gap: 12, alignItems: "center", padding: "16px 0", flexWrap: "wrap" }}>
          <span className="label">Filter by question category</span>
          {categories.map((c) => (
            <button key={c.id} className="pill">§ {c.num} {c.name}</button>
          ))}
        </div>

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "12px 0", marginTop: 8, borderTop: "1px solid var(--ink)" }}>
          <div className="meta" style={{ color: "var(--ink-2)" }}>{filtered.length} {filtered.length === 1 ? "paper" : "papers"} · sorted by most recently revised</div>
          <div className="meta">
            <a href="#" style={{ color: "var(--ink-3)" }}>by year ↑</a> · <a href="#" style={{ color: "var(--ink-3)" }}>by field</a> · <span style={{ color: "var(--ink)" }}>by recency ↓</span>
          </div>
        </div>

        {published.length > 0 && (
          <React.Fragment>
            <div className="eyebrow" style={{ marginTop: 16, marginBottom: 4 }}>§ Published dossiers · {published.length}</div>
            {published.map(renderRow)}
          </React.Fragment>
        )}

        {inProgress.length > 0 && (
          <React.Fragment>
            <div className="eyebrow" style={{ marginTop: 32, marginBottom: 4 }}>§ More dossiers in progress · {inProgress.length}</div>
            {inProgress.map(renderRow)}
          </React.Fragment>
        )}
      </main>

      <Footer />
    </div>
  );
};

window.PaperIndex = PaperIndex;
