/* global React */
// Collection Discovery — Lobby + Drill-down with 3 layout variants (V1/V2/V4).
// The drill-down content is identical across variants; only the left-side
// navigation chrome differs.

const { useState: useStateC, useMemo: useMemoC, useEffect: useEffectC } = React;

/* ─────────────── data helpers ─────────────── */

// Walk the tree along a path of ids; returns the node at the end of the path
// (or root if path empty).
function nodeAt(root, path) {
  let n = root;
  for (const id of path) {
    const next = (n.children || []).find((c) => c.id === id);
    if (!next) break;
    n = next;
  }
  return n;
}

// Build the breadcrumb (array of nodes from root → current)
function crumbsOf(root, path) {
  const out = [root];
  let n = root;
  for (const id of path) {
    const next = (n.children || []).find((c) => c.id === id);
    if (!next) break;
    out.push(next);
    n = next;
  }
  return out;
}

// Children-or-items: produces a flat list of "cards" to render in the grid
function cardsAt(node) {
  const subs = (node.children || []).map((c) => ({
    kind: "folder",
    id: c.id,
    title: c.name,
    palette: c.palette,
    count: (c.children?.length ?? 0) + ((c.items?.length) ?? 0),
    raw: c,
  }));
  const items = (node.items || []).map((it) => ({
    kind: "item",
    id: it.id,
    title: it.title,
    type: it.type,
    palette: it.palette,
    callNumber: it.callNumber,
    year: it.year,
    raw: it,
  }));
  return [...subs, ...items];
}

/* ─────────────── small atoms (local copies for clarity) ─────────────── */

const COL_FONT = {
  serif: '"Newsreader", Georgia, serif',
  sans:  '"Geist", ui-sans-serif, system-ui, sans-serif',
  mono:  '"Geist Mono", ui-monospace, Menlo, monospace',
};

function ColSmallCaps({ children, style }) {
  return (
    <span style={{
      fontFamily: COL_FONT.sans, fontSize: 10, letterSpacing: "0.14em",
      textTransform: "uppercase", fontWeight: 600, color: "var(--muted)",
      ...style,
    }}>{children}</span>
  );
}

function ColChevron({ open, size = 11 }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="none"
      stroke="currentColor" strokeWidth="2"
      style={{ transform: open ? "rotate(0)" : "rotate(-90deg)", transition: "transform .15s" }}>
      <path d="M6 9l6 6 6-6" />
    </svg>
  );
}

function FolderIco({ size = 13 }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1.4">
      <path d="M3 7h6l2 2h10v10H3z" />
    </svg>
  );
}

function FilterIco({ size = 14 }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1.4">
      <path d="M4 5h16l-6 8v6l-4 1v-7L4 5z" />
    </svg>
  );
}

function TreeIco({ size = 14 }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1.4">
      <path d="M5 4h6M5 12h6M5 20h6" />
      <path d="M11 4h4v16h-4" />
    </svg>
  );
}

function BookmarkIco({ size = 13, filled }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size}
      fill={filled ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.4">
      <path d="M6 4h12v17l-6-4-6 4z" />
    </svg>
  );
}

function InfoIco({ size = 13 }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1.4">
      <circle cx="12" cy="12" r="9" /><path d="M12 8v.01M11 12h1v5h1" />
    </svg>
  );
}

function CollapseIco({ size = 14 }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1.6">
      <path d="M14 6l-6 6 6 6" />
      <path d="M19 6l-6 6 6 6" opacity="0.4" />
    </svg>
  );
}

function ExpandIco({ size = 14 }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1.6">
      <path d="M10 6l6 6-6 6" />
      <path d="M5 6l6 6-6 6" opacity="0.4" />
    </svg>
  );
}

function CollapsedRail({ label, icon, onClick, background = "var(--surface)" }) {
  return (
    <div onClick={onClick} title={`Expand ${label}`} style={{
      height: "100%", display: "flex", flexDirection: "column", alignItems: "center",
      padding: "12px 0", gap: 12, cursor: "default",
      background, overflow: "hidden",
    }}>
      <span style={{
        display: "grid", placeItems: "center",
        width: 26, height: 26, color: "var(--ink)",
        border: "1px solid var(--hairline-2)", background: "var(--paper)",
      }}>
        <ExpandIco size={13} />
      </span>
      <span style={{ color: "var(--muted)" }}>{icon}</span>
      <div style={{
        writingMode: "vertical-rl", transform: "rotate(180deg)",
        fontFamily: COL_FONT.sans, fontSize: 10.5, letterSpacing: "0.16em",
        textTransform: "uppercase", fontWeight: 600, color: "var(--ink)",
        whiteSpace: "nowrap",
      }}>{label}</div>
    </div>
  );
}

/* ─────────────── cover art (no real photos) ─────────────── */

// Single hero image — abstract gradient with subtle texture
function CoverHero({ palette, height = 200, label }) {
  const [a, b, c] = palette;
  const grad = `linear-gradient(135deg, ${a} 0%, ${b} 55%, ${c || b} 100%)`;
  return (
    <div style={{
      position: "relative", height, overflow: "hidden", background: grad,
    }}>
      <svg viewBox="0 0 400 200" preserveAspectRatio="none"
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0.18 }}>
        <defs>
          <pattern id={`dot-${a.replace("#", "")}`} width="14" height="14" patternUnits="userSpaceOnUse">
            <circle cx="2" cy="2" r="1" fill="#fbf8ef" />
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill={`url(#dot-${a.replace("#", "")})`} />
        <path d="M0 130 Q100 90 200 130 T400 110 L400 200 L0 200 Z" fill="#fbf8ef" opacity="0.12" />
        <path d="M0 160 Q100 130 200 160 T400 150 L400 200 L0 200 Z" fill="#fbf8ef" opacity="0.18" />
      </svg>
      {label && (
        <span style={{
          position: "absolute", top: 8, left: 10,
          fontFamily: COL_FONT.sans, fontSize: 9, letterSpacing: "0.14em",
          textTransform: "uppercase", color: "#fbf8ef", opacity: 0.95, fontWeight: 600,
        }}>{label}</span>
      )}
    </div>
  );
}

