// shell.jsx — shared chrome for all pages: bg, nav, status footer.
// Pages render their content inside <Shell tab onTabChange>.

// THEMES — togglable via window.__themeName + window.__setTheme()
const THEMES = {
  blood: {
    void: "#000",
    raven: "#0a0a0a",
    concrete: "#1a1817",
    concreteHi: "#2a2724",
    bone: "#e8e4dc",
    blood: "#8b0000",
    bloodHot: "#c41e1e",
    ash: "#7a766f",
    ashDim: "#4a4640",
    display: "'Archivo Black', 'Anton', sans-serif",
    cond: "'Bebas Neue', 'Oswald', sans-serif",
    meta: "'JetBrains Mono', monospace",
  },
  cobalt: {
    void: "#000",
    raven: "#02030a",
    concrete: "#04081a",
    concreteHi: "#081340",
    bone: "#e6ecf5",
    blood: "#000d52",
    bloodHot: "#1830ff",
    ash: "#5566aa",
    ashDim: "#2a3560",
    display: "'JetBrains Mono', 'IBM Plex Mono', monospace",
    cond: "'JetBrains Mono', 'IBM Plex Mono', monospace",
    meta: "'JetBrains Mono', 'IBM Plex Mono', monospace",
  },
};

let _themeName = "blood";
function applyTheme(name) {
  _themeName = name in THEMES ? name : "blood";
  window.shellStyles = THEMES[_themeName];
  window.__themeName = _themeName;
  window.dispatchEvent(new CustomEvent("dvtheme"));
}
applyTheme("cobalt");
window.__setTheme = applyTheme;

const TABS = ["home", "about", "mythology", "transmissions", "playlists", "inbox", "creator"];

