// Where the student is in the app, kept per-tab so a reload returns them to the
// same screen (cleared with the session when the tab closes).
const NAV_KEY = 'ayani-nav';
function loadNav() {
  try { return JSON.parse(sessionStorage.getItem(NAV_KEY)) || null; } catch (_) { return null; }
}

function App() {
  const savedNav = React.useMemo(loadNav, []);
  const [screen, setScreen]  = React.useState('loading');
  const [moduleCode, setModule] = React.useState(savedNav?.moduleCode || '301');
  const [lesson, setLesson]  = React.useState(savedNav?.lesson || null);

  React.useEffect(() => {
    if (screen === 'loading') return;
    try {
      if (screen === 'login') sessionStorage.removeItem(NAV_KEY);
      else sessionStorage.setItem(NAV_KEY, JSON.stringify({ screen, moduleCode, lesson }));
    } catch (_) {}
  }, [screen, moduleCode, lesson]);

  // Session restore (1.3): on load, resolve any existing session to a profile and
  // land on the student menu. The admin dashboard is reached only via admin.html
  // (typed URL), never auto-routed here -- admins log in to the lessons like anyone.
  React.useEffect(() => {
    let active = true;

    async function resolve() {
      const { data: { session } } = await window.supabaseClient.auth.getSession();
      if (!session) { if (active) setScreen('login'); return; }

      const profile = await window.ayaniFetchProfile();
      if (!active) return;
      if (!profile || profile.status !== 'active') {
        await window.supabaseClient.auth.signOut();
        setScreen('login');
        return;
      }
      window.ayaniLogActivity();
      // Only auto-route from the loading/login gate; don't yank a user who's already
      // navigated deeper in the app when a token silently refreshes.
      // On a reload, return to the screen they were on (video needs its lesson).
      const restored = savedNav?.screen === 'video' && !savedNav.lesson ? 'channel' : savedNav?.screen;
      setScreen(s => (s === 'loading' || s === 'login') ? (s === 'loading' && restored) || 'menu' : s);
    }

    resolve();

    const { data: sub } = window.supabaseClient.auth.onAuthStateChange((event) => {
      if (event === 'SIGNED_OUT') setScreen('login');
    });

    return () => { active = false; sub.subscription.unsubscribe(); };
  }, []);

  return (
    <div className="ay-app">
      {screen === 'loading' && <div className="ay-screen ay-login" data-screen-label="01 Login" />}
      {screen === 'login'   && <LoginScreen onLogin={() => setScreen('menu')} />}
      {screen === 'menu'    && <MenuScreen onPick={c => { setModule(c); setScreen('channel'); }} />}
      {screen === 'chat'    && <ChatScreen initialChannel={null} onExit={() => setScreen('menu')} />}
      {screen === 'channel' && (
        <ChannelScreen
          moduleCode={moduleCode}
          onPickLesson={l => { setLesson(l); setScreen('video'); }}
          onExit={() => setScreen('menu')}
        />
      )}
      {screen === 'video' && (
        <VideoScreen lesson={lesson} moduleCode={moduleCode} onExit={() => setScreen('channel')} />
      )}
    </div>
  );
}
window.App = App;