// 2x2 mosaic — four offset tiles
function CoverMosaic({ palette, height = 200 }) {
  const [a, b, c] = palette;
  const swatches = [
    `linear-gradient(135deg, ${a}, ${b})`,
    `linear-gradient(135deg, ${b}, ${c || b})`,
    `linear-gradient(135deg, ${c || b}, ${a})`,
    `linear-gradient(135deg, ${a}, ${c || b})`,
  ];
  return (
    <div style={{
      display: "grid", gridTemplateColumns: "1fr 1fr", gridTemplateRows: "1fr 1fr",
      gap: 2, height,
    }}>
      {swatches.map((g, i) => (
        <div key={i} style={{ background: g, position: "relative", overflow: "hidden" }}>
          <svg viewBox="0 0 100 100" preserveAspectRatio="none"
            style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0.14 }}>
            <path d="M0 70 Q25 50 50 70 T100 60 L100 100 L0 100 Z" fill="#fbf8ef" />
          </svg>
        </div>
      ))}
    </div>
  );
}

/* ─────────────── hierarchy tree (functional) ─────────────── */

function TreeNode({ node, depth = 0, currentPath, onSelect, openMap, setOpenMap }) {
  const isCurrent = node.id === currentPath[currentPath.length - 1];
  const onPath = currentPath.includes(node.id);
  const has = node.children?.length;
  const open = openMap[node.id] ?? onPath;
  const indent = depth * 14;

  function toggle(e) {
    e.stopPropagation();
    setOpenMap((m) => ({ ...m, [node.id]: !open }));
  }

  function select() {
    onSelect(node.id);
  }

  return (
    <>
      <div onClick={select} style={{
        display: "grid", gridTemplateColumns: "14px 1fr auto",
        alignItems: "center", gap: 6,
        padding: "5px 8px", paddingLeft: 8 + indent,
        background: isCurrent ? "var(--accent-soft)" : "transparent",
        color: isCurrent ? "var(--accent)" : "var(--ink)",
        borderLeft: isCurrent ? "2px solid var(--accent)" : "2px solid transparent",
        fontFamily: COL_FONT.sans, fontSize: 12.5, fontWeight: isCurrent ? 600 : (onPath ? 500 : 400),
        cursor: "default",
      }}>
        <span onClick={has ? toggle : undefined} style={{ display: "inline-flex", color: "var(--muted)" }}>
          {has ? <ColChevron open={open} size={10} /> : <span style={{ width: 10 }} />}
        </span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6, minWidth: 0 }}>
          <FolderIco size={12} />
          <span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{node.name}</span>
        </span>
        {has && (
          <span style={{ fontFamily: COL_FONT.mono, fontSize: 10.5, color: isCurrent ? "var(--accent)" : "var(--muted)" }}>
            {node.children.length}
          </span>
        )}
      </div>
      {has && open && node.children.map((c) => (
        <TreeNode key={c.id} node={c} depth={depth + 1} currentPath={currentPath}
          onSelect={onSelect} openMap={openMap} setOpenMap={setOpenMap} />
      ))}
    </>
  );
}

function HierarchyPanel({ collection, currentPath, onSelect, openMap, setOpenMap, withHeader = true, onCollapse }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", overflow: "hidden" }}>
      {withHeader && (
        <div style={{
          padding: "12px 14px 10px", borderBottom: "1px solid var(--hairline)",
          display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8,
        }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <ColSmallCaps style={{ color: "var(--ink2, var(--ink-2))" }}>Finding aid</ColSmallCaps>
            <div style={{
              fontFamily: COL_FONT.serif, fontSize: 15, fontWeight: 500, marginTop: 2,
              letterSpacing: "-0.005em",
            }}>{collection.name}</div>
            <div style={{ fontFamily: COL_FONT.mono, fontSize: 10, color: "var(--muted)", marginTop: 3 }}>
              {collection.callNumber} · {collection.dates} · {collection.linearFeet}
            </div>
            <input placeholder="Filter finding aid…" style={{
              marginTop: 10, width: "100%", padding: "6px 8px",
              background: "var(--paper)", border: "1px solid var(--hairline-2)",
              fontFamily: COL_FONT.sans, fontSize: 12, color: "var(--ink)", outline: "none",
            }} />
          </div>
          {onCollapse && (
            <button onClick={onCollapse} title="Collapse finding aid" style={{
              background: "transparent", border: "1px solid var(--hairline-2)",
              width: 22, height: 22, display: "grid", placeItems: "center",
              color: "var(--muted)", cursor: "default", flexShrink: 0,
            }}>
              <CollapseIco size={12} />
            </button>
          )}
        </div>
      )}
      <div style={{ flex: 1, overflow: "auto", padding: "6px 0" }}>
        <TreeNode node={collection} currentPath={currentPath}
          onSelect={onSelect} openMap={openMap} setOpenMap={setOpenMap} />
      </div>
    </div>
  );
}

/* ─────────────── facets panel ─────────────── */

const FACET_GROUPS = [
  { id: "type", title: "Format", items: [
    { id: "photograph", l: "Photograph", c: 412 },
    { id: "contact",    l: "Contact sheet", c: 22 },
    { id: "neg",        l: "Negative", c: 88 },
    { id: "map",        l: "Map", c: 36 },
    { id: "doc",        l: "Document", c: 31 },
    { id: "audio",      l: "Audio", c: 14 },
  ]},
  { id: "date", title: "Date", items: [
    { id: "20-24", l: "2020 – 2024", c: 198 },
    { id: "10-19", l: "2010 – 2019", c: 287 },
    { id: "00-09", l: "2000 – 2009", c: 47 },
  ]},
  { id: "lang", title: "Language", items: [
    { id: "en", l: "English", c: 380 },
    { id: "nl", l: "Dutch", c: 64 },
    { id: "pt", l: "Portuguese", c: 28 },
  ]},
  { id: "photographer", title: "Photographer", items: [
    { id: "ades", l: "M. Adesanya", c: 218 },
    { id: "holm", l: "L. Holmberg", c: 142 },
    { id: "park", l: "C. Park", c: 96 },
  ]},
];

