import { useState, useEffect } from 'react'
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
import { TenantProvider } from './context/TenantContext'
import Navbar from './components/Navbar'
import LandingPage from './pages/LandingPage'
import LoginPage from './pages/LoginPage'
import RafflePage from './pages/RafflePage'
import DashboardPage from './pages/DashboardPage'
import ClubePage from './pages/ClubePage'
import CarteirinhaPage from './pages/CarteirinhaPage'
import VagasListPage from './pages/VagasListPage'
import VagaDetailPage from './pages/VagaDetailPage'
import CotacaoPage from './pages/CotacaoPage'
import { AuthAPI } from './api'

function AppContent() {
  const [user, setUser] = useState<any>(null)
  const [authChecked, setAuthChecked] = useState(false)

  useEffect(() => {
    AuthAPI.getMe()
      .then(data => setUser(data))
      .catch(() => setUser(null))
      .finally(() => setAuthChecked(true))

    const handler = () => setUser(null)
    window.addEventListener('app:logout', handler)
    return () => window.removeEventListener('app:logout', handler)
  }, [])

  function logout() {
    fetch('/user/logout', { credentials: 'include' }).catch(() => {})
    setUser(null)
    window.location.href = '/app/login'
  }

  if (!authChecked) {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center">
        <div className="w-8 h-8 border-2 border-amber-500 border-t-transparent rounded-full animate-spin" />
      </div>
    )
  }

  return (
    <>
      <Navbar user={user} onLogout={logout} />
      <Routes>
        <Route path="/"               element={<LandingPage />} />
        <Route path="/login"          element={user ? <Navigate to="/minha-area" replace /> : <LoginPage onLogin={setUser} />} />
        <Route path="/raffle"         element={<RafflePage user={user} />} />
        <Route path="/clube/:slug"    element={<ClubePage user={user} />} />
        <Route path="/vagas"          element={<VagasListPage />} />
        <Route path="/vagas/:id"      element={<VagaDetailPage user={user} />} />
        <Route path="/carteirinha/:cpf" element={<CarteirinhaPage />} />
        <Route path="/minha-area"     element={user ? <DashboardPage user={user} onLogout={logout} /> : <Navigate to="/login" replace />} />
        <Route path="/catalogo"       element={<CotacaoPage user={user} />} />
        <Route path="*"               element={<Navigate to="/" replace />} />
      </Routes>
    </>
  )
}

export default function App() {
  return (
    <TenantProvider>
      <Router basename="/app">
        <AppContent />
      </Router>
    </TenantProvider>
  )
}
