import { useState } from 'react';
import { Outlet, useNavigate } from 'react-router-dom';
import { Menu } from 'lucide-react';
import Sidebar from './Sidebar';
import { useAuthGuard } from '@/hooks/useAuthGuard';

export default function AppLayout() {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const { status } = useAuthGuard();
  const navigate = useNavigate();

  if (status === 'loading') {
    return (
      <div className="min-h-screen flex items-center justify-center" style={{ background: '#1a0a2e' }}>
        <div className="w-8 h-8 border-4 border-white/20 border-t-orange-500 rounded-full animate-spin" />
      </div>
    );
  }

  if (status === 'unauthenticated' || status === 'denied') {
    // Use effect to avoid rendering issues during navigation
    if (typeof window !== 'undefined') window.location.replace('/login');
    return null;
  }

  return (
    <div className="flex h-screen bg-gray-50 overflow-hidden">
      <Sidebar open={sidebarOpen} onClose={() => setSidebarOpen(false)} />

      <div className="flex-1 flex flex-col min-w-0 md:ml-64">
        {/* Mobile topbar */}
        <header className="md:hidden h-14 flex items-center px-4 bg-white border-b border-gray-200 sticky top-0 z-30">
          <button
            onClick={() => setSidebarOpen(true)}
            className="text-gray-600 hover:text-gray-900"
          >
            <Menu size={22} />
          </button>
          <span className="ml-3 font-bold text-gray-800 text-sm">Shire 3D Manager</span>
        </header>

        <main className="flex-1 overflow-y-auto">
          <Outlet />
        </main>
      </div>
    </div>
  );
}