function FacetsCollectionPanel({ selected, onToggle, onClear, title = "Refine", onCollapse }) {
  return (
    <div style={{ fontFamily: COL_FONT.sans, color: "var(--ink)", height: "100%", overflow: "auto" }}>
      <div style={{
        padding: "12px 14px 8px", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8,
      }}>
        <ColSmallCaps style={{ color: "var(--ink)" }}>{title}</ColSmallCaps>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          {Object.values(selected).flat().length > 0 && (
            <span onClick={onClear} style={{ fontSize: 10.5, color: "var(--muted)", textDecoration: "underline", cursor: "default" }}>Clear</span>
          )}
          {onCollapse && (
            <button onClick={onCollapse} title="Collapse refine" style={{
              background: "transparent", border: "1px solid var(--hairline-2)",
              width: 22, height: 22, display: "grid", placeItems: "center",
              color: "var(--muted)", cursor: "default",
            }}>
              <CollapseIco size={12} />
            </button>
          )}
        </div>
      </div>
      {FACET_GROUPS.map((g) => (
        <div key={g.id} style={{ padding: "10px 14px", borderTop: "1px solid var(--hairline)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingBottom: 6 }}>
            <ColSmallCaps style={{ color: "var(--ink-2)", fontSize: 9.5 }}>{g.title}</ColSmallCaps>
            <ColChevron open size={9} />
          </div>
          {g.items.map((it) => {
            const on = (selected[g.id] || []).includes(it.id);
            return (
              <div key={it.id} onClick={() => onToggle(g.id, it.id)} style={{
                display: "grid", gridTemplateColumns: "14px 1fr auto", alignItems: "center", gap: 8,
                padding: "3px 0", fontSize: 12, cursor: "default",
              }}>
                <span style={{
                  width: 12, height: 12, border: `1.5px solid ${on ? "var(--accent)" : "var(--hairline-2)"}`,
                  background: on ? "var(--accent)" : "transparent", color: "var(--accent-ink)",
                  display: "grid", placeItems: "center", fontSize: 9,
                }}>{on ? "✓" : ""}</span>
                <span>{it.l}</span>
                <span style={{ fontFamily: COL_FONT.mono, fontSize: 10.5, color: "var(--muted)" }}>{it.c}</span>
              </div>
            );
          })}
        </div>
      ))}
    </div>
  );
}

/* ─────────────── hero ─────────────── */

function CollectionHero({ collection, crumbs, currentNode, onCrumb, height = 220 }) {
  const [a, b, c] = collection.palette;
  return (
    <div style={{
      position: "relative", height, overflow: "hidden",
      background: `linear-gradient(110deg, ${a} 0%, ${b} 50%, ${c || b} 100%)`,
    }}>
      <svg viewBox="0 0 1200 220" preserveAspectRatio="none"
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0.16 }}>
        <defs>
          <pattern id={`heropat-${a.replace("#", "")}`} width="14" height="14" patternUnits="userSpaceOnUse">
            <circle cx="2" cy="2" r="1" fill="#fbf8ef" />
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill={`url(#heropat-${a.replace("#", "")})`} />
        <path d="M0 150 Q300 110 600 150 T1200 130 L1200 220 L0 220 Z" fill="#fbf8ef" opacity="0.12" />
        <path d="M0 180 Q300 150 600 180 T1200 170 L1200 220 L0 220 Z" fill="#fbf8ef" opacity="0.18" />
      </svg>
      <div style={{
        position: "absolute", inset: 0, padding: "20px 28px 22px",
        display: "flex", flexDirection: "column", justifyContent: "space-between",
        color: "var(--surface)",
      }}>
        {/* breadcrumbs */}
        <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 0 }}>
          {crumbs.map((n, i) => {
            const isLast = i === crumbs.length - 1;
            return (
              <span key={n.id} style={{ display: "inline-flex", alignItems: "center" }}>
                <span onClick={() => !isLast && onCrumb(i)} style={{
                  fontFamily: COL_FONT.sans, fontSize: 12.5,
                  color: isLast ? "var(--surface)" : "rgba(251,248,239,0.78)",
                  textDecoration: isLast ? "none" : "underline", textUnderlineOffset: 3,
                  fontWeight: isLast ? 500 : 400, cursor: "default",
                  textWrap: "nowrap",
                }}>{i === 0 ? "Collection Discovery" : (n.shortName || n.name)}</span>
                {!isLast && (
                  <span style={{ margin: "0 8px", color: "rgba(251,248,239,0.55)", fontSize: 12 }}>/</span>
                )}
              </span>
            );
          })}
        </div>
        <div>
          <h1 style={{
            fontFamily: COL_FONT.serif, margin: 0,
            fontSize: 30, fontWeight: 500, letterSpacing: "-0.01em",
            lineHeight: 1.1, textWrap: "balance", maxWidth: "30ch",
          }}>{currentNode.name}</h1>
          <div style={{
            marginTop: 8, fontSize: 12.5, opacity: 0.86, display: "flex", gap: 12, alignItems: "center",
            fontFamily: COL_FONT.sans, flexWrap: "wrap",
          }}>
            <span>{collection.contributor} · {collection.dates}</span>
            <span style={{ opacity: 0.5 }}>|</span>
            <span style={{ letterSpacing: "0.14em", textTransform: "uppercase", fontSize: 9.5, fontWeight: 600 }}>
              {collection.type}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ─────────────── overview block (shown only at collection root) ─────────────── */

