import { useState } from 'react';
import { Outlet } from 'react-router-dom';
import { Menu } from 'lucide-react';
import { useTheme } from '@/hooks/useTheme';
import { AlertsProvider } from '@/hooks/useAlerts';
import { LockProvider } from '@/hooks/useLock';
import { NotificationProvider } from '@/hooks/useNotifications';
import { Button } from '@/components/ui/button';
import Sidebar from './Sidebar';
import LockOverlay from './LockOverlay';
import NotificationToaster from '@/components/notifications/NotificationToaster';

export default function AppLayout() {
  useTheme();
  const [collapsed, setCollapsed] = useState(() => {
    try { return JSON.parse(localStorage.getItem('umbra-sidebar-collapsed') || 'false'); }
    catch { return false; }
  });
  const [mobileOpen, setMobileOpen] = useState(false);

  return (
    <LockProvider>
      <AlertsProvider>
        <NotificationProvider>
          <div className="flex h-dvh overflow-hidden bg-background">
            <Sidebar
              collapsed={collapsed}
              onToggle={() => {
                const next = !collapsed;
                setCollapsed(next);
                localStorage.setItem('umbra-sidebar-collapsed', JSON.stringify(next));
              }}
              mobileOpen={mobileOpen}
              onMobileClose={() => setMobileOpen(false)}
            />
            <div className="flex-1 flex flex-col overflow-hidden">
              {/* Mobile header */}
              <div className="flex md:hidden items-center h-14 border-b bg-card px-4">
                <Button variant="ghost" size="icon" onClick={() => setMobileOpen(true)}>
                  <Menu className="h-5 w-5" />
                </Button>
                <h1 className="text-lg font-bold text-accent ml-3">UMBRA</h1>
              </div>
              <main className="flex-1 overflow-y-auto mobile-scale">
                <Outlet />
              </main>
            </div>
          </div>
          <LockOverlay />
          <NotificationToaster />
        </NotificationProvider>
      </AlertsProvider>
    </LockProvider>
  );
}
