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('cms_token')

  // 앱 진입 시 현재 사용자 역할 조회 → RBAC 메뉴/가드 사용
  useEffect(() => {
    if (!token) return
    getMe()
      .then(r => {
        const me = r.data?.data || {}
        if (me.role) localStorage.setItem('cms_role', me.role)
        if (me.username) localStorage.setItem('cms_user', me.username)
      })
      .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>
  )
}