function OverviewBlock({ collection }) {
  return (
    <div style={{
      display: "grid", gridTemplateColumns: "1fr 280px", gap: 36,
      padding: "24px 28px", borderBottom: "1px solid var(--hairline)",
    }}>
      <div>
        <ColSmallCaps>Collection overview</ColSmallCaps>
        <div style={{
          marginTop: 12, display: "grid", gridTemplateColumns: "120px 1fr",
          rowGap: 8, fontSize: 13, fontFamily: COL_FONT.sans,
        }}>
          <span style={{ color: "var(--muted)" }}>Repository</span>
          <strong style={{ fontWeight: 500 }}>{collection.repository}</strong>
          <span style={{ color: "var(--muted)" }}>Extent</span>
          <strong style={{ fontWeight: 500 }}>{collection.extent}</strong>
          <span style={{ color: "var(--muted)" }}>Language</span>
          <strong style={{ fontWeight: 500 }}>{collection.language}</strong>
          <span style={{ color: "var(--muted)" }}>Dates</span>
          <strong style={{ fontWeight: 500 }}>{collection.dates}</strong>
          <span style={{ color: "var(--muted)" }}>Call number</span>
          <strong style={{ fontWeight: 500, fontFamily: COL_FONT.mono, fontSize: 12 }}>{collection.callNumber}</strong>
        </div>
        <hr style={{ border: 0, borderTop: "1px solid var(--hairline)", margin: "20px 0" }} />
        <ColSmallCaps>Summary</ColSmallCaps>
        <p style={{
          margin: "10px 0 0", fontFamily: COL_FONT.serif, fontSize: 16, lineHeight: 1.55,
          color: "var(--ink)", maxWidth: "62ch", textWrap: "pretty",
        }}>{collection.summary}</p>
        <hr style={{ border: 0, borderTop: "1px solid var(--hairline)", margin: "20px 0" }} />
        <ColSmallCaps>Scope and content</ColSmallCaps>
        <ul style={{
          margin: "10px 0 0", paddingLeft: 18, fontFamily: COL_FONT.sans, fontSize: 13.5,
          color: "var(--ink-2)", lineHeight: 1.55,
        }}>
          {collection.scope.map((s) => <li key={s} style={{ paddingBottom: 4 }}>{s}</li>)}
        </ul>
      </div>
      <div>
        <div style={{ border: "1px solid var(--hairline)", background: "var(--surface)", padding: 14 }}>
          <ColSmallCaps>Featured</ColSmallCaps>
          <div style={{ marginTop: 10 }}>
            <CoverHero palette={collection.palette} height={160} />
          </div>
          <div style={{
            marginTop: 8, fontSize: 11.5, color: "var(--muted)", fontFamily: COL_FONT.sans,
          }}>
            Rotterdam, Maeslantkering · 2014
          </div>
        </div>
      </div>
    </div>
  );
}

/* ─────────────── results toolbar + grid ─────────────── */

function ContentToolbar({
  showFilterButton, total, current, scope, searchValue, setSearchValue,
  selectedFacets, layout, setLayout,
}) {
  const activeChips = [];
  Object.entries(selectedFacets).forEach(([gid, ids]) => {
    const group = FACET_GROUPS.find((g) => g.id === gid);
    if (!group) return;
    ids.forEach((id) => {
      const it = group.items.find((x) => x.id === id);
      if (it) activeChips.push({ gid, id, label: it.l });
    });
  });

  return (
    <div style={{ padding: "16px 28px 0", fontFamily: COL_FONT.sans }}>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        gap: 12, flexWrap: "wrap",
      }}>
        <div style={{ fontSize: 13, color: "var(--muted)" }}>
          Showing <span style={{ fontFamily: COL_FONT.mono, color: "var(--ink)" }}>{total}</span> of <span style={{ fontFamily: COL_FONT.mono, color: "var(--ink)" }}>{total}</span> in {scope}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            border: "1px solid var(--hairline-2)", padding: "4px 8px", width: 240,
          }}>
            <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.6" style={{ color: "var(--muted)" }}>
              <circle cx="11" cy="11" r="6.5" /><path d="M20 20l-4.2-4.2" />
            </svg>
            <input
              value={searchValue} onChange={(e) => setSearchValue(e.target.value)}
              placeholder="Search within…"
              style={{
                background: "transparent", border: 0, outline: "none",
                fontFamily: COL_FONT.sans, fontSize: 12.5, color: "var(--ink)", flex: 1,
              }}
            />
          </div>
          <span style={{ fontSize: 11.5, color: "var(--muted)" }}>Sort</span>
          <span style={{ fontSize: 12.5, color: "var(--ink)", fontWeight: 500 }}>Newest ▾</span>
          <span style={{ color: "var(--hairline-2)" }}>|</span>
          <div style={{ display: "inline-flex", border: "1px solid var(--hairline-2)" }}>
            <span onClick={() => setLayout("grid")} style={{
              width: 26, height: 26, display: "grid", placeItems: "center",
              background: layout === "grid" ? "var(--ink)" : "transparent",
              color: layout === "grid" ? "var(--paper)" : "var(--ink-2)",
              fontSize: 13, cursor: "default",
            }}>▦</span>
            <span onClick={() => setLayout("list")} style={{
              width: 26, height: 26, display: "grid", placeItems: "center",
              background: layout === "list" ? "var(--ink)" : "transparent",
              color: layout === "list" ? "var(--paper)" : "var(--ink-2)",
              fontSize: 13, cursor: "default",
            }}>≡</span>
          </div>
        </div>
      </div>

      {/* filter row */}
      <div style={{
        marginTop: 12, display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap",
      }}>
        {showFilterButton && (
          <button style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            background: "var(--ink)", color: "var(--paper)", border: 0, padding: "6px 11px",
            fontFamily: COL_FONT.sans, fontSize: 12, fontWeight: 500, cursor: "default",
          }}>
            <FilterIco size={12} /> All filters
          </button>
        )}
        {activeChips.length === 0 && (
          <span style={{ fontSize: 11.5, color: "var(--muted)" }}>No filters applied</span>
        )}
        {activeChips.map((c) => (
          <span key={c.gid + c.id} style={{
            display: "inline-flex", alignItems: "center", gap: 5,
            padding: "4px 9px", fontSize: 11.5,
            background: "var(--ink)", color: "var(--paper)",
          }}>
            {c.label}
            <svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M5 5l14 14M19 5L5 19" />
            </svg>
          </span>
        ))}
      </div>
    </div>
  );
}

