/* global React */
const { useState, useEffect } = window.ReactHooks;

function applyTweaks(t) {
  const root = document.documentElement;
  root.setAttribute("data-theme", t.theme);
  root.setAttribute("data-density", t.density);
  root.style.setProperty("--accent", t.accent);
}

function Shell() {
  const route = window.useRoute();
  const [tweaks, setTweaks] = useState(window.__TCVIZ_TWEAKS);
  const [showTweaks, setShowTweaks] = useState(false);

  useEffect(() => { applyTweaks(tweaks); }, [tweaks]);

  // Scroll to top on nav change (except product, which stays in-page)
  useEffect(() => {
    if (typeof window !== "undefined") window.scrollTo(0, 0);
  }, [route.path, route.query]);

  // Edit-mode contract
  useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === "__activate_edit_mode") setShowTweaks(true);
      if (d.type === "__deactivate_edit_mode") setShowTweaks(false);
    };
    window.addEventListener("message", onMsg);
    window.parent && window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

  const setTweak = (k, v) => {
    setTweaks((t) => {
      const next = { ...t, [k]: v };
      window.parent && window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { [k]: v } }, "*");
      return next;
    });
  };

  const hideChrome = route.path === "admin";

  let Page;
  switch (route.path) {
    case "catalog": Page = <window.CatalogPage />; break;
    case "product": Page = <window.ProductPage query={route.query} />; break;
    case "gallery": Page = <window.GalleryPage />; break;
    case "contact": Page = <window.ContactPage />; break;
    case "admin":   Page = <window.AdminPage />;   break;
    case "home":
    default:        Page = <window.HomePage />;
  }

  return (
    <>
      {!hideChrome && <window.Nav route={route} />}
      {hideChrome && (
        <header className="nav">
          <div className="nav-inner">
            <a href="#/home" className="brand">
              <span className="brand-mark">TC</span>
              <span>tcviz · admin</span>
            </a>
            <div className="nav-cta">
              <a href="#/home" className="btn btn-ghost btn-sm">← Back to site</a>
            </div>
          </div>
        </header>
      )}
      {Page}
      {!hideChrome && <window.Footer />}
      {!hideChrome && <window.SupportBot />}
      {showTweaks && <window.TweaksPanel tweaks={tweaks} setTweak={setTweak} />}
    </>
  );
}

window.Shell = Shell;
