/* =========================================================================
   DR. BANANA CLUB — MEMBERSHIP APP · SHELL
   Navigation state + theatre toggle. Mounts screens inside the iOS frame.
   ========================================================================= */

const SCREENS = {
  home: HomeScreen,
  events: EventsScreen,
  node: NodeScreen,
  vault: VaultScreen,
  perks: PerksScreen,
  unlocks: UnlocksScreen,
};

/* ----- bottom nav, non-absolute variant used at the device root ----- */
const InlineBottomNav = ({ active, onNav, dark }) => {
  const items = [
    { id: 'home', label: 'HOME' },
    { id: 'events', label: 'EVENTS' },
    { id: 'node', label: 'NODE' },
    { id: 'vault', label: 'VAULT' },
    { id: 'perks', label: 'PERKS' },
  ];
  return (
    <nav
      style={{
        display: 'flex',
        justifyContent: 'space-between',
        padding: '12px 20px 14px',
        borderTop: `1px solid ${dark ? 'var(--db-d-hairline)' : 'var(--db-hairline)'}`,
        background: dark ? 'var(--db-d-bg)' : 'var(--db-paper)',
      }}
    >
      {items.map((i) => {
        const on = active === i.id;
        const inkOn = dark ? 'var(--db-d-ink)' : 'var(--db-ink)';
        const inkOff = dark ? 'var(--db-d-silver)' : 'var(--db-silver)';
        return (
          <button
            key={i.id}
            onClick={() => onNav && onNav(i.id)}
            style={{
              background: 'transparent',
              border: 0,
              padding: '4px 2px 3px',
              cursor: 'pointer',
              fontFamily: 'var(--font-mono)',
              fontSize: 10,
              letterSpacing: '0.1em',
              textTransform: 'uppercase',
              color: on ? inkOn : inkOff,
              borderBottom: on ? `2px solid ${inkOn}` : '2px solid transparent',
            }}
          >
            {i.label}
          </button>
        );
      })}
    </nav>
  );
};

/* ----- Bottom-nav slot with 200ms fade transition -----
   States: 'mounted' (visible), 'leaving' (opacity 0, transitioning out),
   'gone' (unmounted). Transitions: mounted → leaving on detail open,
   leaving → gone after 200ms; gone → mounted on detail close.
*/
const NAV_FADE_MS = 200;

const BottomNavSlot = ({ visible, active, onNav, dark }) => {
  const [phase, setPhase] = React.useState(visible ? 'mounted' : 'gone');
  React.useEffect(() => {
    if (visible) {
      // becoming visible: mount immediately; opacity animates via inline style swap
      setPhase('mounted');
      return;
    }
    // becoming hidden: drop to leaving (opacity 0), then unmount after 200ms
    setPhase('leaving');
    const id = setTimeout(() => setPhase('gone'), NAV_FADE_MS);
    return () => clearTimeout(id);
  }, [visible]);

  if (phase === 'gone') return null;
  return (
    <div
      aria-hidden={phase !== 'mounted'}
      style={{
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 34,
        zIndex: 70,
        opacity: phase === 'mounted' ? 1 : 0,
        transition: `opacity ${NAV_FADE_MS}ms ease`,
        pointerEvents: phase === 'mounted' ? 'auto' : 'none',
      }}
    >
      <InlineBottomNav active={active} onNav={onNav} dark={dark} />
    </div>
  );
};

const MembershipApp = ({ initialScreen = 'home', initialDark = true }) => {
  const [screen, setScreen] = React.useState(initialScreen);
  const [dark, setDark] = React.useState(initialDark);
  const [detail, setDetail] = React.useState(null);
  const Screen = SCREENS[screen] || HomeScreen;

  return (
    <div
      style={{
        minHeight: '100vh',
        background: dark ? '#181612' : '#E2DECF',
        padding: '48px 24px 80px',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: 28,
        fontFamily: 'var(--font-sans)',
        color: dark ? 'var(--db-d-ink)' : 'var(--db-ink)',
        transition: 'background 300ms ease',
      }}
    >
      <AppHeader dark={dark} screen={screen} onScreen={setScreen} onTheatre={() => setDark(!dark)} />

      <IOSDevice dark={dark} width={402} height={874}>
        <div
          style={{
            position: 'relative',
            width: '100%',
            height: '100%',
            background: dark ? 'var(--db-d-bg)' : 'var(--db-paper)',
            display: 'flex',
            flexDirection: 'column',
          }}
        >
          <NoiseOverlay />
          <div
            className="ios-screen-scroll"
            style={{
              position: 'relative',
              zIndex: 2,
              flex: 1,
              overflow: 'auto',
              paddingTop: 44 /* clear status bar */,
              paddingBottom: detail ? 24 : 90 /* no bottom nav in detail */,
            }}
          >
            {detail ? (
              <DetailRouter detail={detail} dark={dark} onBack={() => setDetail(null)} />
            ) : (
              <Screen dark={dark} onNav={setScreen} onDetail={setDetail} />
            )}
          </div>
          <BottomNavSlot visible={!detail} active={screen} onNav={setScreen} dark={dark} />
        </div>
      </IOSDevice>

      <Footer dark={dark} />
    </div>
  );
};

