// Sou Coluna — Main App, view switching, auth bootstrapping
function App() {
  const [view, setView] = React.useState('landing'); // landing | app | loading
  const [user, setUser] = React.useState(null);
  const [loginOpen, setLoginOpen] = React.useState(false);
  const [registerOpen, setRegisterOpen] = React.useState(false);

  // Bootstrap: try to validate existing token on mount
  React.useEffect(() => {
    const tok = getToken();
    if (!tok) return;
    (async () => {
      try {
        const r = await api('/api/me');
        if (r.ok) {
          const d = await r.json();
          const u = d.user || d;
          if (u && u.id) { setUser(u); setView('app'); return; }
        }
        clearToken();
      } catch { clearToken(); }
    })();
  }, []);

  // Scroll reveal on landing
  React.useEffect(() => {
    if (view !== 'landing') return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.12 });
    document.querySelectorAll('.reveal').forEach(el => obs.observe(el));
    return () => obs.disconnect();
  }, [view]);

  function handleLoginSuccess(u) {
    setUser(u); setLoginOpen(false); setRegisterOpen(false); setView('app');
  }

  function handleLogout() {
    clearToken(); setUser(null); setView('landing');
  }

  if (view === 'app' && user) {
    return <InternalApp user={user} onLogout={handleLogout}/>;
  }

  return (
    <>
      <Nav
        onLogin={() => { setLoginOpen(true); setRegisterOpen(false); }}
        onSignup={() => { setRegisterOpen(true); setLoginOpen(false); }}
        onAccess={() => { setLoginOpen(true); setRegisterOpen(false); }}
      />
      <Hero onAccess={() => { setLoginOpen(true); setRegisterOpen(false); }}/>
      <HowItWorks/>
      <Vantagens/>
      <Sobre/>
      <CTA onAccess={() => { setLoginOpen(true); setRegisterOpen(false); }}/>
      <Footer/>
      <LoginModal
        open={loginOpen}
        onClose={() => setLoginOpen(false)}
        onSuccess={handleLoginSuccess}
        onSwitchRegister={() => { setLoginOpen(false); setRegisterOpen(true); }}
      />
      <RegisterModal
        open={registerOpen}
        onClose={() => setRegisterOpen(false)}
        onSuccess={() => {}}
        onSwitchLogin={() => { setRegisterOpen(false); setLoginOpen(true); }}
      />
    </>
  );
}

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