function ContentGrid({ cards, layout, onOpenFolder, gridCols }) {
  if (cards.length === 0) {
    return (
      <div style={{ padding: "48px 28px", color: "var(--muted)", fontFamily: COL_FONT.sans, fontSize: 13.5 }}>
        Nothing in this folder yet.
      </div>
    );
  }

  const isList = layout === "list";
  const gridTemplate = isList
    ? "1fr"
    : (gridCols ? `repeat(${gridCols}, minmax(0, 1fr))` : "repeat(auto-fill, minmax(220px, 1fr))");

  return (
    <div style={{
      padding: "16px 28px 28px",
      display: "grid",
      gridTemplateColumns: gridTemplate,
      gap: isList ? 0 : 14,
    }}>
      {cards.map((card) => (
        <CardItem key={card.kind + "-" + card.id} card={card} layout={layout} onOpenFolder={onOpenFolder} />
      ))}
    </div>
  );
}

function CardItem({ card, layout, onOpenFolder }) {
  const [saved, setSaved] = useStateC(false);
  const isFolder = card.kind === "folder";

  if (layout === "list") {
    return (
      <div onClick={isFolder ? () => onOpenFolder(card.id) : undefined} style={{
        display: "grid", gridTemplateColumns: "80px 1fr auto", gap: 16,
        padding: "12px 0", borderBottom: "1px solid var(--hairline)",
        alignItems: "center", cursor: "default",
      }}>
        <div style={{ height: 56, overflow: "hidden" }}>
          {isFolder
            ? <CoverMosaic palette={card.palette} height={56} />
            : <CoverHero palette={card.palette} height={56} label={card.type} />}
        </div>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            {isFolder && <FolderIco size={12} />}
            <ColSmallCaps style={{ fontSize: 9.5 }}>
              {isFolder ? "Collection" : card.type}
            </ColSmallCaps>
          </div>
          <div style={{
            fontFamily: COL_FONT.serif, fontSize: 16, fontWeight: 500,
            color: isFolder ? "var(--accent)" : "var(--ink)", marginTop: 2,
            textDecoration: isFolder ? "underline" : "none", textUnderlineOffset: 3,
          }}>{card.title}</div>
          {!isFolder && (
            <div style={{ fontFamily: COL_FONT.mono, fontSize: 10.5, color: "var(--muted)", marginTop: 2 }}>
              {card.callNumber} · {card.year}
            </div>
          )}
        </div>
        <div style={{ display: "flex", gap: 8, color: "var(--muted)" }}>
          {isFolder && <span style={{ fontFamily: COL_FONT.mono, fontSize: 11 }}>{card.count} items</span>}
          <span onClick={(e) => { e.stopPropagation(); setSaved(!saved); }} style={{ cursor: "default" }}>
            <BookmarkIco filled={saved} />
          </span>
          {isFolder && <InfoIco />}
        </div>
      </div>
    );
  }

  return (
    <article
      onClick={isFolder ? () => onOpenFolder(card.id) : undefined}
      style={{
        border: "1px solid var(--hairline)", background: "var(--surface)",
        display: "flex", flexDirection: "column", cursor: "default",
      }}
    >
      {isFolder
        ? <CoverMosaic palette={card.palette} height={140} />
        : <CoverHero palette={card.palette} height={140} label={card.type} />}
      <div style={{ padding: "10px 12px 12px", display: "flex", flexDirection: "column", gap: 4 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            {isFolder && <FolderIco size={11} />}
            <ColSmallCaps style={{ fontSize: 9 }}>
              {isFolder ? "Collection" : card.type}
            </ColSmallCaps>
          </div>
          <div style={{ display: "flex", gap: 6, color: "var(--muted)" }}>
            <span onClick={(e) => { e.stopPropagation(); setSaved(!saved); }} style={{ cursor: "default" }}>
              <BookmarkIco filled={saved} />
            </span>
            {isFolder && <InfoIco />}
          </div>
        </div>
        <div style={{
          fontFamily: COL_FONT.serif, fontSize: 15.5, fontWeight: 500, lineHeight: 1.25,
          color: isFolder ? "var(--accent)" : "var(--ink)",
          textDecoration: isFolder ? "underline" : "none", textUnderlineOffset: 3,
          textWrap: "pretty",
        }}>{card.title}</div>
        <div style={{ fontFamily: COL_FONT.mono, fontSize: 10.5, color: "var(--muted)", marginTop: 2 }}>
          {isFolder ? `${card.count} items` : `${card.callNumber} · ${card.year}`}
        </div>
      </div>
    </article>
  );
}

/* ─────────────── layout mini-diagrams ─────────────── */

function LayoutDiagram({ layout, size = 56 }) {
  const h = size * 0.6;
  const props = { width: size, height: h, viewBox: `0 0 80 48`, style: { display: "block" } };
  if (layout === "v1") {
    return (
      <svg {...props}>
        <rect x="1" y="1" width="18" height="46" fill="currentColor" opacity="0.85" />
        <rect x="20" y="1" width="18" height="46" fill="currentColor" opacity="0.5" />
        <rect x="39" y="1" width="40" height="46" fill="currentColor" opacity="0.15" />
      </svg>
    );
  }
  if (layout === "v2") {
    return (
      <svg {...props}>
        <rect x="1" y="1" width="7" height="46" fill="currentColor" opacity="0.95" />
        <rect x="9" y="1" width="22" height="46" fill="currentColor" opacity="0.5" />
        <rect x="32" y="1" width="47" height="46" fill="currentColor" opacity="0.15" />
      </svg>
    );
  }
  return (
    <svg {...props}>
      <rect x="1" y="1" width="12" height="8" fill="currentColor" opacity="0.85" />
      <rect x="14" y="1" width="12" height="8" fill="currentColor" opacity="0.35" />
      <rect x="1" y="10" width="25" height="37" fill="currentColor" opacity="0.5" />
      <rect x="27" y="1" width="52" height="46" fill="currentColor" opacity="0.15" />
    </svg>
  );
}

/* ─────────────── prototype chip (thin strip inside discovery) ─────────────── */

function PrototypeChip({ layout, label, onBack }) {
  const num = layout === "v1" ? "01" : layout === "v2" ? "02" : "03";
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 12, padding: "8px 28px",
      background: "var(--ink)", color: "var(--paper)",
      fontFamily: COL_FONT.sans, fontSize: 12,
    }}>
      <span style={{ color: "var(--paper)", display: "inline-flex" }}>
        <LayoutDiagram layout={layout} size={28} />
      </span>
      <span style={{
        fontFamily: COL_FONT.mono, fontSize: 9.5, letterSpacing: "0.14em",
        textTransform: "uppercase", background: "var(--accent)", color: "var(--accent-ink)",
        padding: "2px 7px", fontWeight: 600,
      }}>Prototype {num}</span>
      <span style={{ fontWeight: 500 }}>{label}</span>
      <span style={{ color: "rgba(243,238,226,0.55)" }}>· viewing layout {layout.toUpperCase()}</span>
      <div style={{ flex: 1 }} />
      <span onClick={onBack} style={{
        cursor: "default", color: "rgba(243,238,226,0.85)",
        textDecoration: "underline", textUnderlineOffset: 3,
      }}>See the other prototypes →</span>
    </div>
  );
}

