// === Main App — SCP Sistema de Cotação de Preços ===
const { useState, useEffect, useMemo, useRef, useLayoutEffect } = React;

function App() {
  const [route, setRoute] = useState('dashboard');
  const [activeQuote, setActiveQuote] = useState(null);
  const [session, setSession] = useState(undefined); // undefined = carregando
  const [profile, setProfile] = useState(null);
  const [sidebarStats, setSidebarStats] = useState({ cotacoes: 0, pedidos: 0, estoque: 0, savingsThisYear: 0 });
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const contentRef = useRef(null);

  // Remove a tela de boot assim que o React monta.
  useEffect(() => {
    const boot = document.getElementById('boot');
    if (boot) {
      setTimeout(() => {
        boot.classList.add('gone');
        setTimeout(() => boot.remove(), 450);
      }, 300);
    }
  }, []);

  // Carrega sessão inicial e escuta mudanças do auth.
  useEffect(() => {
    scpAuth.getSession().then(s => setSession(s));
    const { data: sub } = scpAuth.onChange((s) => setSession(s));
    return () => sub.subscription.unsubscribe();
  }, []);

  // Sempre que a sessão muda, recarrega o profile.
  useEffect(() => {
    if (!session) { setProfile(null); return; }
    scpAuth.getProfile().then(p => setProfile(p));
  }, [session?.user?.id]);

  // Carrega contadores da sidebar e refaz a cada navegação (pra refletir mudanças)
  useEffect(() => {
    if (!session) return;
    window.scpDb.stats.sidebar().then(setSidebarStats).catch(() => {});
  }, [session?.user?.id, route]);

  const openQuotation = (id) => {
    setRoute('quotationDetail');
    setActiveQuote(id);
  };

  useEffect(() => {
    if (contentRef.current) contentRef.current.scrollTop = 0;
  }, [route]);

  const badges = {
    cotacoes: sidebarStats.cotacoes,
    pedidos: sidebarStats.pedidos,
    estoque: sidebarStats.estoque,
  };

  const handleSetRoute = (r) => {
    setRoute(r);
    if (r !== 'quotationDetail') setActiveQuote(null);
    setMobileMenuOpen(false); // fecha o menu mobile ao navegar
  };

  const handleSignOut = async () => {
    await scpAuth.signOut();
    setRoute('dashboard');
  };

  // Aguardando primeira leitura do auth — não renderiza nada ainda.
  if (session === undefined) return null;

  // Não autenticado → tela de login.
  if (!session) {
    return <ScreenLogin onSignedIn={(s) => setSession(s)} />;
  }

  return (
    <div className="scp-app">
      <Sidebar
        route={route}
        setRoute={handleSetRoute}
        badge={badges}
        profile={profile}
        session={session}
        onSignOut={handleSignOut}
        savingsThisYear={sidebarStats.savingsThisYear}
        mobileOpen={mobileMenuOpen}
        onMobileClose={() => setMobileMenuOpen(false)}
      />
      {mobileMenuOpen && <div className="scp-mobile-backdrop" onClick={() => setMobileMenuOpen(false)} />}
      <div className="scp-main" ref={contentRef}>
        <TopBar
          route={route}
          setRoute={handleSetRoute}
          openQuotation={openQuotation}
          onMenuClick={() => setMobileMenuOpen(true)}
        />
        <div className="scp-content" style={{ position: 'relative', zIndex: 1 }}>
          {route === 'dashboard'       && <ScreenDashboard       setRoute={handleSetRoute} openQuotation={openQuotation} />}
          {route === 'quotations'      && <ScreenQuotations      setRoute={handleSetRoute} openQuotation={openQuotation} />}
          {route === 'quotationDetail' && <ScreenQuotationDetail setRoute={handleSetRoute} quoteId={activeQuote} />}
          {route === 'newQuotation'    && <ScreenNewQuotation    setRoute={handleSetRoute} />}
          {route === 'suppliers'       && <ScreenSuppliers       setRoute={handleSetRoute} />}
          {route === 'products'        && <ScreenProducts        setRoute={handleSetRoute} />}
          {route === 'orders'          && <ScreenOrders          setRoute={handleSetRoute} openQuotation={openQuotation} />}
          {route === 'stock'           && <ScreenStock           setRoute={handleSetRoute} />}
          {route === 'reports'         && <ScreenReports   />}
          {route === 'portal'          && <ScreenPortal    />}
          {route === 'settings'        && <ScreenSettings  />}
        </div>
      </div>

      <style>{`
        .scp-app {
          display: flex; height: 100vh; overflow: hidden;
          position: relative; z-index: 1;
        }
        .scp-main {
          flex: 1; min-width: 0; display: flex; flex-direction: column;
          overflow: hidden;
        }
        .scp-content {
          flex: 1; overflow-y: auto; overflow-x: hidden;
        }
      `}</style>
    </div>
  );
}

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