import { useEffect } from 'react'
import { Outlet, Navigate } from 'react-router-dom'
import Sidebar from './Sidebar'
import Header from './Header'
import { getMe } from '../api/client'

export default function Layout() {
  const token = localStorage.getItem('esn_token')

  useEffect(() => {
    if (!token) return
    getMe()
      .then(r => {
        const me = r.data?.data || {}
        if (me.role)     localStorage.setItem('esn_role',   me.role)
        if (me.username) localStorage.setItem('esn_user',   me.username)
        if (me.tenant)   localStorage.setItem('esn_tenant', me.tenant)
      })
      .catch(() => {})
  }, [token])

  if (!token) return <Navigate to="/login" replace />

  return (
    <div className="flex h-screen bg-ink">
      <Sidebar />
      <div className="flex-1 flex flex-col overflow-hidden">
        <Header />
        <main className="flex-1 overflow-auto p-6">
          <Outlet />
        </main>
      </div>
    </div>
  )
}
