/* global React */
// Screens: Home, Results, Item Detail

const { useState: useStateS, useEffect: useEffectS, useMemo: useMemoS } = React;

/* ─────────── HOME ─────────── */
function HomeScreen({ onSearch, setQuery }) {
  const D = window.LD_DATA;
  return (
    <div style={{ maxWidth: 1280, margin: "0 auto", padding: "48px 32px 96px" }}>
      {/* Hero */}
      <section style={{
        display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 64, alignItems: "center",
        padding: "48px 0 56px", borderBottom: "1px solid var(--hairline)",
      }}>
        <div>
          <div className="smallcaps" style={{ color: "var(--accent)", marginBottom: 12 }}>
            Discovery · Across 142 sources
          </div>
          <h1 className="serif" style={{
            margin: 0, fontSize: 56, fontWeight: 500, lineHeight: 1.05,
            letterSpacing: "-0.015em", textWrap: "balance",
          }}>
            One search across<br />the entire collection.
          </h1>
          <p style={{
            fontFamily: "var(--font-serif)", fontStyle: "italic",
            fontSize: 18, lineHeight: 1.5, color: "var(--muted)",
            maxWidth: "44ch", marginTop: 18,
          }}>
            14 million books, articles, datasets and archival materials —
            curated by your subject librarians and indexed nightly.
          </p>

          <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 22 }}>
            {["climate change adaptation", "Toni Morrison", "CRISPR ethics", "Federalist No. 10", "deep learning surveys"].map(q => (
              <button key={q} onClick={() => { setQuery(q); onSearch(q); }} style={{
                background: "transparent", border: "1px solid var(--hairline-2)",
                color: "var(--ink-2)", padding: "6px 12px", fontSize: 13,
                fontFamily: "var(--font-sans)", cursor: "default",
              }}>
                {q}
              </button>
            ))}
          </div>
        </div>

        {/* Live snapshot */}
        <div style={{
          background: "var(--surface)", border: "1px solid var(--hairline)",
          padding: 28,
        }}>
          <div className="smallcaps" style={{ color: "var(--muted)", marginBottom: 16 }}>
            Library at a glance · today
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "24px 32px" }}>
            <Stat n="14.2m" label="Indexed items" />
            <Stat n="3.9m" label="Open access" />
            <Stat n="312" label="Subscribed databases" />
            <Stat n="6 / 8" label="Branches open now" tone="good" />
            <Stat n="2,184" label="Holds picked today" />
            <Stat n="48s" label="Avg. chat answer" />
          </div>
        </div>
      </section>

      {/* Quick paths */}
      <section style={{ padding: "40px 0", borderBottom: "1px solid var(--hairline)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <h2 className="serif" style={{ fontSize: 22, margin: 0, fontWeight: 600, letterSpacing: "-0.005em" }}>
            Start somewhere
          </h2>
          <a href="#" style={{ color: "var(--accent)", textDecoration: "none", fontSize: 13 }}>
            All collections →
          </a>
        </div>
        <div style={{
          display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16, marginTop: 18,
        }}>
          {D.COLLECTIONS.map((c) => (
            <button key={c.id} onClick={() => { setQuery(c.name); onSearch(c.name); }} style={{
              textAlign: "left", border: "1px solid var(--hairline)", background: "var(--surface)",
              padding: 22, cursor: "default", position: "relative", minHeight: 130,
              display: "flex", flexDirection: "column", justifyContent: "space-between",
            }}>
              <CollectionGlyph accent={c.accent} />
              <div>
                <div className="serif" style={{ fontSize: 19, fontWeight: 500 }}>
                  {c.name}
                </div>
                <div className="mono" style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 6 }}>
                  {window.fmt(c.count)} items
                </div>
              </div>
            </button>
          ))}
        </div>
      </section>

      {/* Recent acquisitions */}
      <section style={{ padding: "40px 0" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <h2 className="serif" style={{ fontSize: 22, margin: 0, fontWeight: 600, letterSpacing: "-0.005em" }}>
            Recently catalogued
          </h2>
          <a href="#" style={{ color: "var(--accent)", textDecoration: "none", fontSize: 13 }}>
            See all new arrivals →
          </a>
        </div>
        <div style={{
          display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 22, marginTop: 18,
        }}>
          {D.RESULTS.slice(0, 4).map((r) => (
            <article key={r.id} style={{
              display: "flex", flexDirection: "column", gap: 10,
              border: "1px solid var(--hairline)", background: "var(--surface)", padding: 18,
            }}>
              <BookGlyph type={r.type} title={r.title} />
              <div className="smallcaps" style={{ color: "var(--muted)", fontSize: 9.5 }}>
                {window.TYPE_LABEL[r.type]} · {r.year}
              </div>
              <div className="serif" style={{
                fontSize: 16, fontWeight: 500, lineHeight: 1.25, color: "var(--ink)",
                textWrap: "pretty",
              }}>
                {r.title}
              </div>
              <div style={{ fontSize: 12.5, color: "var(--muted)" }}>
                {r.authors[0]}{r.authors.length > 1 ? " et al." : ""}
              </div>
            </article>
          ))}
        </div>
      </section>
    </div>
  );
}