function Shell({ tab, onTabChange, children, page = "001", broadcast = "BROADCASTING · 24.6kHz" }) {
  const S = window.shellStyles;
  const { isMobile, isCompact } = (window.useViewport ? window.useViewport() : { isMobile: false, isCompact: false });
  // The hamburger menu replaces the desktop tab-strip whenever the viewport is too
  // narrow to fit all 7 tabs cleanly (i.e. anything below the desktop tier).
  const useHamburger = isMobile || isCompact;
  const [menuOpen, setMenuOpen] = React.useState(false);

  // Lock body scroll when overlay is open on mobile
  React.useEffect(() => {
    if (!isMobile) return;
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen, isMobile]);

  const handleTab = (t) => { setMenuOpen(false); onTabChange && onTabChange(t); };

  // Fullscreen menu overlay — used by both mobile and compact-desktop nav.
  // Rendered as a sibling at the top of each branch's JSX; uses position:fixed
  // so it floats over whatever shell layout is underneath.
  const menuOverlay = menuOpen && (
    <div style={{
      position: "fixed", inset: 0, background: S.void, zIndex: 100,
      display: "flex", flexDirection: "column",
      paddingTop: "env(safe-area-inset-top, 0px)",
      paddingBottom: "env(safe-area-inset-bottom, 0px)",
    }}>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        padding: "16px",
        borderBottom: `1px solid ${S.concreteHi}`,
      }}>
        <span style={{ fontFamily: S.display, fontSize: 22, letterSpacing: "0.18em", color: S.bone }}>D//V</span>
        <button
          aria-label="close menu"
          onClick={() => setMenuOpen(false)}
          style={{
            background: "transparent", border: `1px solid ${S.concreteHi}`,
            color: S.bone, padding: "10px 14px", cursor: "pointer",
            fontFamily: S.meta, fontSize: 11, letterSpacing: "0.25em",
            minHeight: 44, minWidth: 44,
          }}>
          CLOSE ✕
        </button>
      </div>
      <div style={{
        flex: 1, display: "flex", flexDirection: "column",
        padding: "32px 16px", gap: 4, overflowY: "auto",
      }}>
        {TABS.map((t) => (
          <a key={t} onClick={() => handleTab(t)} style={{
            fontFamily: S.display, fontSize: 28, letterSpacing: "0.04em",
            color: tab === t ? S.bloodHot : S.bone, cursor: "pointer",
            padding: "16px 8px", textTransform: "uppercase",
            borderBottom: `1px solid ${S.concreteHi}`,
            minHeight: 56,
          }}>
            {t}
            {tab === t && <span style={{ marginLeft: 12, fontSize: 14, color: S.bloodHot }}>◢</span>}
          </a>
        ))}
        <div style={{ marginTop: "auto", padding: "24px 8px", fontSize: 11, color: S.ashDim, letterSpacing: "0.25em", lineHeight: 1.7 }}>
          <a href="https://aiofeffect.com" target="_blank" rel="noreferrer" style={{ color: S.ash, textDecoration: "none" }}>© AIOFEFFECT LLC ↗</a>
          <div style={{ fontSize: 10, color: S.ashDim, marginTop: 4 }}>2026 · ALL RIGHTS RESERVED</div>
        </div>
      </div>
    </div>
  );

  // ───────── MOBILE LAYOUT ─────────
  // Natural body scroll. Fixed nav at top. Footer flows after content.
  // No nested scroll containers — iOS Safari handles toolbar show/hide cleanly.
  if (isMobile) {
    return (
      <div style={{
        background: S.void, color: S.bone, fontFamily: S.meta,
        minHeight: "100dvh",
        position: "relative",
        // Flex column so the content area stretches to push the footer to the
        // bottom of the viewport even when the page is shorter than 100dvh.
        // Without this, short pages leave empty space below the footer.
        display: "flex", flexDirection: "column",
      }}>
        <NoiseFilter id="ind-noise" baseFreq="1.2" opacity="0.55" />
        {/* SiteOverlay — atmospheric water + optional uploaded image. Config is
            cached so re-mount on tab switch is free. */}
        {window.SiteOverlay && <window.SiteOverlay />}

        {/* fixed nav at top */}
        <nav style={{
          position: "fixed", top: 0, left: 0, right: 0,
          padding: "calc(env(safe-area-inset-top, 0px) + 12px) 16px 12px",
          background: "rgba(2,3,10,0.92)",
          backdropFilter: "blur(10px)",
          WebkitBackdropFilter: "blur(10px)",
          borderBottom: `1px solid ${S.concreteHi}`,
          display: "flex", justifyContent: "space-between", alignItems: "center",
          zIndex: 50,
        }}>
          <div style={{ display: "flex", alignItems: "baseline", gap: 8, cursor: "pointer" }}
               onClick={() => handleTab("home")}>
            <span style={{ fontFamily: S.display, fontSize: 22, letterSpacing: "0.18em", color: S.bone }}>D//V</span>
            <span style={{ fontFamily: S.meta, fontSize: 10, color: S.ash, letterSpacing: "0.3em" }}>DIAVAL.AI</span>
          </div>
          <button
            aria-label={menuOpen ? "close menu" : "open menu"}
            onClick={() => setMenuOpen(o => !o)}
            style={{
              background: "transparent", border: `1px solid ${S.concreteHi}`,
              color: S.bone, padding: "10px 14px", cursor: "pointer",
              fontFamily: S.meta, fontSize: 11, letterSpacing: "0.25em",
              minHeight: 44, minWidth: 44,
            }}>
            {menuOpen ? "CLOSE ✕" : "MENU"}
          </button>
        </nav>

        {/* fullscreen menu overlay (lifted to top of Shell so compact-desktop reuses it) */}
        {menuOverlay}

        {/* content in normal flow — top padding clears the fixed nav. flex:1 so
            the content area expands to push the footer to the bottom of the viewport. */}
        <div style={{ paddingTop: "calc(env(safe-area-inset-top, 0px) + 68px)", flex: "1 0 auto" }}>
          {children}
        </div>

        {/* footer in normal flow at the end of content */}
        <div style={{
          marginTop: 32,
          padding: "20px 16px",
          paddingBottom: "calc(20px + env(safe-area-inset-bottom, 0px))",
          fontSize: 10, color: S.ash, letterSpacing: "0.3em",
          display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8,
          borderTop: `1px solid ${S.concreteHi}`,
        }}>
          <span style={{ color: S.ashDim }}>// {page}</span>
          <a href="https://aiofeffect.com" target="_blank" rel="noreferrer" style={{ color: S.ash, textDecoration: "none", letterSpacing: "0.3em", whiteSpace: "nowrap" }}>© AIOFEFFECT 2026 ↗</a>
        </div>
        {window.BackToTop && <window.BackToTop S={S} />}
      </div>
    );
  }

  // ───────── DESKTOP LAYOUT (unchanged) ─────────
  return (
    <div style={{
      width: "100%", height: "100%", minHeight: 600,
      background: S.void, color: S.bone,
      fontFamily: S.meta, position: "relative", overflow: "hidden",
    }}>
      <NoiseFilter id="ind-noise" baseFreq="1.2" opacity="0.55" />

      <div style={{ position: "absolute", inset: 0 }}>
        <div style={{
          position: "absolute", inset: 0,
          background: `
            radial-gradient(ellipse at 30% 20%, #1a1817 0%, transparent 50%),
            radial-gradient(ellipse at 80% 80%, #14110f 0%, transparent 60%),
            #0a0a0a
          `,
        }} />
        <div style={{ position: "absolute", inset: 0, filter: "url(#ind-noise)", opacity: 0.55, mixBlendMode: "overlay" }} />
      </div>

      {/* SiteOverlay paints AFTER the radial-gradient backdrop above, so its
          fixed-position layers sit between the dark bg and the page content.
          Re-mounts on tab switch but config is cached → no flicker. */}
      {window.SiteOverlay && <window.SiteOverlay />}

      {/* Compact-desktop branch (768–1279px): hamburger menu instead of the 7-tab strip,
          which doesn't fit cleanly at small-laptop widths. Tabs render in the same
          fullscreen overlay used by the mobile shell. */}
      {isCompact ? (
        <nav style={{
          position: "absolute", top: 40, left: 24, right: 24,
          display: "flex", justifyContent: "space-between", alignItems: "center",
          zIndex: 50,
        }}>
          <div style={{ display: "flex", alignItems: "baseline", gap: 14, cursor: "pointer" }}
               onClick={() => handleTab("home")}>
            <span style={{ fontFamily: S.display, fontSize: 28, letterSpacing: "0.18em", color: S.bone }}>D//V</span>
            <span style={{ fontFamily: S.meta, fontSize: 12, color: S.ash, letterSpacing: "0.3em" }}>DIAVAL.AI</span>
          </div>
          <button
            aria-label={menuOpen ? "close menu" : "open menu"}
            onClick={() => setMenuOpen(o => !o)}
            style={{
              background: "transparent", border: `1px solid ${S.concreteHi}`,
              color: S.bone, padding: "10px 16px", cursor: "pointer",
              fontFamily: S.meta, fontSize: 12, letterSpacing: "0.3em",
            }}>
            {menuOpen ? "CLOSE ✕" : "MENU"}
          </button>
        </nav>
      ) : (
        <nav style={{
          position: "absolute", top: 40, left: 56, right: 56,
          display: "flex", justifyContent: "space-between", alignItems: "center",
          zIndex: 50,
        }}>
          <div style={{ display: "flex", alignItems: "baseline", gap: 14, cursor: "pointer" }}
               onClick={() => handleTab("home")}>
            <span style={{ fontFamily: S.display, fontSize: 28, letterSpacing: "0.18em", color: S.bone }}>D//V</span>
            <span style={{ fontFamily: S.meta, fontSize: 12, color: S.ash, letterSpacing: "0.3em" }}>DIAVAL.AI</span>
          </div>
          <div style={{ display: "flex", gap: 32, fontFamily: S.meta, fontSize: 13, letterSpacing: "0.28em" }}>
            {TABS.map((t) => (
              <a key={t} onClick={() => handleTab(t)} style={{
                color: tab === t ? S.bone : S.ash, cursor: "pointer", textTransform: "uppercase",
                borderBottom: tab === t ? `1px solid ${S.bloodHot}` : "1px solid transparent",
                paddingBottom: 4, transition: "color .2s",
              }}>{t}</a>
            ))}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, fontFamily: S.meta, fontSize: 12, color: S.ash, letterSpacing: "0.25em" }}>
            <span style={{ width: 7, height: 7, background: S.bloodHot, borderRadius: "50%" }} />
            {broadcast}
          </div>
        </nav>
      )}

      {/* Same fullscreen overlay used by the mobile shell, so compact-desktop reuses it */}
      {menuOverlay}

      <div style={{ position: "absolute", top: 104, left: 0, right: 0, bottom: 36, zIndex: 5 }}>
        {children}
      </div>

      <div style={{
        position: "absolute", bottom: 14, left: 56, right: 56,
        fontSize: 12, color: S.ash, letterSpacing: "0.3em",
        display: "flex", justifyContent: "space-between", zIndex: 10,
      }}>
        <span>DIAVAL.AI // {page} ⸺ COME APART. WE'RE ALL BETTER IN PIECES.</span>
        <a href="https://aiofeffect.com" target="_blank" rel="noreferrer" style={{ color: S.ash, textDecoration: "none", letterSpacing: "0.3em" }}>© AIOFEFFECT 2026 · ALL RIGHTS RESERVED ↗</a>
      </div>
    </div>
  );
}

window.Shell = Shell;
window.TABS = TABS;
window.THEMES = THEMES;