/* ─────────────── LOBBY screen ─────────────── */

function CollectionsLobbyScreen({ onOpenCollection }) {
  const D = window.LD_COLLECTIONS_FULL;

  return (
    <div style={{ maxWidth: 1248, margin: "0 auto", padding: "0 0 80px" }}>
      <div style={{ padding: "44px 28px 32px" }}>
        <ColSmallCaps style={{ color: "var(--accent)" }}>Collection Discovery · 3 Layout Prototypes</ColSmallCaps>
        <h1 style={{
          margin: "10px 0 0", fontFamily: COL_FONT.serif, fontSize: 46, fontWeight: 500,
          letterSpacing: "-0.015em", lineHeight: 1.04, textWrap: "balance", maxWidth: "20ch",
        }}>
          Three ways to explore the archive.
        </h1>
        <p style={{
          margin: "14px 0 0", fontFamily: COL_FONT.serif, fontStyle: "italic",
          fontSize: 17, color: "var(--muted)", maxWidth: "58ch", lineHeight: 1.5,
        }}>
          Each collection below opens in a different navigation layout — same content,
          same capabilities. The question being answered: where do the hierarchy tree
          and the refine panel live when both are needed?
        </p>
      </div>

      <div style={{
        padding: "4px 28px 28px",
        display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 22,
      }}>
        {D.LOBBY.map((c) => (
          <PrototypeCard key={c.id} c={c} onClick={() => onOpenCollection(c.id)} />
        ))}
      </div>
    </div>
  );
}

function PrototypeCard({ c, onClick }) {
  const num = c.prototypeLayout === "v1" ? "01" : c.prototypeLayout === "v2" ? "02" : "03";
  return (
    <article onClick={onClick} style={{
      background: "var(--surface)", border: "1px solid var(--hairline)",
      display: "flex", flexDirection: "column", cursor: "default", position: "relative",
    }}>
      {c.coverKind === "mosaic-4"
        ? <CoverMosaic palette={c.palette} height={180} />
        : <CoverHero palette={c.palette} height={180} label={c.dateRange} />}
      <div style={{
        position: "absolute", top: 12, left: 12, right: 12,
        display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8,
      }}>
        <span style={{
          display: "inline-flex", alignItems: "center", gap: 7,
          background: "var(--ink)", color: "var(--paper)",
          padding: "5px 9px",
          fontFamily: COL_FONT.mono, fontSize: 10, letterSpacing: "0.10em",
          textTransform: "uppercase", fontWeight: 600,
        }}>
          <span style={{ color: "var(--paper)", display: "inline-flex" }}>
            <LayoutDiagram layout={c.prototypeLayout} size={26} />
          </span>
          Prototype {num} · {c.prototypeLabel}
        </span>
      </div>
      <div style={{ padding: "18px 18px 20px", display: "flex", flexDirection: "column", gap: 8, flex: 1 }}>
        <ColSmallCaps>
          <FolderIco size={10} style={{ verticalAlign: "-1px", marginRight: 4 }} /> Collection
        </ColSmallCaps>
        <div style={{
          fontFamily: COL_FONT.serif, fontSize: 21, fontWeight: 500, lineHeight: 1.18,
          color: "var(--accent)", textDecoration: "underline", textUnderlineOffset: 3,
          textWrap: "pretty",
        }}>{c.name}</div>
        <p style={{
          margin: 0, fontFamily: COL_FONT.sans, fontSize: 13, color: "var(--muted)",
          lineHeight: 1.5, flex: 1,
        }}>{c.blurb}</p>
        <div style={{
          marginTop: 4, padding: "10px 12px", background: "var(--paper-2)",
          fontFamily: COL_FONT.sans, fontSize: 12.5, color: "var(--ink-2)",
          borderLeft: "2px solid var(--accent)", lineHeight: 1.45,
        }}>
          <span style={{ fontFamily: COL_FONT.mono, fontSize: 10, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--accent)", fontWeight: 600 }}>
            Layout · {c.prototypeLayout.toUpperCase()}
          </span>
          <div style={{ marginTop: 4 }}>{c.prototypeBlurb}</div>
        </div>
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          marginTop: 6, paddingTop: 12, borderTop: "1px solid var(--hairline)",
        }}>
          <div style={{ fontFamily: COL_FONT.mono, fontSize: 11, color: "var(--ink-2)" }}>
            {c.itemCount.toLocaleString()} items · {c.dateRange}
          </div>
          <span style={{
            fontFamily: COL_FONT.sans, fontSize: 12.5, fontWeight: 600, color: "var(--accent)",
          }}>Open prototype →</span>
        </div>
      </div>
    </article>
  );
}