function Stat({ n, label, tone }) {
  return (
    <div>
      <div className="serif" style={{
        fontSize: 30, fontWeight: 500, letterSpacing: "-0.01em",
        color: tone === "good" ? "var(--good)" : "var(--ink)",
        fontVariantNumeric: "tabular-nums",
      }}>{n}</div>
      <div className="smallcaps" style={{ color: "var(--muted)", marginTop: 2 }}>{label}</div>
    </div>
  );
}

function CollectionGlyph({ accent }) {
  const colors = {
    leaf:  ["#1f3a2e", "#406b51"],
    amber: ["#8a4a1f", "#c08b4a"],
    rust:  ["#6a1f23", "#a44a4a"],
    ink:   ["#1c1814", "#5c544a"],
  };
  const [a, b] = colors[accent] || colors.ink;
  return (
    <svg viewBox="0 0 80 56" width="80" height="56" aria-hidden="true">
      <defs>
        <pattern id={`hatch-${accent}`} width="6" height="6" patternUnits="userSpaceOnUse">
          <path d="M0 6L6 0" stroke={b} strokeWidth="0.7" opacity="0.4" />
        </pattern>
      </defs>
      <rect x="2" y="6" width="20" height="46" fill={a} />
      <rect x="24" y="14" width="18" height="38" fill="transparent" stroke={a} strokeWidth="1.5" />
      <rect x="24" y="14" width="18" height="38" fill={`url(#hatch-${accent})`} />
      <rect x="44" y="2" width="16" height="50" fill={b} opacity="0.85" />
      <rect x="62" y="20" width="14" height="32" fill="transparent" stroke={a} strokeWidth="1.5" />
    </svg>
  );
}

