/* global React, ReactDOM */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "library",
  "density": "balanced",
  "layout": "list",
  "showAIDefault": true,
  "serifTitles": true
}/*EDITMODE-END*/;

const THEMES = {
  library: {
    label: "Library",
    "--paper":      "#f3eee2",
    "--paper-2":    "#ece6d5",
    "--surface":    "#fbf8ef",
    "--ink":        "#1c1814",
    "--ink-2":      "#3a342c",
    "--muted":      "#6c655a",
    "--hairline":   "#d8cfba",
    "--hairline-2": "#c5b99c",
    "--accent":     "#6a1f23",
    "--accent-ink": "#fbf8ef",
    "--accent-soft":"#f0d8d4",
    "--tag":        "#efe8d4",
    "--good":       "#2f5a3a",
    "--warn":       "#8a4a1f",
  },
  forest: {
    label: "Forest",
    "--paper":      "#eef0e8",
    "--paper-2":    "#e2e7d8",
    "--surface":    "#f7f8f2",
    "--ink":        "#19251d",
    "--ink-2":      "#34403a",
    "--muted":      "#5e6a5e",
    "--hairline":   "#cdd5c4",
    "--hairline-2": "#a8b8a0",
    "--accent":     "#1f3a2e",
    "--accent-ink": "#f7f8f2",
    "--accent-soft":"#d4dfd1",
    "--tag":        "#dfe6d2",
    "--good":       "#1f5a3a",
    "--warn":       "#8a4a1f",
  },
  midnight: {
    label: "Midnight",
    "--paper":      "#0f1622",
    "--paper-2":    "#181f2d",
    "--surface":    "#141b27",
    "--ink":        "#ede7d3",
    "--ink-2":      "#cdc6b2",
    "--muted":      "#8a8470",
    "--hairline":   "#2c3447",
    "--hairline-2": "#3b465e",
    "--accent":     "#d4a358",
    "--accent-ink": "#0f1622",
    "--accent-soft":"#2d2a1d",
    "--tag":        "#1f2738",
    "--good":       "#8ec196",
    "--warn":       "#e0a86a",
  },
};

const DENSITY = {
  compact:  { fs: 14,   ws: 1.45 },
  balanced: { fs: 15,   ws: 1.5 },
  comfy:    { fs: 16,   ws: 1.55 },
};

