'use client';

import { useState, useEffect, ReactNode } from 'react';
import { inventoryApi } from '@/lib/api';
import IdentityCheckOverlay from '@/components/IdentityCheckOverlay';
import BottomNav from '@/components/BottomNav';
import { Toaster, toast } from 'react-hot-toast';
import { usePathname, useRouter } from 'next/navigation';

interface PageShellProps {
  children: ReactNode;
  requireAdmin?: boolean;
}

export default function PageShell({ children, requireAdmin = false }: PageShellProps) {
  const [mounted, setMounted] = useState(false);
  const [currentUser, setCurrentUser] = useState<any | null>(null);
  const [showUserSelect, setShowUserSelect] = useState(false);
  const [users, setUsers] = useState<any[]>([]);
  const pathname = usePathname();
  const router = useRouter();

  useEffect(() => {
    setMounted(true);
    const savedUser = localStorage.getItem('inventory_user');
    
    if (savedUser) {
      const user = JSON.parse(savedUser);
      setCurrentUser(user);
      
      // Admin check
      if (requireAdmin && user.role !== 'admin') {
        toast.error("Access Denied: Admin role required");
        router.push('/');
      }
    } else {
      // Redirect to dedicated login page if not authenticated
      if (pathname !== '/login') {
        router.push('/login');
      }
    }

    // Refresh users list if needed for admin contexts
    if (requireAdmin) {
       inventoryApi.getUsers().then(setUsers).catch(() => {});
    }
  }, [requireAdmin, router, pathname]);


  if (!mounted) return null;

  // Prevent flicker by not rendering background if we're redirecting to login
  if (!currentUser && pathname !== '/login') return null;

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 flex flex-col">
      <Toaster position="top-center" />
      
      {/* Content Area */}
      <div className="flex-1 pb-32">
        {children}
      </div>

      {/* Navigation */}
      {pathname !== '/login' && <BottomNav currentUser={currentUser} />}
    </div>
  );
}
