'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import AdminSidebar from '@/components/admin/AdminSidebar';
import { isAdmin, getCurrentUser } from '@/lib/auth';

export default function AdminLayout({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const [isAuthorized, setIsAuthorized] = useState(false);
  const [user, setUser] = useState<any>(null);

  useEffect(() => {
    // 权限检查
    const token = localStorage.getItem('rsid');
    if (!token) {
      router.push('/login');
      return;
    }
    if (!isAdmin()) {
      alert("您没有权限访问管理后台");
      router.push('/dashboard');
      return;
    }
    setIsAuthorized(true);
    setUser(getCurrentUser());
  }, [router]);

  if (!isAuthorized) return null;

  return (
    <div className="min-h-screen bg-slate-50 flex flex-col md:flex-row font-sans text-slate-900">
      
      {/* 
         侧边栏组件 
         - 内部自包含移动端 Header 和开关逻辑
         - 不需要传递 isOpen / onClose 
      */}
      <AdminSidebar />

      {/* 
         主内容区域 
         - flex-1: 占满剩余空间
         - pt-16: 移动端顶部留出 64px 给 Sidebar 的固定 Header
         - md:pt-0: 桌面端不需要留白（左右布局）
         - h-screen: 限制高度以便内部滚动 (可选，视需求而定)
      */}
      <main className="flex-1 flex flex-col min-w-0 pt-16 md:pt-0 h-screen overflow-hidden">
        
        {/* 
           Desktop Header (右侧顶部栏)
           - 显示页面标题和用户信息
           - 移动端如果觉得太挤可以隐藏 (hidden md:flex)，或者保留
        */}
        <header className="bg-white shadow-sm h-16 flex items-center justify-between px-6 flex-shrink-0 z-10 border-b border-slate-200">
          <h2 className="font-bold text-lg text-slate-800">管理控制台</h2>

          <div className="flex items-center gap-4">
            <div className="text-right hidden sm:block">
              <div className="text-sm font-medium text-slate-700">
                {user?.nickname || 'Administrator'}
              </div>
              <div className="text-xs text-slate-500">
                {user?.email}
              </div>
            </div>
            <div className="h-9 w-9 bg-blue-100 rounded-full flex items-center justify-center text-blue-600 font-bold text-sm border border-blue-200">
              AD
            </div>
          </div>
        </header>

        {/* 页面内容滚动区 */}
        <div className="flex-1 overflow-y-auto p-4 md:p-8 scroll-smooth">
          <div className="max-w-7xl mx-auto">
            {children}
          </div>
        </div>
      </main>
    </div>
  );
}