function applyTheme(theme, density) {
  const t = THEMES[theme] || THEMES.library;
  Object.entries(t).forEach(([k, v]) => {
    if (k.startsWith("--")) document.documentElement.style.setProperty(k, v);
  });
  const d = DENSITY[density] || DENSITY.balanced;
  document.body.style.fontSize = d.fs + "px";
  document.body.style.lineHeight = d.ws;
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Read ?start=... to deep-link into a specific prototype (for sharing)
  const startParam = React.useMemo(() => {
    try {
      const u = new URL(window.location.href);
      return u.searchParams.get("start");
    } catch { return null; }
  }, []);
  const isSoloPrototype = startParam && (window.LD_COLLECTIONS_FULL?.LOBBY || []).some(l => l.id === startParam);

  const [route, setRoute] = React.useState(isSoloPrototype ? "collections-discover" : "home");
  const [activeId, setActiveId] = React.useState(null);
  const [activeCollectionId, setActiveCollectionId] = React.useState(isSoloPrototype ? startParam : null);
  const [query, setQuery] = React.useState("climate change adaptation");
  const [savedIds, setSavedIds] = React.useState([]);
  const [showAI, setShowAI] = React.useState(t.showAIDefault);

  React.useEffect(() => {
    applyTheme(t.theme, t.density);
  }, [t.theme, t.density]);

  React.useEffect(() => {
    setShowAI(t.showAIDefault);
  }, [t.showAIDefault]);

  function search(q) {
    if (typeof q === "string") setQuery(q);
    setRoute("results");
  }

  function openItem(id) {
    setActiveId(id);
    setRoute("detail");
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

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

  const activeItem = window.LD_DATA.RESULTS.find(r => r.id === activeId);
  const accentInk = "var(--ink)";

  function openCollection(id) {
    setActiveCollectionId(id);
    setRoute("collections-discover");
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  return (
    <div data-screen-label={
      route === "home" ? "Home" :
      route === "results" ? "Search Results" :
      route === "detail" ? "Item Detail" :
      route === "collections-lobby" ? "Collections Lobby" :
      route === "collections-discover" ? `Collection Discovery (${(window.LD_COLLECTIONS_FULL.LOBBY.find(l => l.id === activeCollectionId) || {}).prototypeLayout?.toUpperCase() || ""})` : ""
    }>
      <HeaderBar
        query={query}
        setQuery={setQuery}
        onSubmit={search}
        route={route}
        goto={(r) => { setRoute(r); }}
        savedCount={savedIds.length}
        accentInk={accentInk}
      />

      {route === "home" && (
        <HomeScreen onSearch={search} setQuery={setQuery} />
      )}
      {route === "results" && (
        <ResultsScreen
          query={query}
          layout={t.layout}
          onOpen={openItem}
          savedIds={savedIds}
          toggleSave={toggleSave}
          showAI={showAI}
          setShowAI={setShowAI}
        />
      )}
      {route === "detail" && activeItem && (
        <ItemDetailScreen
          item={activeItem}
          onBack={() => setRoute("results")}
          onOpen={openItem}
          savedIds={savedIds}
          toggleSave={toggleSave}
        />
      )}
      {route === "collections-lobby" && (
        <CollectionsLobbyScreen onOpenCollection={openCollection} />
      )}
      {route === "collections-discover" && (
        <CollectionDiscoveryScreen
          collectionId={activeCollectionId}
          onBackToLobby={() => setRoute("collections-lobby")}
        />
      )}

      <Footer />

      <TweaksPanel>
        <TweakSection label="Theme" />
        <TweakRadio
          label="Palette"
          value={t.theme}
          options={["library", "forest", "midnight"]}
          onChange={(v) => setTweak("theme", v)}
        />
        <TweakRadio
          label="Density"
          value={t.density}
          options={["compact", "balanced", "comfy"]}
          onChange={(v) => setTweak("density", v)}
        />

        <TweakSection label="Results layout" />
        <TweakRadio
          label="View"
          value={t.layout}
          options={["list", "card"]}
          onChange={(v) => setTweak("layout", v)}
        />

        <TweakSection label="Research assistant" />
        <TweakToggle
          label="Show by default"
          value={t.showAIDefault}
          onChange={(v) => setTweak("showAIDefault", v)}
        />

        <TweakSection label="Try" />
        <TweakButton onClick={() => { setRoute("home"); }}>Home</TweakButton>
        <TweakButton onClick={() => search("climate change adaptation")}>Search results</TweakButton>
        <TweakButton onClick={() => openItem("r1")}>Article detail (r1)</TweakButton>
        <TweakButton onClick={() => openItem("r2")}>Book detail (r2)</TweakButton>
        <TweakButton onClick={() => { setRoute("collections-lobby"); }}>Collection Discovery — 3 prototypes</TweakButton>
        <TweakButton onClick={() => openCollection("coastal-adaptation")}>→ Prototype 01 (Coastal, V1)</TweakButton>
        <TweakButton onClick={() => openCollection("wexler-maps")}>→ Prototype 02 (Wexler, V2)</TweakButton>
        <TweakButton onClick={() => openCollection("faculty-papers")}>→ Prototype 03 (Faculty, V4)</TweakButton>
      </TweaksPanel>
    </div>
  );
}

function Footer() {
  return (
    <footer style={{
      marginTop: 40, borderTop: "1px solid var(--hairline)",
      padding: "28px 32px",
      display: "grid", gridTemplateColumns: "1fr auto", gap: 24,
      maxWidth: 1480, margin: "40px auto 0", alignItems: "center",
      color: "var(--muted)", fontSize: 12.5,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
        <span style={{ width: 22, height: 22, display: "grid", placeItems: "center", background: "var(--ink)", color: "var(--paper)" }}>
          <Icon.Library width={12} height={12} />
        </span>
        <span>Eastbrook University Libraries · 1450 Wexler Way · Discovery powered by the EUL federated index</span>
      </div>
      <div style={{ display: "flex", gap: 18 }}>
        <a href="#" style={{ color: "var(--muted)", textDecoration: "none" }}>Accessibility</a>
        <a href="#" style={{ color: "var(--muted)", textDecoration: "none" }}>Privacy</a>
        <a href="#" style={{ color: "var(--muted)", textDecoration: "none" }}>Status</a>
        <span className="mono">v4.12</span>
      </div>
    </footer>
  );
}

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