// Outer app shell — three-tab nav at top, content below. This is the single
// source of truth for the top-right tab row: Home / The Write Stuff / TWS + EPL.
//
// UX note: on the Write Stuff and TWS+EPL tabs, the inner PortalShell has its
// own sticky header. Two stacked banners reads as clutter. So once the user
// scrolls past the master nav, we slide it up out of view; returning to the
// top reveals it again. Home keeps it pinned (no inner header competing).

const { useState: useStateApp, useEffect: useEffectApp, useRef: useRefApp } = React;

function AppShell() {
  // Start collapsed on inner tabs (TWS / EPL). Two stacked banners at the top
  // reads too chunky; the master nav re-appears on scroll-to-top or via the handle.
  const initialTab = localStorage.getItem('app_tab') || 'home';
  const [tab, setTab] = useStateApp(initialTab);
  const [collapsed, setCollapsed] = useStateApp(initialTab !== 'home');
  useEffectApp(() => { localStorage.setItem('app_tab', tab); }, [tab]);

  // On tab switch, collapse on inner tabs, keep master pinned on Home. Scroll to top too.
  useEffectApp(() => {
    setCollapsed(tab !== 'home');
    window.scrollTo({ top: 0, behavior: 'auto' });
  }, [tab]);

  // On inner tabs, scroll listener can still expand when user scrolls back to very top.
  useEffectApp(() => {
    if (tab === 'home') return; // home has no inner header; keep master pinned
    const onScroll = () => {
      // Only auto-collapse once the user has scrolled past the threshold.
      // Don't auto-expand here — the handle click is the explicit way back.
      if (window.scrollY > 40) setCollapsed(true);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [tab]);

  const TABS = [
    { key: 'home', label: 'Home' },
    { key: 'tws', label: 'The Write Stuff' },
    { key: 'epl', label: 'TWS + EPL' },
  ];

  // The outer shell wears the theme of whichever tab is active, so the top bar colour reads right.
  const tabTheme = tab === 'epl' ? ELYSIUM_THEME : UNORDINARY_THEME;

  // Master nav is ~62px tall incl. gradient bar. Translate the whole block up
  // when collapsed. On home tab, never collapse.
  const shouldCollapse = collapsed && tab !== 'home';

  return (
    <BrandTheme.Provider value={tabTheme}>
      <div style={{ minHeight: '100vh', background: '#fff', color: tabTheme.ink, fontFamily: 'Inter, Arial' }}>
        {/* Top master nav */}
        <div style={{
          borderBottom: `1px solid ${tabTheme.rule}`, background: '#fff',
          position: 'sticky', top: 0, zIndex: 30,
          transform: shouldCollapse ? 'translateY(-100%)' : 'translateY(0)',
          transition: 'transform .28s cubic-bezier(.4,0,.2,1)',
          willChange: 'transform',
        }}>
          <div style={{ maxWidth: 1280, margin: '0 auto', padding: '14px 32px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24 }}>
            {/* Brand lockup (always Unordinary at the master level) */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <img src="assets/logos/unordinary-pinwheel.png" alt="" style={{ height: 26 }} />
              <span style={{ font: "700 18px/1 'Space Grotesk', Arial", color: '#1A1A1A', letterSpacing: '-.01em' }}>The Unordinary</span>
            </div>

            {/* Top-right tabs */}
            <nav style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
              {TABS.map(tb => {
                const active = tab === tb.key;
                return (
                  <button key={tb.key} onClick={() => setTab(tb.key)} style={{
                    font: "600 13px/1 'Space Grotesk', Arial",
                    padding: '10px 16px', borderRadius: 6,
                    border: 'none', cursor: 'pointer',
                    background: active ? tabTheme.ink : 'transparent',
                    color: active ? '#fff' : '#555',
                    transition: 'background .18s, color .18s',
                  }}>{tb.label}</button>
                );
              })}
              <div style={{ width: 1, height: 20, background: '#E8E8E8', margin: '0 10px' }} />
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ font: "400 13px/1 Inter, Arial", color: '#555' }}>Brett Ackroyd</span>
                <div style={{
                  width: 28, height: 28, borderRadius: 999,
                  background: tabTheme.primaryMid, color: tabTheme.primaryDark,
                  font: "700 12px/1 'Space Grotesk', Arial",
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>BA</div>
              </div>
            </nav>
          </div>
          <GradientBar height={2} />
        </div>

        {/* Slim "return to master nav" handle — appears when collapsed so the
            user can still switch tabs without scrolling to the top. Clicking
            it expands the nav directly; no scroll dependency. */}
        {shouldCollapse && (
          <button
            onClick={() => { setCollapsed(false); window.scrollTo({ top: 0, behavior: 'smooth' }); }}
            title="Back to top nav"
            style={{
              position: 'fixed', top: 0, left: '50%', transform: 'translateX(-50%)',
              width: 120, height: 22,
              borderBottomLeftRadius: 12, borderBottomRightRadius: 12,
              borderTopLeftRadius: 0, borderTopRightRadius: 0,
              border: `1px solid ${tabTheme.rule}`, borderTop: 'none',
              background: '#fff',
              boxShadow: '0 6px 16px rgba(26,26,26,0.10)',
              cursor: 'pointer', zIndex: 40,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              font: "600 11px/1 'Space Grotesk', Arial", color: tabTheme.muted,
              letterSpacing: '.04em', textTransform: 'uppercase',
            }}
            aria-label="Show top navigation"
          >
            <span>Menu</span>
            <svg width="10" height="7" viewBox="0 0 14 8" fill="none">
              <path d="M1 2 L7 6 L13 2" stroke={tabTheme.muted} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        )}

        {/* Tab content */}
        {tab === 'home' && <Home goTab={setTab} />}
        {tab === 'tws' && (
          <BrandTheme.Provider value={UNORDINARY_THEME}>
            <WriteStuffTab />
          </BrandTheme.Provider>
        )}
        {tab === 'epl' && (
          <BrandTheme.Provider value={ELYSIUM_THEME}>
            <EPLTab />
          </BrandTheme.Provider>
        )}
      </div>
    </BrandTheme.Provider>
  );
}

window.AppShell = AppShell;
