// AcademiaDental — Main app router
const { useState: useStateApp, useEffect: useEffectApp, useRef: useRefApp } = React;

function App() {
  const [session, setSession] = useStateApp(() => window.AD_STATE.currentSession());
  const [route, setRoute] = useStateApp('home');
  const [topicFlow, setTopicFlow] = useStateApp(null);
  const [tutorContext, setTutorContext] = useStateApp(null);
  const [progressTick, setProgressTick] = useStateApp(0);

  // Detectar URL params al cargar: pago exitoso → llevar al módulo
  useEffectApp(() => {
    const params = new URLSearchParams(location.search);
    const welcomeModule = params.get('module');
    if ((params.get('welcome') === '1' || params.get('payment') === 'ok') && welcomeModule && session) {
      // El user ya está logueado (via magic link); ir al módulo comprado
      setRoute('modules:' + welcomeModule);
      window.AD_TOAST && window.AD_TOAST.show('¡Bienvenida! Tu acceso está activo ✓', 3500);
      history.replaceState(null, '', location.pathname);
    }
  }, [session]);

  // Init security layer (always on; updates ident when user logs in)
  useEffectApp(() => {
    if (window.AD_CONFIG && window.AD_CONFIG.security && window.AD_SECURITY) {
      window.AD_SECURITY.init(session ? session.email : 'invitado');
    }
  }, []);
  useEffectApp(() => {
    if (window.AD_SECURITY && session) window.AD_SECURITY.setUser(session.email);
  }, [session && session.email]);

  // PWA install prompt
  const [installEvt, setInstallEvt] = useStateApp(null);
  const [showInstall, setShowInstall] = useStateApp(false);
  useEffectApp(() => {
    const handler = (e) => { e.preventDefault(); setInstallEvt(e); };
    window.addEventListener('beforeinstallprompt', handler);
    window.addEventListener('appinstalled', () => {
      window.AD_TOAST.show('¡App instalada! ✓');
      setInstallEvt(null);
      setShowInstall(false);
    });
    return () => window.removeEventListener('beforeinstallprompt', handler);
  }, []);

  function doInstall() {
    if (!installEvt) {
      // No native prompt available → show instructions modal
      setShowInstall(true);
      return;
    }
    installEvt.prompt();
    installEvt.userChoice.then(() => setInstallEvt(null));
  }
  function openInstall() { setShowInstall(true); }

  // Boot scheduler for active user
  useEffectApp(() => {
    if (session) {
      const r = window.AD_STATE.getReminders(session.email);
      if (r.enabled) window.AD_NOTIF.startScheduler(session.email);
      // Touch streak on app open
      window.AD_STATE.touchStreak(session.email);
    }
    return () => window.AD_NOTIF.stopScheduler();
  }, [session && session.email]);

  // Cross-tab session validation (single active session)
  useEffectApp(() => {
    if (!session) return;
    const onStorage = (e) => {
      if (e.key === 'ad.activeSession') {
        const v = e.newValue ? JSON.parse(e.newValue) : null;
        if (!v || v.email !== session.email || v.deviceId !== session.deviceId) {
          window.AD_TOAST.show('Sesión cerrada — otro dispositivo tomó control', 4000);
          window.AD_STATE.logout();
          setSession(null);
        }
      }
    };
    window.addEventListener('storage', onStorage);
    return () => window.removeEventListener('storage', onStorage);
  }, [session]);

  // Validate active session periodically
  useEffectApp(() => {
    if (!session) return;
    const i = setInterval(() => {
      const active = JSON.parse(localStorage.getItem('ad.activeSession') || 'null');
      if (!active || active.email !== session.email || active.deviceId !== session.deviceId) {
        window.AD_TOAST.show('Sesión cerrada — otro dispositivo tomó control', 4000);
        window.AD_STATE.logout();
        setSession(null);
      }
    }, 5000);
    return () => clearInterval(i);
  }, [session]);

  if (!session) {
    return <AuthScreen onAuthed={(s) => { setSession(s); setRoute('home'); }}/>;
  }

  function openTopic(mod, topic) {
    setTopicFlow({ module: mod, topic, stage: 'theory' });
  }
  function openTutorWithContext(ctx) {
    setTutorContext(ctx); setTopicFlow(null); setRoute('tutor');
  }

  // Route handling
  let body;
  if (route === 'home') {
    body = <HomeScreen
      session={session}
      setRoute={setRoute}
      openTopic={openTopic}
      canInstall={!window.AD_INSTALL.detect().isStandalone}
      onInstall={openInstall}/>;
  } else if (route.startsWith('modules')) {
    body = <ModulesScreen
      session={session}
      route={route}
      setRoute={setRoute}
      openTopic={openTopic}/>;
  } else if (route === 'tutor') {
    body = <TutorScreen session={session} setRoute={setRoute} tutorContext={tutorContext}/>;
  } else if (route === 'referrals') {
    body = <ReferralsScreen session={session} setRoute={setRoute}/>;
  } else if (route === 'minsal') {
    body = <MinsalScreen session={session} setRoute={setRoute}/>;
  } else if (route === 'security') {
    setRoute('account'); // alias
    body = null;
  } else if (route === 'account') {
    body = <AccountScreen
      session={session}
      setRoute={setRoute}
      canInstall={!window.AD_INSTALL.detect().isStandalone}
      onInstall={openInstall}
      onLogout={() => { window.AD_STATE.logout(); setSession(null); }}/>;
  } else {
    body = <HomeScreen session={session} setRoute={setRoute} openTopic={openTopic}/>;
  }

  return (
    <>
      <AppShell session={session} route={route} setRoute={(r) => { setTopicFlow(null); setRoute(r); }}>
        {body}
      </AppShell>
      {topicFlow ? (
        <div style={{position:'fixed',inset:0,background:'var(--bg)',zIndex:50,display:'flex',flexDirection:'column'}}>
          <div className="app-window" style={{width:'100%',height:'100%',maxWidth:'none',maxHeight:'none',borderRadius:0,gridTemplateColumns:'1fr',display:'flex',boxShadow:'none',border:'none'}}>
            <div style={{display:'flex',flexDirection:'column',flex:1,overflow:'hidden',background:'#fff'}}>
              {topicFlow.stage === 'theory' ? (
                <TheoryScreen
                  session={session}
                  module={topicFlow.module}
                  topic={topicFlow.topic}
                  onStartQuiz={() => setTopicFlow({ ...topicFlow, stage: 'quiz' })}
                  onClose={() => setTopicFlow(null)}
                />
              ) : (
                <QuizScreen
                  key={topicFlow.topic.id + ':' + progressTick}
                  session={session}
                  module={topicFlow.module}
                  topic={topicFlow.topic}
                  onClose={() => setTopicFlow(null)}
                  onCompleted={() => setProgressTick(x => x + 1)}
                  setRoute={setRoute}
                  openTutorWithContext={openTutorWithContext}/>
              )}
            </div>
          </div>
        </div>
      ) : null}
      {showInstall ? (
        <InstallModal
          onClose={() => setShowInstall(false)}
          installEvt={installEvt}
          doInstall={doInstall}/>
      ) : null}
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