function BookGlyph({ type, title }) {
  const seed = (title || "").length;
  const palettes = [
    ["#6a1f23", "#f0d8d4"],
    ["#1f3a2e", "#d6e4d8"],
    ["#1c1814", "#e7dfca"],
    ["#8a4a1f", "#efd9bf"],
    ["#3a2b56", "#dcd2e8"],
  ];
  const [fg, bg] = palettes[seed % palettes.length];
  return (
    <div style={{ height: 96, background: bg, position: "relative", overflow: "hidden" }}>
      <div style={{ position: "absolute", inset: 0, padding: 10, color: fg, fontFamily: "var(--font-serif)" }}>
        <div style={{ borderTop: `1px solid ${fg}`, borderBottom: `1px solid ${fg}`, padding: "4px 0", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase" }}>
          {window.TYPE_LABEL[type]}
        </div>
        <div style={{ marginTop: 8, fontSize: 13, lineHeight: 1.15, fontWeight: 500 }}>
          {title.split(" ").slice(0, 4).join(" ")}
        </div>
      </div>
      <div style={{ position: "absolute", right: 0, top: 0, bottom: 0, width: 6, background: fg, opacity: 0.85 }} />
    </div>
  );
}

/* ─────────── RESULTS ─────────── */
function ResultsScreen({ query, layout, onOpen, savedIds, toggleSave, showAI, setShowAI }) {
  const D = window.LD_DATA;
  const [selected, setSelected] = useStateS({ resourceType: [], availability: [], year: [], subject: [], language: [] });
  const [sort, setSort] = useStateS("relevance");

  const total = 11947;

  const sorted = useMemoS(() => {
    const arr = [...D.RESULTS];
    if (sort === "year") arr.sort((a, b) => b.year - a.year);
    if (sort === "cited") arr.sort((a, b) => (b.cited || 0) - (a.cited || 0));
    return arr;
  }, [sort]);

  function toggle(group, id) {
    setSelected((s) => ({ ...s, [group]: s[group].includes(id) ? s[group].filter(x => x !== id) : [...s[group], id] }));
  }

  function clearAll() {
    setSelected({ resourceType: [], availability: [], year: [], subject: [], language: [] });
  }

  const activeChips = useMemoS(() => {
    const out = [];
    Object.entries(selected).forEach(([g, ids]) => {
      ids.forEach(id => {
        const f = D.FACETS[g]?.find(x => x.id === id);
        if (f) out.push({ group: g, id, label: f.label });
      });
    });
    return out;
  }, [selected]);

  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: showAI ? "264px minmax(0, 1fr) 380px" : "264px minmax(0, 1fr)",
      gap: 0,
      maxWidth: 1480, margin: "0 auto",
      minHeight: "calc(100vh - 134px)",
    }}>
      {/* Facets */}
      <aside style={{
        padding: "24px 24px 24px 32px",
        borderRight: "1px solid var(--hairline)",
        position: "sticky", top: 134, alignSelf: "start", maxHeight: "calc(100vh - 134px)", overflowY: "auto",
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <h3 className="smallcaps" style={{ margin: 0, color: "var(--ink)" }}>Refine</h3>
          {activeChips.length > 0 && (
            <button onClick={clearAll} style={{
              background: "transparent", border: 0, color: "var(--muted)", fontSize: 11,
              textDecoration: "underline", cursor: "default", padding: 0,
            }}>Clear all</button>
          )}
        </div>

        <FacetGroup title="Resource type" facet={D.FACETS.resourceType} selected={selected.resourceType} onToggle={(id) => toggle("resourceType", id)} />
        <FacetGroup title="Availability" facet={D.FACETS.availability} selected={selected.availability} onToggle={(id) => toggle("availability", id)} />
        <FacetGroup title="Publication year" facet={D.FACETS.year} selected={selected.year} onToggle={(id) => toggle("year", id)} />
        <FacetGroup title="Subject" facet={D.FACETS.subject} selected={selected.subject} onToggle={(id) => toggle("subject", id)} />
        <FacetGroup title="Language" facet={D.FACETS.language} selected={selected.language} onToggle={(id) => toggle("language", id)} defaultOpen={false} />
      </aside>

      {/* Main */}
      <main style={{ padding: "24px 32px 80px", minWidth: 0 }}>
        {/* Result header */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap", gap: 12 }}>
          <div>
            <div className="smallcaps" style={{ color: "var(--muted)" }}>
              Search results
            </div>
            <h1 className="serif" style={{
              margin: "4px 0 0", fontSize: 32, fontWeight: 500, letterSpacing: "-0.01em",
            }}>
              <span style={{ fontStyle: "italic", color: "var(--muted)" }}>“</span>
              {query}
              <span style={{ fontStyle: "italic", color: "var(--muted)" }}>”</span>
            </h1>
            <div style={{ marginTop: 6, fontSize: 13, color: "var(--muted)" }}>
              <span className="mono" style={{ color: "var(--ink-2)" }}>{window.fmt(total)}</span> results · returned in <span className="mono">0.24s</span> from {" "}
              <a href="#" style={{ color: "var(--accent)", textDecoration: "none" }}>142 sources</a>
            </div>
          </div>

          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <span className="smallcaps" style={{ color: "var(--muted)" }}>Sort</span>
            <SegSelect value={sort} onChange={setSort}
              options={[{ id: "relevance", label: "Relevance" }, { id: "year", label: "Newest" }, { id: "cited", label: "Most cited" }]} />
            {!showAI && (
              <button onClick={() => setShowAI(true)} style={{
                display: "inline-flex", alignItems: "center", gap: 6,
                background: "var(--accent)", color: "var(--accent-ink)", border: 0,
                padding: "8px 12px", fontSize: 13, fontWeight: 500, cursor: "default",
              }}>
                <Icon.Sparkle width={13} height={13} /> Ask the research assistant
              </button>
            )}
          </div>
        </div>

        {/* Active chips */}
        {activeChips.length > 0 && (
          <div style={{ marginTop: 14, display: "flex", flexWrap: "wrap", gap: 6, alignItems: "center" }}>
            <span className="smallcaps" style={{ color: "var(--muted)", marginRight: 4 }}>Filters</span>
            {activeChips.map(c => (
              <button key={c.group + c.id} onClick={() => toggle(c.group, c.id)} style={{
                display: "inline-flex", alignItems: "center", gap: 6,
                background: "var(--ink)", color: "var(--paper)", border: 0,
                padding: "4px 10px", fontSize: 12, cursor: "default",
              }}>
                {c.label} <Icon.X width={11} height={11} />
              </button>
            ))}
          </div>
        )}

        {/* Did you mean / topic ribbon */}
        <div style={{
          marginTop: 18, padding: "12px 14px",
          background: "var(--paper-2)", border: "1px solid var(--hairline)",
          display: "flex", alignItems: "center", gap: 16, fontSize: 13, color: "var(--ink-2)",
          flexWrap: "wrap",
        }}>
          <span style={{ color: "var(--muted)" }}>
            <em style={{ fontFamily: "var(--font-serif)", fontStyle: "italic" }}>Did you also mean</em>
          </span>
          {["climate resilience", "vulnerability assessment", "managed retreat", "loss and damage"].map(t => (
            <button key={t} style={{
              background: "transparent", border: 0, color: "var(--accent)", padding: 0,
              fontSize: 13, textDecoration: "underline", cursor: "default", fontFamily: "var(--font-sans)",
            }}>{t}</button>
          ))}
        </div>

        {/* Results list */}
        <div style={{
          marginTop: 18,
          display: layout === "card" ? "grid" : "block",
          gridTemplateColumns: layout === "card" ? "repeat(2, 1fr)" : undefined,
          gap: layout === "card" ? 16 : 0,
        }}>
          {sorted.map((item) => (
            <div key={item.id} className="ld-fade">
              <ResultCard
                item={item}
                layout={layout}
                onOpen={onOpen}
                onSave={toggleSave}
                saved={savedIds.includes(item.id)}
                query={query}
              />
            </div>
          ))}
        </div>

        {/* Pagination */}
        <div style={{
          marginTop: 28, paddingTop: 18, borderTop: "1px solid var(--hairline)",
          display: "flex", alignItems: "center", justifyContent: "space-between",
        }}>
          <div style={{ fontSize: 13, color: "var(--muted)" }}>
            Showing <span className="mono" style={{ color: "var(--ink-2)" }}>1–10</span> of {window.fmt(total)}
          </div>
          <div style={{ display: "flex", gap: 6 }}>
            {[1, 2, 3, 4, "…", 1195].map((n, i) => (
              <button key={i} style={{
                minWidth: 32, height: 32, background: n === 1 ? "var(--ink)" : "transparent",
                color: n === 1 ? "var(--paper)" : "var(--ink)",
                border: n === 1 ? 0 : "1px solid var(--hairline-2)",
                fontFamily: "var(--font-mono)", fontSize: 12, cursor: "default",
              }}>{n}</button>
            ))}
          </div>
        </div>
      </main>

      {/* AI panel */}
      {showAI && (
        <div style={{
          borderLeft: "1px solid var(--hairline)",
          position: "sticky", top: 134, alignSelf: "start", height: "calc(100vh - 134px)",
        }}>
          <AIAssistant query={query} onOpenItem={onOpen} onClose={() => setShowAI(false)} />
        </div>
      )}
    </div>
  );
}

function SegSelect({ value, onChange, options }) {
  return (
    <div style={{ display: "inline-flex", border: "1px solid var(--hairline-2)" }}>
      {options.map(o => (
        <button key={o.id} onClick={() => onChange(o.id)} style={{
          background: value === o.id ? "var(--ink)" : "transparent",
          color: value === o.id ? "var(--paper)" : "var(--ink-2)",
          border: 0, padding: "6px 12px", fontSize: 12.5, fontWeight: 500,
          fontFamily: "var(--font-sans)", cursor: "default",
        }}>
          {o.label}
        </button>
      ))}
    </div>
  );
}

/* ─────────── ITEM DETAIL ─────────── */
function ItemDetailScreen({ item, onBack, onOpen, savedIds, toggleSave }) {
  const D = window.LD_DATA;
  const isShelf = item.access === "shelf";
  const [tab, setTab] = useStateS("overview");
  const saved = savedIds.includes(item.id);

  return (
    <div style={{ maxWidth: 1280, margin: "0 auto", padding: "24px 32px 80px" }}>
      {/* Breadcrumb */}
      <nav style={{ fontSize: 12.5, color: "var(--muted)", display: "flex", gap: 6, alignItems: "center" }}>
        <button onClick={onBack} style={{ background: "transparent", border: 0, color: "var(--muted)", padding: 0, cursor: "default", fontSize: 12.5 }}>
          ← Back to results
        </button>
        <span style={{ color: "var(--hairline-2)" }}>/</span>
        <span>{window.TYPE_LABEL[item.type]}</span>
        <span style={{ color: "var(--hairline-2)" }}>/</span>
        <span style={{ color: "var(--ink-2)" }}>{(item.title || "").slice(0, 60)}…</span>
      </nav>

      <div style={{ display: "grid", gridTemplateColumns: "180px 1fr 320px", gap: 36, marginTop: 24 }}>
        {/* Cover */}
        <div>
          <BookGlyph type={item.type} title={item.title} />
          <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 8 }}>
            <button style={btnPrimary}>
              {isShelf ? <>Request hold <Icon.Chevron /></> : <>Read full text <Icon.Chevron /></>}
            </button>
            <button onClick={() => toggleSave(item.id)} style={btnGhost}>
              {saved ? <><Icon.StarFill /> Saved</> : <><Icon.Star /> Save to shelf</>}
            </button>
            <button style={btnGhost}><Icon.Cite /> Cite this</button>
            <button style={btnGhost}><Icon.Share /> Share / export</button>
          </div>
        </div>

        {/* Main column */}
        <article>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6, alignItems: "center" }}>
            <Pill tone="neutral"><TypeGlyph type={item.type} size={11} /> {window.TYPE_LABEL[item.type]}</Pill>
            {item.peerReviewed && <Pill tone="ghost">Peer-reviewed</Pill>}
            {item.openAccess && <Pill tone="accent">Open access</Pill>}
            <span style={{ marginLeft: 4, fontSize: 12.5, color: "var(--muted)" }}>{item.year} · {item.venue}</span>
          </div>

          <h1 className="serif" style={{
            margin: "10px 0 6px", fontSize: 38, fontWeight: 500, lineHeight: 1.12,
            letterSpacing: "-0.015em", textWrap: "balance",
          }}>
            {item.title}
          </h1>

          <div style={{ fontSize: 15, color: "var(--ink-2)", lineHeight: 1.45 }}>
            {item.authors.map((a, i) => (
              <span key={a}>
                <a href="#" style={{ color: "var(--accent)", textDecoration: "none" }}>{a}</a>
                {i < item.authors.length - 1 ? "; " : ""}
              </span>
            ))}
          </div>

          {/* Tabs */}
          <div style={{ marginTop: 24, borderBottom: "1px solid var(--hairline)", display: "flex", gap: 28 }}>
            {[
              { id: "overview", label: "Overview" },
              { id: "citations", label: `Citations (${item.cited ?? 0})` },
              { id: "related", label: "Related works" },
              { id: "details", label: "Bibliographic details" },
            ].map(t => (
              <button key={t.id} onClick={() => setTab(t.id)} style={{
                background: "transparent", border: 0, padding: "10px 0",
                borderBottom: tab === t.id ? "2px solid var(--ink)" : "2px solid transparent",
                color: tab === t.id ? "var(--ink)" : "var(--muted)",
                fontSize: 13.5, fontWeight: 500, cursor: "default", fontFamily: "var(--font-sans)",
              }}>{t.label}</button>
            ))}
          </div>

          <div style={{ marginTop: 22 }}>
            {tab === "overview" && (
              <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
                <section>
                  <h3 className="smallcaps" style={{ margin: "0 0 8px", color: "var(--muted)" }}>Abstract</h3>
                  <p style={{
                    margin: 0, fontFamily: "var(--font-serif)", fontSize: 17, lineHeight: 1.55,
                    color: "var(--ink)", maxWidth: "62ch", textWrap: "pretty",
                  }}>
                    {item.abstract || "We synthesise twenty years of coastal adaptation case studies across 47 cities and propose a pathways framework that couples ecological capacity with municipal finance horizons. Findings suggest that incremental retreat strategies, when paired with green-grey infrastructure, outperform single-strategy interventions on a 30-year resilience index. The paper closes with policy recommendations for the IPCC AR7 working group."}
                  </p>
                </section>

                <section>
                  <h3 className="smallcaps" style={{ margin: "0 0 8px", color: "var(--muted)" }}>Subjects</h3>
                  <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                    {(item.subjects || []).map(s => (
                      <Pill key={s} tone="neutral">{s}</Pill>
                    ))}
                  </div>
                </section>

                <section>
                  <h3 className="smallcaps" style={{ margin: "0 0 10px", color: "var(--muted)" }}>Citation graph</h3>
                  <CitationGraph item={item} citations={D.CITATIONS} />
                </section>
              </div>
            )}

            {tab === "citations" && (
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32 }}>
                <CiteList title={`This work cites (${D.CITATIONS.cites.length})`} items={D.CITATIONS.cites} />
                <CiteList title={`Cited by (${item.cited})`} items={D.CITATIONS.citedBy} />
              </div>
            )}

            {tab === "related" && (
              <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 14 }}>
                {D.RESULTS.filter(r => r.id !== item.id).slice(0, 4).map(r => (
                  <button key={r.id} onClick={() => onOpen(r.id)} style={{
                    background: "var(--surface)", border: "1px solid var(--hairline)", padding: 16,
                    textAlign: "left", cursor: "default", display: "flex", flexDirection: "column", gap: 6,
                  }}>
                    <div className="smallcaps" style={{ color: "var(--muted)", fontSize: 9.5 }}>
                      {window.TYPE_LABEL[r.type]} · {r.year}
                    </div>
                    <div className="serif" style={{ fontSize: 16, fontWeight: 500, lineHeight: 1.25 }}>{r.title}</div>
                    <div style={{ fontSize: 12.5, color: "var(--muted)" }}>{r.authors[0]}{r.authors.length > 1 ? " et al." : ""}</div>
                  </button>
                ))}
              </div>
            )}

            {tab === "details" && (
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13.5 }}>
                <tbody>
                  {[
                    ["Title", item.title],
                    ["Authors", item.authors.join("; ")],
                    ["Year", item.year],
                    ["Source", item.venue + (item.vol ? `, ${item.vol}` : "") + (item.pages ? `, ${item.pages}` : "")],
                    item.doi && ["DOI", item.doi],
                    item.isbn && ["ISBN", item.isbn],
                    item.callNumber && ["Call number", item.callNumber],
                    ["Language", (item.languages || []).join(", ")],
                    ["Format", window.TYPE_LABEL[item.type]],
                  ].filter(Boolean).map(([k, v]) => (
                    <tr key={k} style={{ borderBottom: "1px solid var(--hairline)" }}>
                      <td style={{ padding: "10px 0", color: "var(--muted)", width: 160, verticalAlign: "top" }}>{k}</td>
                      <td style={{ padding: "10px 0", color: "var(--ink)" }} className={(k === "DOI" || k === "ISBN" || k === "Call number") ? "mono" : ""}>{v}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </article>

        {/* Right rail — availability */}
        <aside>
          <div style={{
            border: "1px solid var(--hairline)", background: "var(--surface)", padding: 20,
            display: "flex", flexDirection: "column", gap: 14,
          }}>
            <h3 className="smallcaps" style={{ margin: 0, color: "var(--muted)" }}>Get it</h3>

            {isShelf ? (
              <>
                <div>
                  <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                    <span style={{
                      width: 8, height: 8, borderRadius: 999,
                      background: item.availability?.startsWith("Available") ? "var(--good)" : "var(--warn)",
                    }} />
                    <strong style={{ fontSize: 14 }}>{item.availability}</strong>
                  </div>
                  <div className="mono" style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 6 }}>
                    {item.callNumber}
                  </div>
                  <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 2 }}>
                    {item.location}
                  </div>
                </div>
                <ShelfMap />
                <div style={{ display: "flex", gap: 6 }}>
                  <button style={btnTiny}><Icon.Pin /> Locate on map</button>
                  <button style={btnTiny}>Email this location</button>
                </div>
                <div style={{ borderTop: "1px solid var(--hairline)", paddingTop: 12 }}>
                  <div className="smallcaps" style={{ color: "var(--muted)", marginBottom: 6 }}>Other formats</div>
                  <ul style={{ margin: 0, padding: 0, listStyle: "none", fontSize: 13, color: "var(--ink-2)" }}>
                    <li style={{ padding: "4px 0", display: "flex", justifyContent: "space-between" }}>
                      E-book <a href="#" style={{ color: "var(--accent)", textDecoration: "none" }}>Read online →</a>
                    </li>
                    <li style={{ padding: "4px 0", display: "flex", justifyContent: "space-between" }}>
                      Audiobook <a href="#" style={{ color: "var(--accent)", textDecoration: "none" }}>Hoopla →</a>
                    </li>
                  </ul>
                </div>
              </>
            ) : (
              <>
                <div>
                  <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                    <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--good)" }} />
                    <strong style={{ fontSize: 14 }}>Full text available online</strong>
                  </div>
                  <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 4 }}>
                    Via your Eastbrook subscription
                  </div>
                </div>
                <ul style={{ margin: 0, padding: 0, listStyle: "none", fontSize: 13, display: "flex", flexDirection: "column", gap: 8 }}>
                  {["Nature.com", "ScienceDirect", "JSTOR (delayed)"].map(s => (
                    <li key={s} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderBottom: "1px dashed var(--hairline)", paddingBottom: 6 }}>
                      <span>{s}</span>
                      <a href="#" style={{ color: "var(--accent)", textDecoration: "none" }}>Open →</a>
                    </li>
                  ))}
                </ul>
                {item.openAccess && (
                  <div style={{ padding: "10px 12px", background: "var(--accent-soft)", color: "var(--accent)", fontSize: 12.5 }}>
                    This work is open access — no login required.
                  </div>
                )}
              </>
            )}
          </div>

          {/* Librarian help */}
          <div style={{
            marginTop: 16, border: "1px solid var(--hairline)", padding: 18, background: "var(--paper-2)",
          }}>
            <div className="smallcaps" style={{ color: "var(--muted)", marginBottom: 6 }}>Subject librarian</div>
            <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
              <div style={{
                width: 44, height: 44, background: "var(--ink)", color: "var(--paper)",
                display: "grid", placeItems: "center", fontFamily: "var(--font-serif)", fontSize: 16,
              }}>RH</div>
              <div>
                <div className="serif" style={{ fontSize: 15, fontWeight: 600 }}>Reza Hosseini</div>
                <div style={{ fontSize: 12, color: "var(--muted)" }}>Environmental Sciences</div>
              </div>
            </div>
            <button style={{ ...btnTiny, marginTop: 12, width: "100%", justifyContent: "center" }}>
              Schedule a consultation
            </button>
          </div>
        </aside>
      </div>
    </div>
  );
}