/* ----- header ----- */
const AppHeader = ({ dark, screen, onScreen, onTheatre }) => {
  const ink = dark ? 'var(--db-d-ink)' : 'var(--db-ink)';
  const hair = dark ? 'var(--db-d-hairline)' : 'var(--db-hairline)';
  const graphite = dark ? 'var(--db-d-graphite)' : 'var(--db-graphite)';
  const surface = dark ? 'var(--db-d-surface)' : 'var(--db-cream)';

  const screens = [
    ['home', 'HOME'],
    ['events', 'EVENTS'],
    ['node', 'NODE'],
    ['vault', 'VAULT'],
    ['perks', 'PERKS'],
    ['unlocks', 'UNLOCKS'],
  ];

  return (
    <header
      style={{
        width: '100%',
        maxWidth: 760,
        display: 'flex',
        flexDirection: 'column',
        gap: 14,
        paddingBottom: 18,
        borderBottom: `1px solid ${hair}`,
      }}
    >
      <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: graphite }}>
          UI KIT · MEMBERSHIP APP
        </span>
        <span style={{ color: graphite }}>●</span>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: graphite }}>
          FILE 029
        </span>
        <span style={{ flex: 1 }} />
        <button
          onClick={onTheatre}
          style={{
            padding: '6px 10px',
            background: 'transparent',
            border: `1px solid ${ink}`,
            color: ink,
            borderRadius: 2,
            cursor: 'pointer',
            fontFamily: 'var(--font-mono)',
            fontSize: 10,
            letterSpacing: '0.1em',
            textTransform: 'uppercase',
          }}
        >
          Theatre: {dark ? 'NIGHT' : 'DAY'} — override
        </button>
      </div>

      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 18, flexWrap: 'wrap' }}>
        <img
          src="../../assets/logo-color.png"
          alt="Dr. Banana Club"
          style={{
            height: 96,
            width: 'auto',
            mixBlendMode: dark ? 'screen' : 'multiply',
            filter: dark ? 'invert(1) hue-rotate(180deg)' : 'none',
            flexShrink: 0,
          }}
        />
        <h1
          style={{
            margin: '0 0 2px',
            fontFamily: 'var(--font-serif-italic)',
            fontStyle: 'italic',
            fontWeight: 400,
            fontSize: 32,
            lineHeight: 1.05,
            letterSpacing: '-0.01em',
            color: ink,
            flex: 1,
            minWidth: 200,
          }}
        >
          — residency app.
        </h1>
      </div>

      <p
        style={{
          margin: 0,
          maxWidth: 620,
          fontSize: 15,
          lineHeight: 1.5,
          color: graphite,
        }}
      >
        Six surfaces, two theatres. <em style={{ fontFamily: 'var(--font-serif-italic)', color: ink }}>One vocabulary.</em>{' '}
        The app boots dark after 20:00 or in low-light ambient — the member can override, the club cannot.
      </p>

      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {screens.map(([id, label]) => {
          const on = screen === id;
          return (
            <button
              key={id}
              onClick={() => onScreen(id)}
              style={{
                padding: '6px 10px',
                background: on ? ink : surface,
                color: on ? (dark ? 'var(--db-d-bg)' : 'var(--db-paper)') : ink,
                border: `1px solid ${on ? ink : hair}`,
                borderRadius: 2,
                cursor: 'pointer',
                fontFamily: 'var(--font-mono)',
                fontSize: 10,
                letterSpacing: '0.1em',
                textTransform: 'uppercase',
              }}
            >
              {label}
            </button>
          );
        })}
      </div>
    </header>
  );
};

const Footer = ({ dark }) => {
  const graphite = dark ? 'var(--db-d-graphite)' : 'var(--db-graphite)';
  return (
    <footer
      style={{
        maxWidth: 760,
        width: '100%',
        fontFamily: 'var(--font-mono)',
        fontSize: 10,
        letterSpacing: '0.08em',
        textTransform: 'uppercase',
        color: graphite,
        display: 'flex',
        gap: 10,
        flexWrap: 'wrap',
        alignItems: 'center',
      }}
    >
      <img
        src="../../assets/banana-mark.png"
        alt="Dr. Banana Club"
        style={{
          height: 22,
          width: 'auto',
          mixBlendMode: dark ? 'screen' : 'multiply',
          opacity: dark ? 0.92 : 1,
          marginRight: 4,
        }}
      />
      <span>DR.BANANA / 28.ROOM</span>
      <span>●</span>
      <span>SÃO PAULO</span>
      <span>●</span>
      <span>FILE 029 · UI KIT</span>
      <span style={{ flex: 1 }} />
      <img
        src="../../assets/wordmark.png"
        alt=""
        aria-hidden="true"
        style={{
          height: 14,
          width: 'auto',
          mixBlendMode: dark ? 'screen' : 'multiply',
          opacity: 0.55,
        }}
      />
      <span>
        <em style={{ fontFamily: 'var(--font-serif-italic)', textTransform: 'none', letterSpacing: 0 }}>
          For dilated pupils and real walls.
        </em>
      </span>
    </footer>
  );
};

Object.assign(window, { MembershipApp });

/* -----  Auto-mount  -----
   Done here (not in index.html) so the mount runs in the same Babel pass
   that defines MembershipApp — avoiding race conditions where an inline
   text/babel block executes before sibling text/babel src files resolve.
*/
(function mountWhenReady() {
  if (!window.IOSDevice || !window.HomeScreen || !window.DetailRouter) {
    return setTimeout(mountWhenReady, 30);
  }
  const host = document.getElementById('root');
  if (!host || host.__mounted) return;
  host.__mounted = true;
  const root = ReactDOM.createRoot(host);
  root.render(<MembershipApp initialScreen="home" initialDark={true} />);
})();
