;(function () {
/* LeveragedTradeShell — router + chrome for the Leveraged Trade sub-app.
   Owns the active-tab state and renders the four pages (Discover, Trade,
   Portfolio, Activity) as permanently-mounted cross-fading layers, the
   same pattern app.jsx uses for the home tabs. The shell sits inside the
   parent's 390×844 absolute container.

   Transitions are unified across home tabs / subapp tabs / voice overlay
   via window.TRANSITION (utils/transition.js). Sequential out → blank →
   in pattern, 350 / 80 / 750 ms total ~1180ms with smooth easings. */

/* Tab metadata — display name + window-global component reference. The
   page bodies are loaded as separate scripts and registered as window
   globals; if a page hasn't been loaded yet (e.g. during dev), the slot
   renders nothing rather than throwing. */
const TAB_META = {
  discover:  { name: 'Discover',  globalKey: 'DiscoverPage' },
  trade:     { name: 'Trade',     globalKey: 'TradePage' },
  portfolio: { name: 'Portfolio', globalKey: 'PortfolioPage' },
  activity:  { name: 'Activity',  globalKey: 'ActivityPage' },
};
const TAB_KEYS = ['discover', 'trade', 'portfolio', 'activity'];

const OUT_DURATION = window.TRANSITION.OUT_DURATION;
const BLANK_MS = window.TRANSITION.BLANK_MS;
const OUT_TRANSITION = window.TRANSITION.OUT_TRANSITION;
const IN_TRANSITION = window.TRANSITION.IN_TRANSITION;

const LeveragedTradeShell = ({ onBack, onVoice }) => {
  const [activeTradeTab, setActiveTradeTab] = React.useState('discover');
  const tabRef = React.useRef('discover');
  const [opacities, setOpacities] = React.useState({ discover: 1, trade: 0, portfolio: 0, activity: 0 });
  const [transitions, setTransitions] = React.useState({ discover: '', trade: '', portfolio: '', activity: '' });

  /* selectedSym lives at the shell level so other tabs (Discover) can
     change it before navigating. Default 'EURUSD' matches what
     TradePage used to default to internally. */
  const [selectedSym, setSelectedSym] = React.useState('EURUSD');

  const handleTabChange = React.useCallback((next) => {
    if (next === tabRef.current) return;
    const prev = tabRef.current;
    /* Active flips immediately so the BottomNav pill + the title's
       text-swap animation kick off in parallel with the page OUT phase
       (was gated behind the 430ms timeout). The page cross-fade still
       runs OUT → BLANK → IN. */
    tabRef.current = next;
    setActiveTradeTab(next);
    setTransitions((t) => ({ ...t, [prev]: OUT_TRANSITION }));
    setOpacities((o) => ({ ...o, [prev]: 0 }));
    setTimeout(() => {
      setTransitions((t) => ({ ...t, [next]: IN_TRANSITION }));
      setOpacities((o) => ({ ...o, [next]: 1 }));
    }, OUT_DURATION + BLANK_MS);
  }, []);

  /* Expose a window-level goToTrade(symId) so DiscoverPage's row taps
     can flip the tab + symbol in one call without needing to thread
     callbacks through every layer. */
  React.useEffect(() => {
    window.goToTrade = (symId) => {
      if (symId) setSelectedSym(symId);
      handleTabChange('trade');
    };
    /* Voice tool bridges — sit under equiti.* alongside navigateTo. */
    window.equiti = window.equiti || {};
    window.equiti.openTradeSection = (section) => {
      const valid = ['discover', 'trade', 'portfolio', 'activity'];
      if (valid.indexOf(section) < 0) return false;
      handleTabChange(section);
      return true;
    };
    window.equiti.selectSymbol = (symId) => {
      if (!symId) return false;
      setSelectedSym(symId);
      handleTabChange('trade');
      return true;
    };
    window.equiti.getActiveTradeTab = () => tabRef.current;
    return () => {
      delete window.goToTrade;
      if (window.equiti) {
        delete window.equiti.openTradeSection;
        delete window.equiti.selectSymbol;
        delete window.equiti.getActiveTradeTab;
      }
    };
  }, [handleTabChange]);

  /* Resolve the page name for the top bar from the active tab. */
  const pageName = TAB_META[activeTradeTab].name;

  return (
    <div style={{
      position: 'absolute',
      inset: 0,
      display: 'flex',
      flexDirection: 'column',
      backgroundColor: colors.bg,
      overflow: 'hidden',
    }}>
      <TradeTopBar pageName={pageName} onBack={onBack} />

      {/* Page stack — each tab is a permanently-mounted absolute layer.
         flex:1 lets the stack fill the space between top bar and bottom nav. */}
      <div style={{ flex: 1, position: 'relative' }}>
        {TAB_KEYS.map((key) => {
          const PageComp = window[TAB_META[key].globalKey];
          let pageProps = {};
          if (key === 'portfolio') pageProps = { onOpenTrade: () => handleTabChange('trade') };
          else if (key === 'trade') pageProps = { selectedSym, setSelectedSym };
          return (
            <div
              key={key}
              /* See app.jsx: inline pointer-events:none on the wrapper
                 alone leaks because CSS doesn't cascade it to children.
                 The class (defined in Equiti SuperApp.html) walks the
                 subtree so inactive subapp tabs can't steal scroll/clicks
                 from whichever tab is actually active. */
              className={activeTradeTab === key ? '' : 'tab-pane-inactive'}
              style={{
                position: 'absolute',
                inset: 0,
                opacity: opacities[key],
                transition: transitions[key],
              }}
            >
              {PageComp ? <PageComp {...pageProps} /> : null}
            </div>
          );
        })}
      </div>

      <TradeBottomNav
        active={activeTradeTab}
        onChange={handleTabChange}
        onVoice={onVoice}
      />

      {/* Teal blur ambience matching the home screens. TopFade renders
         BEHIND the top bar; BottomFade renders BEHIND the bottom nav.
         Both span the full shell area. */}
      <TopFade/>
      <BottomFade/>
    </div>
  );
};

Object.assign(window, { LeveragedTradeShell });
})();