function CiteList({ title, items }) {
  return (
    <div>
      <h3 className="smallcaps" style={{ margin: "0 0 10px", color: "var(--muted)" }}>{title}</h3>
      <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 12 }}>
        {items.map(c => (
          <li key={c.id} style={{ paddingBottom: 12, borderBottom: "1px solid var(--hairline)" }}>
            <div className="serif" style={{ fontSize: 15.5, lineHeight: 1.3, fontWeight: 500 }}>{c.title}</div>
            <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 2 }}>{c.authors} · {c.year}</div>
          </li>
        ))}
      </ul>
    </div>
  );
}

function CitationGraph({ item, citations }) {
  // SVG of a small force-ish layout: center node + cites left + citedBy right
  const W = 600, H = 220;
  const cx = W / 2, cy = H / 2;
  const leftN = citations.cites;
  const rightN = citations.citedBy;
  const place = (arr, side) => arr.map((n, i) => ({
    ...n,
    x: side === "L" ? 80 + (i % 2) * 30 : W - 80 - (i % 2) * 30,
    y: 40 + (i * (H - 80) / Math.max(arr.length - 1, 1)),
  }));
  const left = place(leftN, "L");
  const right = place(rightN, "R");

  return (
    <div style={{ border: "1px solid var(--hairline)", background: "var(--surface)", padding: 12 }}>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block", maxHeight: 240 }}>
        {/* edges */}
        {left.map(n => (
          <line key={"l" + n.id} x1={n.x} y1={n.y} x2={cx} y2={cy}
            stroke="var(--hairline-2)" strokeWidth="0.8" />
        ))}
        {right.map(n => (
          <line key={"r" + n.id} x1={cx} y1={cy} x2={n.x} y2={n.y}
            stroke="var(--accent)" strokeOpacity="0.4" strokeWidth="0.8" />
        ))}
        {/* nodes */}
        {left.map(n => (
          <g key={n.id}>
            <circle cx={n.x} cy={n.y} r="5" fill="var(--paper)" stroke="var(--muted)" strokeWidth="1" />
            <text x={n.x - 10} y={n.y + 3} fontSize="9" textAnchor="end" fill="var(--ink-2)" fontFamily="var(--font-sans)">
              {n.authors} {n.year}
            </text>
          </g>
        ))}
        {right.map(n => (
          <g key={n.id}>
            <circle cx={n.x} cy={n.y} r="5" fill="var(--accent-soft)" stroke="var(--accent)" strokeWidth="1" />
            <text x={n.x + 10} y={n.y + 3} fontSize="9" fill="var(--ink-2)" fontFamily="var(--font-sans)">
              {n.authors} {n.year}
            </text>
          </g>
        ))}
        {/* center node */}
        <circle cx={cx} cy={cy} r="10" fill="var(--ink)" />
        <text x={cx} y={cy + 4} fontSize="9" textAnchor="middle" fill="var(--paper)" fontFamily="var(--font-sans)">This</text>

        {/* labels */}
        <text x={20} y={H - 8} fontSize="9" fill="var(--muted)" fontFamily="var(--font-sans)" letterSpacing="1.4">CITES ←</text>
        <text x={W - 20} y={H - 8} fontSize="9" textAnchor="end" fill="var(--muted)" fontFamily="var(--font-sans)" letterSpacing="1.4">→ CITED BY</text>
      </svg>
    </div>
  );
}