/* ─────────────── DISCOVERY screen (parameterized by variant) ─────────────── */

function CollectionDiscoveryScreen({ collectionId, onBackToLobby }) {
  const D = window.LD_COLLECTIONS_FULL;
  const lobbyEntry = D.LOBBY.find((l) => l.id === collectionId) || D.LOBBY[0];
  const variant = lobbyEntry.prototypeLayout;
  const collectionData = {
    "coastal-adaptation": D.COASTAL,
    "wexler-maps": D.WEXLER,
    "faculty-papers": D.FACULTY,
  };
  const collection = collectionData[collectionId] || D.COASTAL;

  const [path, setPath] = useStateC([]);          // ids from collection root → current
  const [openMap, setOpenMap] = useStateC({});    // tree open/closed by id
  const [selectedFacets, setSelectedFacets] = useStateC({});
  const [layout, setLayout] = useStateC("grid");
  const [searchValue, setSearchValue] = useStateC("");
  const [v2Mode, setV2Mode] = useStateC("tree");   // for V2: which panel is active
  const [v4Tab, setV4Tab] = useStateC("tree");     // for V4: which tab
  const [v1HCollapsed, setV1HCollapsed] = useStateC(false);
  const [v1FCollapsed, setV1FCollapsed] = useStateC(false);

  // Reset path when switching collections
  useEffectC(() => { setPath([]); }, [collectionId]);

  const crumbs = useMemoC(() => crumbsOf(collection, path), [collection, path]);
  const currentNode = useMemoC(() => nodeAt(collection, path), [collection, path]);
  const cards = useMemoC(() => cardsAt(currentNode), [currentNode]);

  function onSelect(nodeId) {
    // Walk full tree to find the path to nodeId
    const found = findPath(collection, nodeId);
    if (found) setPath(found.slice(1)); // drop root
  }

  function onCrumb(idx) {
    setPath(crumbs.slice(1, idx + 1).map((n) => n.id));
  }

  function onOpenFolder(id) {
    setPath([...path, id]);
  }

  function toggleFacet(gid, id) {
    setSelectedFacets((s) => {
      const cur = s[gid] || [];
      const nxt = cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id];
      return { ...s, [gid]: nxt };
    });
  }

  // Common content (overview + toolbar + grid). Built as a function so
  // the grid can adapt to V1's collapse state.
  const atRoot = path.length === 0;
  const scopeLabel = atRoot ? "this collection" : currentNode.name;

  function renderContent(gridCols) {
    return (
      <main style={{ overflow: "auto", minHeight: 0 }}>
        <CollectionHero
          collection={collection}
          crumbs={crumbs}
          currentNode={currentNode}
          onCrumb={onCrumb}
          height={atRoot ? 220 : 180}
        />
        <div style={{ padding: "10px 28px", display: "flex", justifyContent: "space-between", alignItems: "center", borderBottom: "1px solid var(--hairline)" }}>
          <span style={{ fontSize: 12, color: "var(--muted)", fontFamily: COL_FONT.sans }}>
            <span onClick={onBackToLobby} style={{ color: "var(--accent)", textDecoration: "underline", textUnderlineOffset: 3, cursor: "default" }}>← Back to all collections</span>
          </span>
          <span style={{ fontFamily: COL_FONT.mono, fontSize: 11, color: "var(--muted)" }}>
            {collection.callNumber}
          </span>
        </div>
        {atRoot && <OverviewBlock collection={collection} />}
        <ContentToolbar
          showFilterButton={variant === "v2"}
          total={cards.length}
          current={currentNode.name}
          scope={scopeLabel}
          searchValue={searchValue} setSearchValue={setSearchValue}
          selectedFacets={selectedFacets}
          layout={layout} setLayout={setLayout}
        />
        <ContentGrid cards={cards} layout={layout} onOpenFolder={onOpenFolder} gridCols={gridCols} />
      </main>
    );
  }

  /* ── layout shells ── */

  if (variant === "v1") {
    const hCol = v1HCollapsed ? "44px" : "224px";
    const fCol = v1FCollapsed ? "44px" : "224px";
    const opened = (v1HCollapsed ? 0 : 1) + (v1FCollapsed ? 0 : 1);
    const gridCols = opened === 0 ? 6 : opened === 1 ? 5 : 4;
    return (
      <div>
        <PrototypeChip layout="v1" label={lobbyEntry.prototypeLabel} onBack={onBackToLobby} />
        <div style={{ maxWidth: 1248, margin: "0 auto", height: "calc(100vh - 174px)",
          display: "grid", gridTemplateColumns: `${hCol} ${fCol} 1fr`,
          borderLeft: "1px solid var(--hairline)", borderRight: "1px solid var(--hairline)",
          background: "var(--paper)", transition: "grid-template-columns .18s ease",
        }}>
        <aside style={{ borderRight: "1px solid var(--hairline)", background: "var(--surface)", overflow: "hidden", display: "flex", flexDirection: "column" }}>
          {v1HCollapsed ? (
            <CollapsedRail
              label="Finding aid"
              icon={<TreeIco size={14} />}
              onClick={() => setV1HCollapsed(false)}
            />
          ) : (
            <HierarchyPanel
              collection={collection}
              currentPath={[collection.id, ...path]}
              onSelect={onSelect}
              openMap={openMap}
              setOpenMap={setOpenMap}
              onCollapse={() => setV1HCollapsed(true)}
            />
          )}
        </aside>
        <aside style={{ borderRight: "1px solid var(--hairline)", background: "var(--paper-2)", overflow: "hidden" }}>
          {v1FCollapsed ? (
            <CollapsedRail
              label="Refine"
              icon={<FilterIco size={14} />}
              onClick={() => setV1FCollapsed(false)}
              background="var(--paper-2)"
            />
          ) : (
            <FacetsCollectionPanel
              selected={selectedFacets}
              onToggle={toggleFacet}
              onClear={() => setSelectedFacets({})}
              onCollapse={() => setV1FCollapsed(true)}
            />
          )}
        </aside>
        {renderContent(gridCols)}
        </div>
      </div>
    );
  }

  if (variant === "v2") {
    return (
      <div>
        <PrototypeChip layout="v2" label={lobbyEntry.prototypeLabel} onBack={onBackToLobby} />
        <div style={{ maxWidth: 1248, margin: "0 auto", height: "calc(100vh - 174px)",
          display: "grid", gridTemplateColumns: "52px 248px 1fr",
          borderLeft: "1px solid var(--hairline)", borderRight: "1px solid var(--hairline)",
          background: "var(--paper)",
        }}>
        <aside style={{
          background: "var(--ink)", color: "var(--surface)",
          display: "flex", flexDirection: "column", alignItems: "center", padding: "12px 0", gap: 4,
        }}>
          <V2RailBtn icon={<TreeIco size={15} />} active={v2Mode === "tree"} onClick={() => setV2Mode("tree")} label="Tree" />
          <V2RailBtn icon={<FilterIco size={15} />} active={v2Mode === "filter"} onClick={() => setV2Mode("filter")} label="Filters"
            badge={Object.values(selectedFacets).flat().length || null} />
          <V2RailBtn icon={<BookmarkIco size={15} />} label="Saved" />
          <div style={{ flex: 1 }} />
          <div style={{
            writingMode: "vertical-rl", transform: "rotate(180deg)",
            fontFamily: COL_FONT.sans, fontSize: 9.5, letterSpacing: "0.18em",
            textTransform: "uppercase", color: "rgba(251,248,239,0.5)", padding: "8px 0",
            maxHeight: 240, overflow: "hidden",
          }}>{crumbs.slice(1).map((n) => n.shortName || n.name).join(" › ") || "Collection root"}</div>
        </aside>
        <aside style={{
          borderRight: "1px solid var(--hairline)", background: "var(--surface)", overflow: "hidden", display: "flex", flexDirection: "column",
        }}>
          {v2Mode === "tree" ? (
            <HierarchyPanel
              collection={collection}
              currentPath={[collection.id, ...path]}
              onSelect={onSelect}
              openMap={openMap}
              setOpenMap={setOpenMap}
            />
          ) : (
            <FacetsCollectionPanel
              selected={selectedFacets}
              onToggle={toggleFacet}
              onClear={() => setSelectedFacets({})}
              title="Filters"
            />
          )}
        </aside>
        {renderContent(null)}
        </div>
      </div>
    );
  }

  // variant === "v4"
  return (
    <div>
      <PrototypeChip layout="v4" label={lobbyEntry.prototypeLabel} onBack={onBackToLobby} />
      <div style={{ maxWidth: 1248, margin: "0 auto", height: "calc(100vh - 174px)",
        display: "grid", gridTemplateColumns: "280px 1fr",
        borderLeft: "1px solid var(--hairline)", borderRight: "1px solid var(--hairline)",
        background: "var(--paper)",
      }}>
      <aside style={{
        borderRight: "1px solid var(--hairline-2)", background: "var(--paper-2)",
        overflow: "hidden", display: "flex", flexDirection: "column",
      }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", borderBottom: "1px solid var(--hairline-2)" }}>
          <V4Tab active={v4Tab === "tree"} onClick={() => setV4Tab("tree")}>
            <TreeIco size={12} /> Hierarchy
          </V4Tab>
          <V4Tab active={v4Tab === "filter"} onClick={() => setV4Tab("filter")}>
            <FilterIco size={12} /> Filters
            {Object.values(selectedFacets).flat().length > 0 && (
              <span style={{
                marginLeft: 4, fontFamily: COL_FONT.mono, fontSize: 10,
                background: "var(--accent)", color: "var(--accent-ink)", padding: "0 5px",
              }}>{Object.values(selectedFacets).flat().length}</span>
            )}
          </V4Tab>
        </div>
        {v4Tab === "tree" ? (
          <HierarchyPanel
            collection={collection}
            currentPath={[collection.id, ...path]}
            onSelect={onSelect}
            openMap={openMap}
            setOpenMap={setOpenMap}
          />
        ) : (
          <div style={{ flex: 1, background: "var(--surface)", overflow: "hidden" }}>
            <FacetsCollectionPanel
              selected={selectedFacets}
              onToggle={toggleFacet}
              onClear={() => setSelectedFacets({})}
              title="Filters"
            />
          </div>
        )}
      </aside>
      {renderContent(null)}
      </div>
    </div>
  );
}

