import { useState, useEffect } from 'react'
import { BrowserRouter, Routes, Route, NavLink } from 'react-router-dom'
import { auth } from './firebase'
import { onAuthStateChanged } from 'firebase/auth'
import { doc, getDoc } from 'firebase/firestore'
import { db } from './firebase'
import { ETAProvider } from './context/ETAContext'
import Dashboard from './screens/Dashboard'
import SeparationGuide from './screens/SeparationGuide'
import Reports from './screens/Reports'
import Login from './screens/Login'

export default function App() {
  const [usuario,  setUsuario]  = useState(null)   // { uid, email, colonia }
  const [checking, setChecking] = useState(true)   // mientras Firebase verifica sesión

  // Escucha si ya hay sesión activa (persiste aunque recargues la página)
  useEffect(() => {
    const unsub = onAuthStateChanged(auth, async (firebaseUser) => {
      if (firebaseUser) {
        // Recuperar colonia desde Firestore
        const snap = await getDoc(doc(db, 'usuarios', firebaseUser.uid))
        const colonia = snap.exists() ? snap.data().colonia : 'Zona Centro'
        setUsuario({ uid: firebaseUser.uid, email: firebaseUser.email, colonia })
      } else {
        setUsuario(null)
      }
      setChecking(false)
    })
    return () => unsub()
  }, [])

  function handleLogout() {
    auth.signOut()
    setUsuario(null)
  }

  // Pantalla de carga mientras Firebase verifica sesión
  if (checking) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', background: '#0a0e14' }}>
        <div style={{ width: 32, height: 32, border: '3px solid rgba(61,154,255,0.2)', borderTop: '3px solid #3d9aff', borderRadius: '50%', animation: 'spin 1s linear infinite' }} />
      </div>
    )
  }

  // Si no hay sesión → mostrar Login
  if (!usuario) {
    return <Login onLogin={setUsuario} />
  }

  // App principal con sesión activa
  return (
    <ETAProvider colonia={usuario.colonia}>
      <BrowserRouter>
        {/* Barra de navegación */}
        <nav style={navStyle}>
          <NavLink to="/"       end style={({ isActive }) => tabStyle(isActive)}>Dashboard</NavLink>
          <NavLink to="/guia"       style={({ isActive }) => tabStyle(isActive)}>Separación</NavLink>
          <NavLink to="/reportes"   style={({ isActive }) => tabStyle(isActive)}>Reportes</NavLink>
          {/* Botón de cerrar sesión */}
          <div
            onClick={handleLogout}
            style={{ ...tabStyle(false), marginLeft: 'auto', cursor: 'pointer' }}
          >
            Salir
          </div>
        </nav>

        <main style={{ maxWidth: 480, margin: '0 auto', padding: '0 0 32px' }}>
          <Routes>
            <Route path="/"         element={<Dashboard />} />
            <Route path="/guia"     element={<SeparationGuide />} />
            <Route path="/reportes" element={<Reports />} />
          </Routes>
        </main>
      </BrowserRouter>
    </ETAProvider>
  )
}

const navStyle = {
  display: 'flex',
  background: '#131820',
  borderBottom: '1px solid rgba(255,255,255,0.08)',
  padding: '0 16px',
  position: 'sticky',
  top: 0,
  zIndex: 100,
}

const tabStyle = (isActive) => ({
  padding: '12px 14px',
  fontSize: '12px',
  fontWeight: 500,
  color: isActive ? '#3d9aff' : '#6b7f96',
  borderBottom: isActive ? '2px solid #3d9aff' : '2px solid transparent',
  textDecoration: 'none',
  letterSpacing: '0.04em',
  textTransform: 'uppercase',
  whiteSpace: 'nowrap',
  transition: 'color 0.2s',
})
