import React, { useEffect, useState } from 'react'
import Sidebar from './Sidebar'
import { useRouter } from 'next/router'
import { useAuth } from '../context/AuthContext'

const PUBLIC_ROUTES = ['/login']
const NO_SIDEBAR_ROUTES = ['/login', '/inbox']

export default function Layout({ children }: { children: React.ReactNode }) {
  const router = useRouter()
  const { user, loading } = useAuth()
  const [mounted, setMounted] = useState(false)

  useEffect(() => { setMounted(true) }, [])

  const isPublic = PUBLIC_ROUTES.some((r) => router.pathname.startsWith(r))
  const hideSidebar = NO_SIDEBAR_ROUTES.some((r) => router.pathname === r || router.pathname.startsWith(r + '/'))

  // Tela de carregamento inicial — evita flash de conteúdo não autorizado
  if (!mounted || (loading && !isPublic)) {
    return (
      <div className="min-h-screen bg-[#070b14] flex items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <div className="w-10 h-10 border-4 border-brand-500 border-t-transparent rounded-full animate-spin" />
          <span className="text-slate-500 text-sm">Carregando...</span>
        </div>
      </div>
    )
  }

  // Rota privada sem usuário → AuthContext já redireciona, exibe blank para evitar flash
  if (!user && !isPublic) {
    return <div className="min-h-screen bg-[#070b14]" />
  }

  return (
    <div className="flex h-screen bg-[#070b14] overflow-hidden text-white font-sans w-full max-w-full selection:bg-brand-500/30">
      {!hideSidebar && <Sidebar />}
      <main className="flex-1 h-full relative w-full max-w-full flex-col flex overflow-y-auto overflow-x-hidden pt-safe pb-safe">
        {children}
      </main>
    </div>
  )
}