/* ── helpers ── */
function findPath(root, targetId) {
  if (root.id === targetId) return [root.id];
  if (!root.children) return null;
  for (const c of root.children) {
    const p = findPath(c, targetId);
    if (p) return [root.id, ...p];
  }
  return null;
}

function V2RailBtn({ icon, active, label, badge, onClick }) {
  return (
    <div onClick={onClick} title={label} style={{
      width: 40, height: 40, display: "grid", placeItems: "center", position: "relative", cursor: "default",
      background: active ? "var(--accent)" : "transparent",
      color: active ? "var(--accent-ink)" : "var(--surface)",
    }}>
      {icon}
      {badge && (
        <span style={{
          position: "absolute", top: 4, right: 4, minWidth: 14, height: 14,
          background: "var(--accent)", color: "var(--accent-ink)", fontFamily: COL_FONT.mono, fontSize: 9,
          display: "grid", placeItems: "center", borderRadius: 999,
        }}>{badge}</span>
      )}
    </div>
  );
}

function V4Tab({ children, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      display: "inline-flex", alignItems: "center", gap: 6, justifyContent: "center",
      padding: "10px 8px", background: active ? "var(--surface)" : "transparent", border: 0,
      borderBottom: active ? "2px solid var(--accent)" : "2px solid transparent",
      color: active ? "var(--ink)" : "var(--muted)", fontFamily: COL_FONT.sans,
      fontSize: 12, fontWeight: 500, cursor: "default",
    }}>{children}</button>
  );
}

Object.assign(window, {
  CollectionsLobbyScreen,
  CollectionDiscoveryScreen,
});