function ShelfMap() {
  return (
    <div style={{ background: "var(--paper)", border: "1px solid var(--hairline)", padding: 10 }}>
      <svg viewBox="0 0 220 110" width="100%" style={{ display: "block" }}>
        <rect x="0.5" y="0.5" width="219" height="109" fill="transparent" stroke="var(--hairline-2)" />
        {/* shelves */}
        {[15, 35, 55, 75, 95].map(y => (
          <line key={y} x1="20" x2="200" y1={y} y2={y} stroke="var(--hairline-2)" strokeWidth="2" />
        ))}
        {/* aisles */}
        <line x1="110" x2="110" y1="0" y2="110" stroke="var(--hairline)" strokeDasharray="2 3" />
        {/* call number marker */}
        <circle cx="146" cy="55" r="6" fill="var(--accent)" opacity="0.18" />
        <circle cx="146" cy="55" r="3" fill="var(--accent)" />
        <text x="155" y="58" fontSize="8" fill="var(--ink-2)" fontFamily="var(--font-mono)">QC903</text>
        <text x="6" y="106" fontSize="7" fill="var(--muted)" fontFamily="var(--font-sans)" letterSpacing="1">WEXLER · 3F</text>
      </svg>
    </div>
  );
}

Object.assign(window, { HomeScreen, ResultsScreen, ItemDetailScreen });
