// Caririaçu Guincho — App Root

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

const App = () => {
  const [session, setSession] = useStateApp(null);
  const [authReady, setAuthReady] = useStateApp(false);
  const [page, setPage] = useStateApp('dashboard');
  const [sidebarOpen, setSidebarOpen] = useStateApp(false);
  const [isMobile, setIsMobile] = useStateApp(window.innerWidth < 768);
  const [selectedGuincho, setSelectedGuincho] = useStateApp(null);

  useEffectApp(() => {
    window.abrirGuincho = (id) => { setSelectedGuincho(id); setPage('guincho-detalhe'); };
    return () => { delete window.abrirGuincho; };
  }, []);

  useEffectApp(() => {
    const handler = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, []);

  useEffectApp(() => {
    auth.session().then(s => { setSession(s); setAuthReady(true); });
    const { data: sub } = auth.onChange((_event, s) => setSession(s));
    return () => sub?.subscription?.unsubscribe?.();
  }, []);

  if (!authReady) {
    return (
      <div style={{
        minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: 'linear-gradient(135deg,#0F172A 0%,#1E3A5F 60%,#0F4C75 100%)'
      }}>
        <img src="logo.png" alt="" style={{
          width: 100, height: 100, borderRadius: '50%', objectFit: 'cover',
          transform: 'scale(1.06)', boxShadow: '0 0 0 4px rgba(245,158,11,0.5)',
          animation: 'pulse 1.4s infinite'
        }} />
      </div>
    );
  }

  if (!session) return <LoginScreen onLogin={() => {/* session será atualizada via listener */}} />;

  const renderScreen = () => {
    switch (page) {
      case 'dashboard':     return <DashboardScreen onNav={setPage} />;
      case 'assistencias':  return <AssistenciasScreen />;
      case 'vistoria':      return <VistoriaScreen />;
      case 'frota':         return <FrotaScreen />;
      case 'motoristas':    return <MotoristasScreen />;
      case 'seguradoras':   return <SeguradorasScreen />;
      case 'financeiro':    return <FinanceiroScreen />;
      case 'relatorios':    return <RelatoriosScreen />;
      case 'configuracoes': return <ConfigScreen />;
      case 'guincho-detalhe':
        return <GuinchoDetalheScreen
                  guinchoId={selectedGuincho}
                  onBack={() => { setPage('frota'); setSelectedGuincho(null); }} />;
      case 'lembretes':     return <LembretesConsolidadosScreen />;
      default:              return <DashboardScreen onNav={setPage} />;
    }
  };

  const handleLogout = async () => {
    await auth.signOut();
    showToast('Sessão encerrada', 'info');
  };

  return (
    <div style={{ display: 'flex', height: '100vh', background: '#F8FAFC', overflow: 'hidden' }}>
      {!isMobile && (
        <Sidebar active={page} onNav={setPage} collapsed={false} session={session} onLogout={handleLogout} />
      )}
      {isMobile && (
        <SidebarOverlay open={sidebarOpen} onClose={() => setSidebarOpen(false)} active={page} onNav={setPage} session={session} onLogout={handleLogout} />
      )}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', minWidth: 0 }}>
        <Topbar active={page} onMenuToggle={() => setSidebarOpen(!sidebarOpen)} isMobile={isMobile} onNav={setPage} session={session} />
        <main style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden' }}>
          {renderScreen()}
        </main>
      </div>
    </div>
  );
};

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