/* ============================================================
   Lumino Design Site — Shared Chrome (React component)
   Renders the topbar, left nav, ⌘K search, theme switcher.
   Mounts via: <script type="text/babel" src="../core/chrome.jsx"></script>
               LuminoChrome.mount({ active: "tokens" })
   ============================================================ */

const LuminoChrome = (function () {
  const { useEffect, useMemo, useRef, useState, Fragment } = React;

  // Path prefix — `..` when we're inside /pages, /tools, /studio
  const inSubdir = /\/(pages|tools|studio)\//.test(location.pathname);
  const base = inSubdir ? ".." : ".";

  const SECTIONS = [
    { label: "Overview", items: [
      { id: "home", label: "Overview", href: `${base}/index.html`, icon: "home" },
      { id: "getting-started", label: "Getting Started", href: `${base}/pages/getting-started.html`, icon: "book" },
      { id: "changelog", label: "Changelog", href: `${base}/pages/changelog.html`, icon: "clock" },
    ]},
    { label: "Foundations", items: [
      { id: "tokens", label: "Tokens", href: `${base}/pages/tokens.html`, icon: "layers" },
      { id: "themes", label: "Themes", href: `${base}/pages/themes.html`, icon: "sparkle" },
      { id: "logo", label: "Logo", href: `${base}/pages/logo.html`, icon: "ping" },
      { id: "icons", label: "Icons", href: `${base}/pages/icons.html`, icon: "graph" },
      { id: "writing", label: "Writing", href: `${base}/pages/writing.html`, icon: "pencil" },
      { id: "accessibility", label: "Accessibility", href: `${base}/pages/accessibility.html`, icon: "check-circle" },
    ]},
    { label: "Library", items: [
      { id: "components", label: "Components", href: `${base}/pages/components.html`, icon: "layers" },
      { id: "patterns", label: "Patterns", href: `${base}/pages/patterns.html`, icon: "slides" },
    ]},
    { label: "Tools", items: [
      { id: "contrast", label: "Contrast Checker", href: `${base}/tools/contrast.html`, icon: "eye" },
      { id: "ruler", label: "Ruler Mode", href: `${base}/tools/ruler.html`, icon: "filter" },
      { id: "playground", label: "Playground", href: `${base}/tools/playground.html`, icon: "flask" },
    ]},
    { label: "Studio", items: [
      { id: "marketing", label: "Marketing Studio", href: `${base}/studio/marketing.html`, icon: "slides" },
      { id: "forge", label: "Theme Forge", href: `${base}/studio/theme-forge.html`, icon: "sparkle" },
      { id: "doodle", label: "Doodle Studio", href: `${base}/studio/doodle-studio.html`, icon: "sparkle" },
    ]},
    { label: "Resources", items: [
      { id: "downloads", label: "Downloads", href: `${base}/downloads/index.html`, icon: "upload" },
      { id: "changelog", label: "Changelog", href: `${base}/pages/changelog.html`, icon: "clock" },
    ]},
  ];

  const TOP_NAV = [
    { id: "home", label: "Overview", href: `${base}/index.html` },
    { id: "tokens", label: "Tokens", href: `${base}/pages/tokens.html` },
    { id: "components", label: "Components", href: `${base}/pages/components.html` },
    { id: "patterns", label: "Patterns", href: `${base}/pages/patterns.html` },
    { id: "marketing", label: "Studio", href: `${base}/studio/marketing.html` },
  ];

  function CommandK({ open, onClose }) {
    const [q, setQ] = useState("");
    const [focus, setFocus] = useState(0);
    const results = useMemo(() => window.LuminoSearch.search(q), [q]);
    const inputRef = useRef(null);

    useEffect(() => { if (open && inputRef.current) inputRef.current.focus(); }, [open]);
    useEffect(() => { setFocus(0); }, [q]);
    useEffect(() => {
      if (!open) return;
      const onKey = (e) => {
        if (e.key === "Escape") onClose();
        if (e.key === "ArrowDown") { e.preventDefault(); setFocus((f) => Math.min(f + 1, results.length - 1)); }
        if (e.key === "ArrowUp") { e.preventDefault(); setFocus((f) => Math.max(f - 1, 0)); }
        if (e.key === "Enter" && results[focus]) { window.location.href = results[focus].url; }
      };
      document.addEventListener("keydown", onKey);
      return () => document.removeEventListener("keydown", onKey);
    }, [open, focus, results, onClose]);

    if (!open) return null;
    return (
      <div className="lds-cmd" onClick={onClose}>
        <div className="lds-cmd-box" onClick={(e) => e.stopPropagation()}>
          <input ref={inputRef} className="lds-cmd-input" placeholder="Search tokens, components, pages…" value={q} onChange={(e) => setQ(e.target.value)} />
          <div className="lds-cmd-results">
            {results.length === 0 && <div style={{ padding: "20px 14px", color: "var(--color-text-tertiary)", fontSize: 13 }}>No results.</div>}
            {results.map((it, i) => (
              <a key={i} className={"lds-cmd-result " + (i === focus ? "focus" : "")}
                 href={it.url} onMouseEnter={() => setFocus(i)}>
                <span className="lds-cmd-result-title">{it.t}</span>
                <span className="lds-cmd-result-sub">{it.s}</span>
              </a>
            ))}
          </div>
        </div>
      </div>
    );
  }

  function Chrome({ active = "home", showNav = true, pageLabel }) {
    const [theme, setTheme] = useState(window.LuminoTheme.get());
    const [cmdOpen, setCmdOpen] = useState(false);
    const LuminoMark = window.LuminoMark;
    const Icon = window.Icon;

    useEffect(() => {
      const off = window.LuminoTheme.onChange(setTheme);
      const onKey = (e) => {
        if ((e.metaKey || e.ctrlKey) && e.key === "k") { e.preventDefault(); setCmdOpen(true); }
      };
      document.addEventListener("keydown", onKey);
      return () => document.removeEventListener("keydown", onKey);
    }, []);

    const setThemePatch = (p) => window.LuminoTheme.set(p);

    return (
      <Fragment>
        <header className="lds-top">
          <a href={`${base}/index.html`} className="lds-brand">
            <LuminoMark size={28} variant="accent" />
            <div className="lds-brand-text">
              <span className="lds-brand-name">Lumino</span>
              <span className="lds-brand-sub">Design System</span>
            </div>
          </a>
          <nav className="lds-top-nav">
            {TOP_NAV.map((n) => (
              <a key={n.id} href={n.href} className={active === n.id ? "active" : ""}>{n.label}</a>
            ))}
          </nav>
          <div className="lds-top-right">
            <button className="lds-search-btn" onClick={() => setCmdOpen(true)} aria-label="Search">
              <Icon name="search" size={14} />
              <span>Search</span>
              <kbd>⌘K</kbd>
            </button>
            <div className="lds-theme-pills" role="tablist" aria-label="Theme">
              {["pro", "studio", "playful"].map((t) => (
                <button key={t}
                  className={"lds-theme-pill " + (theme.theme === t ? "active" : "")}
                  onClick={() => setThemePatch({ theme: t })}>{t}</button>
              ))}
            </div>
            <button className="lds-mode-toggle" title={theme.mode === "dark" ? "Switch to light" : "Switch to dark"}
              onClick={() => setThemePatch({ mode: theme.mode === "dark" ? "light" : "dark" })}>
              <Icon name={theme.mode === "dark" ? "sun" : "moon"} size={16} />
            </button>
            <select className="lds-density-toggle" style={{ width: "auto", padding: "0 10px", background: "var(--color-surface-elevated)", border: "1px solid var(--color-border-hairline)", borderRadius: "var(--radius-md)", color: "var(--color-text-secondary)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.04em", textTransform: "uppercase" }}
              value={theme.density} onChange={(e) => setThemePatch({ density: e.target.value })}>
              <option value="compact">Compact</option>
              <option value="comfy">Comfy</option>
              <option value="spacious">Spacious</option>
            </select>
          </div>
        </header>
        <div className="lds-shell">
          {showNav && (
            <aside className="lds-side">
              {SECTIONS.map((sec) => (
                <div className="lds-side-section" key={sec.label}>
                  <div className="lds-side-label">{sec.label}</div>
                  {sec.items.map((it) => (
                    <a key={it.id} href={it.href} className={active === it.id ? "active" : ""}>
                      <span className="lds-side-icon"><Icon name={it.icon} size={15} /></span>
                      <span>{it.label}</span>
                    </a>
                  ))}
                </div>
              ))}
              <div style={{ padding: "12px 10px", fontSize: 11, color: "var(--color-text-tertiary)", fontFamily: "var(--font-mono)", letterSpacing: "0.04em" }}>
                v1.0.0 · {pageLabel || ""}
              </div>
            </aside>
          )}
          <main className="lds-main" id="lds-main">
            {/* Content injected by page */}
          </main>
        </div>
        <CommandK open={cmdOpen} onClose={() => setCmdOpen(false)} />
      </Fragment>
    );
  }

  // Copy-to-clipboard helper
  function attachCopyHandlers(root = document) {
    root.addEventListener("click", (e) => {
      const btn = e.target.closest(".copy, [data-copy]");
      if (!btn) return;
      const text = btn.dataset.copy || btn.closest(".lds-code")?.querySelector("pre")?.innerText || "";
      if (!text) return;
      navigator.clipboard.writeText(text).then(() => {
        const original = btn.textContent;
        btn.classList.add("ok");
        btn.textContent = "Copied";
        setTimeout(() => { btn.classList.remove("ok"); btn.textContent = original; }, 1400);
        showToast("Copied to clipboard");
      });
    });
  }

  function showToast(msg, ms = 1800) {
    const t = document.createElement("div");
    t.className = "lds-toast";
    t.textContent = msg;
    document.body.appendChild(t);
    setTimeout(() => t.remove(), ms);
  }

  function mount(opts = {}) {
    // Render chrome into #lds-chrome, content stays in body
    const chromeHost = document.getElementById("lds-chrome") || (() => {
      const d = document.createElement("div");
      d.id = "lds-chrome";
      document.body.prepend(d);
      return d;
    })();
    const root = ReactDOM.createRoot(chromeHost);
    root.render(<Chrome {...opts} />);
    // Wait for Chrome to actually render <main id="lds-main"> into the DOM,
    // then move pre-declared content into it. React 18 createRoot.render() is
    // async-committed, so we poll briefly instead of firing one-shot rAF.
    const tryMove = (attempts = 0) => {
      const content = document.getElementById("lds-content");
      const main = document.getElementById("lds-main");
      if (content && main) {
        while (content.firstChild) main.appendChild(content.firstChild);
        content.remove();
        attachCopyHandlers(document);
        return;
      }
      if (attempts > 30) { attachCopyHandlers(document); return; }
      requestAnimationFrame(() => tryMove(attempts + 1));
    };
    tryMove();
  }

  return { mount, showToast, attachCopyHandlers };
})();

window.LuminoChrome = LuminoChrome;
