import { Outlet, Navigate } from 'react-router-dom'
import { Toaster } from 'react-hot-toast'
import { Sidebar } from './Sidebar'
import { ComposeModal } from '@/components/ComposeModal/ComposeModal'
import { useAuth } from '@/hooks/useAuth'
import { useWebSocket } from '@/hooks/useWebSocket'
import { useEffect } from 'react'
import { useAuthStore } from '@/store/auth.store'

/**
 * Layout principale dell'applicazione autenticata.
 * Include: sidebar + area contenuto + WebSocket + toast notifications.
 */
export function AppLayout() {
  const { isAuthenticated, isLoading } = useAuth()
  const loadUser = useAuthStore((s) => s.loadUser)

  // Inizializza WebSocket (si connette automaticamente quando autenticato)
  useWebSocket()

  // Carica l'utente al mount se c'è un token
  useEffect(() => {
    loadUser()
  }, [loadUser])

  if (isLoading) {
    return (
      <div className="flex h-screen items-center justify-center bg-background">
        <div className="flex flex-col items-center gap-3">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
          <p className="text-sm text-muted-foreground">Caricamento...</p>
        </div>
      </div>
    )
  }

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />
  }

  return (
    <div className="flex h-screen overflow-hidden bg-background">
      {/* Sidebar navigazione */}
      <Sidebar />

      {/* Area contenuto principale */}
      <main className="flex-1 overflow-y-auto">
        <Outlet />
      </main>

      {/* Toast notifications globali */}
      <Toaster
        position="top-right"
        toastOptions={{
          duration: 4000,
          style: {
            background: 'hsl(var(--card))',
            color: 'hsl(var(--card-foreground))',
            border: '1px solid hsl(var(--border))',
          },
        }}
      />

      {/* Finestra di composizione PEC flottante (stile Gmail) */}
      <ComposeModal />
    </div>
  )
}
