import React, { useState, useEffect, PropsWithChildren } from 'react';
import { Link, usePage, router } from '@inertiajs/react';
import Dropdown from '@/Components/Dropdown';
import { PageProps } from '@/types';
import {
  Store,
  ShoppingCart,
  Receipt,
  Clock,
  Users,
  Package,
  FolderTree,
  BarChart3,
  UserCheck,
  Building2,
  Settings,
  ShieldCheck,
  LogOut,
  Menu,
  X,
  Sparkles,
  CheckCircle2,
  AlertCircle,
  ChevronRight,
  ChevronDown,
  LayoutDashboard,
  Search,
  Bell,
  Trash2,
  DollarSign,
  Activity,
  Sun,
  Moon,
  Palette,
  Heart
} from '@/Components/AnimatedIcons';

interface ExtendedPageProps extends PageProps {
  branchContext?: {
    activeBranchId: number | null;
    activeBranch: any;
    isCentralView: boolean;
    availableBranches: Array<{ id: number; code: string; name: string; short_name: string }>;
  };
}

export default function AuthenticatedLayout({ children }: PropsWithChildren) {
  const { auth, flash, settings, branchContext } = usePage<ExtendedPageProps>().props;
  const user = auth.user;
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  
  // Notifications
  const [showNotifications, setShowNotifications] = useState(false);
  const unreadCount = (user as any)?.unread_notifications_count || 0;
  const recentNotifications = (user as any)?.recent_notifications || [];

  const markAsRead = (id: string) => {
    router.post(route('notifications.mark-as-read', id), {}, { preserveScroll: true });
  };

  // Theme mode (Light / Dark) and Accent Color (Pink / SeaGreen)
  const [themeMode, setThemeMode] = useState<'light' | 'dark'>(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('admin_theme_mode');
      if (saved === 'dark' || saved === 'light') return saved;
    }
    return 'light';
  });

  const [accentColor, setAccentColor] = useState<'pink' | 'seagreen'>(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('admin_accent_color');
      if (saved === 'pink' || saved === 'seagreen') return saved;
    }
    return 'pink';
  });

  useEffect(() => {
    localStorage.setItem('admin_theme_mode', themeMode);
    if (themeMode === 'dark') {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
  }, [themeMode]);

  useEffect(() => {
    localStorage.setItem('admin_accent_color', accentColor);
    // Dispatch custom event for child components to re-render if needed
    window.dispatchEvent(new Event('theme_accent_changed'));
  }, [accentColor]);

  const toggleTheme = () => {
    setThemeMode((prev: string) => (prev === 'light' ? 'dark' : 'light'));
  };

  const toggleAccent = () => {
    setAccentColor((prev: string) => (prev === 'pink' ? 'seagreen' : 'pink'));
  };

  const hasPermission = (permission: string) => {
    if (!user) return false;
    if (user.is_admin) return true;
    return user.permissions?.includes(permission);
  };

  const isCurrentRoute = (pattern: string) => {
    try {
      return route().current(pattern);
    } catch {
      return false;
    }
  };

  const handleBranchSwitch = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const value = e.target.value;
    switchBranch(value);
  };

  const switchBranch = (id: string | null) => {
    router.post(route('admin.switch-branch'), {
      branch_id: id ? parseInt(id, 10) : null
    });
  };

  const isPink = accentColor === 'pink';

  // Accent helper classes
  const accentTextClass = isPink ? 'text-[#FF0D8F] dark:text-[#FF4DB8]' : 'text-[#0CA996] dark:text-[#00C8B2]';
  const accentBgClass = isPink ? 'bg-[#FF0D8F]' : 'bg-[#0CA996]';
  const accentHoverBgClass = isPink ? 'hover:bg-[#E0067B]' : 'hover:bg-[#098777]';
  const accentBadgeClass = isPink
    ? 'bg-[#FF0D8F]/10 text-[#FF0D8F] border border-[#FF0D8F]/20 dark:bg-[#FF0D8F]/20 dark:text-[#FFC1E1]'
    : 'bg-[#0CA996]/10 text-[#0CA996] border border-[#0CA996]/20 dark:bg-[#0CA996]/20 dark:text-[#00C8B2]';
  const activeNavItemClass = isPink 
    ? 'bg-[#FDF1F3] dark:bg-[#FF0D8F]/10 text-[#9D1739] dark:text-[#FFC1E1] font-bold shadow-none'
    : 'bg-[#E6F6F4] dark:bg-[#0CA996]/10 text-[#098777] dark:text-[#0CA996] font-bold shadow-none';

  return (
    <div className={`min-h-screen font-sans flex flex-col antialiased transition-colors duration-200 ${
      themeMode === 'dark' ? 'bg-slate-950 text-slate-100 dark' : 'bg-slate-50 text-slate-800'
    }`}>
      {/* DESKTOP SIDEBAR */}
      <aside
        className={`hidden lg:flex flex-col fixed inset-y-0 left-0 z-50 bg-white dark:bg-slate-950 text-slate-800 dark:text-slate-200 transition-all duration-300 border-r border-slate-200 dark:border-slate-800 shadow-sm ${
          sidebarCollapsed ? 'w-20' : 'w-72'
        }`}
      >
        {/* Sidebar Header / Brand */}
        <div className="h-16 px-5 flex items-center justify-between border-b border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950">
          <Link href="/" className="flex items-center space-x-3 group overflow-hidden">
            <div className="relative flex-shrink-0">
              <div className={`w-9 h-9 rounded-xl ${accentBgClass} text-white flex items-center justify-center font-black shadow-md transition-transform duration-300 group-hover:scale-105`}>
                <Sparkles className="w-5 h-5 text-white" />
              </div>
            </div>
            {!sidebarCollapsed && (
              <div className="transition-opacity duration-300">
                <span className=" font-extrabold text-sm tracking-tight text-slate-900 dark:text-white block leading-tight">
                  Laya's POS
                </span>
                <span className={`text-[10px] font-extrabold uppercase tracking-wider block ${accentTextClass}`}>
                  Cakes & Candles
                </span>
              </div>
            )}
          </Link>
        </div>

        {/* Active Branch Display */}
        {user?.branch && !sidebarCollapsed && (
          <div className="px-3.5 py-2.5 mx-4 mt-4 bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl flex items-center space-x-2.5 text-xs text-slate-600 dark:text-slate-400 shadow-xs">
            <Store className={`w-4 h-4 flex-shrink-0 ${accentTextClass}`} />
            <div className="overflow-hidden">
              <span className="block font-bold text-slate-900 dark:text-white truncate text-xs">{user.branch.name}</span>
              <span className="block text-[10px] text-slate-400 ">Code: {user.branch.code}</span>
            </div>
          </div>
        )}

        {/* Sidebar Navigation */}
        <div className="flex-1 overflow-y-auto px-4 py-4 space-y-6 scrollbar-thin scrollbar-thumb-slate-200 dark:scrollbar-thumb-slate-800">
          {/* Section: Operations */}
          <div>
            {!sidebarCollapsed && (
              <h4 className="px-3 text-[10px] font-extrabold text-slate-400 uppercase tracking-widest mb-2 ">
                Operations
              </h4>
            )}
            <div className="space-y-1">
              {hasPermission('pos.access') && (
                <Link
                  href={route('pos.index')}
                  className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                    isCurrentRoute('pos.*')
                      ? activeNavItemClass
                      : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                  }`}
                  title="POS Billing Terminal"
                >
                  <ShoppingCart className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('pos.*') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                  {!sidebarCollapsed && <span className="font-medium">POS Terminal</span>}
                </Link>
              )}

              {hasPermission('invoice.view') && (
                <Link
                  href={route('invoices.index')}
                  className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                    isCurrentRoute('invoices.*')
                      ? activeNavItemClass
                      : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                  }`}
                  title="Invoices"
                >
                  <Receipt className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('invoices.*') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                  {!sidebarCollapsed && <span className="font-medium">Invoices</span>}
                </Link>
              )}

              {hasPermission('daily_closing.create') && (
                <Link
                  href={route('daily-closing.index')}
                  className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                    isCurrentRoute('daily-closing.*')
                      ? activeNavItemClass
                      : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                  }`}
                  title="Daily Closing"
                >
                  <Clock className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('daily-closing.*') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                  {!sidebarCollapsed && <span className="font-medium">Daily Closing</span>}
                </Link>
              )}

              <Link
                href={route('wastage.index')}
                className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                  isCurrentRoute('wastage.*')
                    ? activeNavItemClass
                    : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                }`}
                title="Wastage Register"
              >
                <Trash2 className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('wastage.*') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                {!sidebarCollapsed && <span className="font-medium">Wastage Register</span>}
              </Link>

              <Link
                href={route('expenses.index')}
                className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                  isCurrentRoute('expenses.*')
                    ? activeNavItemClass
                    : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                }`}
                title="Branch Expenses"
              >
                <DollarSign className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('expenses.*') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                {!sidebarCollapsed && <span className="font-medium">Branch Expenses</span>}
              </Link>
            </div>
          </div>

          {/* Section: Catalog & CRM */}
          {(hasPermission('products.view') || hasPermission('customers.view')) && (
            <div>
              {!sidebarCollapsed && (
                <h4 className="px-3 text-[10px] font-extrabold text-slate-400 uppercase tracking-widest mb-2 ">
                  Catalog & CRM
                </h4>
              )}
            <div className="space-y-1">
              {hasPermission('products.view') && (
                <Link
                  href={route('admin.products.index')}
                  className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                    isCurrentRoute('admin.products.*')
                      ? activeNavItemClass
                      : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                  }`}
                  title="Products & Categories"
                >
                  <Package className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('admin.products.*') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                  {!sidebarCollapsed && <span className="font-medium">Products</span>}
                </Link>
              )}

              {hasPermission('customers.view') && (
                <Link
                  href={route('admin.customers.index')}
                  className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                    isCurrentRoute('admin.customers.*')
                      ? activeNavItemClass
                      : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                  }`}
                  title="Customers CRM"
                >
                  <Users className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('admin.customers.*') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                  {!sidebarCollapsed && <span className="font-medium">Customers</span>}
                </Link>
              )}
            </div>
            </div>
          )}

          {/* Section: Analytics & Management */}
          <div>
            {!sidebarCollapsed && (
              <h4 className="px-3 text-[10px] font-extrabold text-slate-400 uppercase tracking-widest mb-2 ">
                Analytics & Management
              </h4>
            )}
            <div className="space-y-1">
              {hasPermission('dashboard.view') && (
                <Link
                  href={route('admin.dashboard')}
                  className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                    isCurrentRoute('admin.dashboard')
                      ? activeNavItemClass
                      : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                  }`}
                  title="Admin Dashboard"
                >
                  <LayoutDashboard className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('admin.dashboard') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                  {!sidebarCollapsed && <span className="font-medium">Admin Dashboard</span>}
                </Link>
              )}

              {user?.is_admin && (
                <Link
                  href={route('admin.branch-operations')}
                  className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                    isCurrentRoute('admin.branch-operations')
                      ? activeNavItemClass
                      : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                  }`}
                  title="Control Room (All Branches)"
                >
                  <Activity className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('admin.branch-operations') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                  {!sidebarCollapsed && <span className="font-medium">Control Room</span>}
                </Link>
              )}

              <Link
                href={route('branch.dashboard')}
                className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                  isCurrentRoute('branch.dashboard')
                    ? activeNavItemClass
                    : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                }`}
                title="Branch Dashboard"
              >
                <Store className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('branch.dashboard') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                {!sidebarCollapsed && <span className="font-medium">Branch Operations</span>}
              </Link>

              {hasPermission('reports.sales') && (
                <Link
                  href={route('admin.reports.index')}
                  className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                    isCurrentRoute('admin.reports.*')
                      ? activeNavItemClass
                      : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                  }`}
                  title="Sales & Reports"
                >
                  <BarChart3 className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('admin.reports.*') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                  {!sidebarCollapsed && <span className="font-medium">Reports</span>}
                </Link>
              )}

              {hasPermission('users.view') && (
                <Link
                  href={route('admin.users.index')}
                  className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                    isCurrentRoute('admin.users.*')
                      ? activeNavItemClass
                      : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                  }`}
                  title="Staff Users"
                >
                  <UserCheck className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('admin.users.*') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                  {!sidebarCollapsed && <span className="font-medium">Staff Users</span>}
                </Link>
              )}
            </div>
          </div>

          {/* Section: System Settings */}
          {(hasPermission('branches.view') || hasPermission('settings.view') || hasPermission('audit.view')) && (
            <div>
              {!sidebarCollapsed && (
                <h4 className="px-3 text-[10px] font-extrabold text-slate-400 uppercase tracking-widest mb-2 ">
                  System
                </h4>
              )}
            <div className="space-y-1">
              {hasPermission('branches.view') && (
                <Link
                  href={route('admin.branches.index')}
                  className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                    isCurrentRoute('admin.branches.*')
                      ? activeNavItemClass
                      : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                  }`}
                  title="Branches Master"
                >
                  <Building2 className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('admin.branches.*') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                  {!sidebarCollapsed && <span className="font-medium">Branches Master</span>}
                </Link>
              )}

              {hasPermission('settings.view') && (
                <Link
                  href={route('admin.settings.index')}
                  className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                    isCurrentRoute('admin.settings.*')
                      ? activeNavItemClass
                      : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                  }`}
                  title="Business Settings"
                >
                  <Settings className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('admin.settings.*') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                  {!sidebarCollapsed && <span className="font-medium">Settings</span>}
                </Link>
              )}

              {hasPermission('audit.view') && (
                <Link
                  href={route('admin.audit-logs.index')}
                  className={`w-full flex items-center space-x-3 px-3.5 py-2.5 rounded-xl text-sm transition-all group ${
                    isCurrentRoute('admin.audit-logs.*')
                      ? activeNavItemClass
                      : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'
                  }`}
                  title="Security Audit Logs"
                >
                  <ShieldCheck className={`w-4 h-4 flex-shrink-0 ${isCurrentRoute('admin.audit-logs.*') ? 'text-current' : 'text-slate-400 group-hover:text-slate-700 dark:group-hover:text-slate-300'}`} />
                  {!sidebarCollapsed && <span className="font-medium">Audit Logs</span>}
                </Link>
              )}
            </div>
            </div>
          )}
        </div>

        {/* Sidebar Footer: User Card */}
        <div className="p-4 border-t border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950 no-print">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3 overflow-hidden">
              <div className={`w-9 h-9 rounded-full ${accentBgClass} text-white font-extrabold flex items-center justify-center text-xs shadow-sm flex-shrink-0`}>
                {user?.name?.charAt(0).toUpperCase() || 'U'}
              </div>
              {!sidebarCollapsed && (
                <div className="overflow-hidden">
                  <span className="block text-xs font-bold text-slate-900 dark:text-slate-100 truncate">{user?.name}</span>
                  <span className="block text-[10px] text-slate-500 dark:text-slate-400 font-medium capitalize">
                    {user?.role?.label || 'Staff'}
                  </span>
                </div>
              )}
            </div>

            <Link
              href={route('logout')}
              method="post"
              as="button"
              className="p-2 text-slate-400 hover:text-rose-400 hover:bg-slate-800 rounded-lg transition-colors flex-shrink-0"
              title="Logout"
            >
              <LogOut className="w-4 h-4" />
            </Link>
          </div>
        </div>
      </aside>

      {/* MAIN CONTAINER */}
      <div className={`flex-1 flex flex-col transition-all duration-300 ${sidebarCollapsed ? 'lg:pl-20' : 'lg:pl-72'}`}>
        {/* TOP HEADER BAR */}
        <header className="bg-white/90 dark:bg-slate-900/90 backdrop-blur-md border-b border-slate-200 dark:border-slate-800 sticky top-0 z-40 no-print shadow-2xs">
          <div className="px-4 sm:px-6 lg:px-8">
            <div className="flex justify-between h-16 items-center">
              {/* Left Side: Mobile Menu Button & Breadcrumbs */}
              <div className="flex items-center space-x-3">
                <button
                  onClick={() => setMobileMenuOpen(true)}
                  className="lg:hidden p-2 text-slate-600 dark:text-slate-300 hover:text-slate-900 rounded-xl hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
                >
                  <Menu className="w-5 h-5" />
                </button>

                <div className="hidden sm:flex items-center space-x-2 text-slate-400 dark:text-slate-500 text-xs font-medium">
                  <span className={`font-bold text-sm ${accentTextClass}`}>Laya's POS</span>
                  <span>/</span>
                  <span className="text-slate-700 dark:text-slate-300 capitalize">
                    {user?.role?.label || 'Admin'} Panel
                  </span>
                </div>
              </div>

              {/* Right Side Controls: Theme Mode, Accent Color Switcher, Branch Switcher & User */}
              <div className="flex items-center space-x-2.5 sm:space-x-3">
                {/* Accent Color Switcher Toggle (Pink vs SeaGreen) */}
                <button
                  onClick={toggleAccent}
                  className="px-2.5 py-1.5 rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-200 text-xs font-semibold flex items-center space-x-1.5 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors"
                  title={`Switch Accent Color (Current: ${isPink ? 'Pink' : 'Sea Green'})`}
                >
                  <span className={`w-3 h-3 rounded-full ${accentBgClass}`} />
                  <span className="hidden md:inline  text-[11px]">{isPink ? 'Pink' : 'Sea Green'}</span>
                </button>

                {/* Dark / Light Mode Toggle */}
                <button
                  onClick={toggleTheme}
                  className="p-2 rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-200 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors"
                  title={`Switch to ${themeMode === 'light' ? 'Dark' : 'Light'} Mode`}
                >
                  {themeMode === 'light' ? (
                    <Moon className="w-4 h-4 text-slate-700" />
                  ) : (
                    <Sun className="w-4 h-4 text-amber-400" />
                  )}
                </button>

                {/* Super Admin Global Branch Switcher */}
                {user?.is_admin && branchContext?.availableBranches && (
                  <div className="relative">
                    <Dropdown>
                      <Dropdown.Trigger>
                        <button type="button" className="flex items-center space-x-2 bg-slate-100 dark:bg-slate-900 text-slate-800 dark:text-white px-3 py-1.5 rounded-xl text-xs font-medium border border-slate-200 dark:border-slate-800 shadow-sm transition-all duration-200 hover:bg-slate-200 dark:hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-slate-200 dark:focus:ring-slate-700">
                          <Store className={`w-3.5 h-3.5 ${accentTextClass} flex-shrink-0`} />
                          <span className="truncate max-w-[200px] font-semibold">
                            {branchContext.activeBranchId
                              ? branchContext.availableBranches.find((b: any) => b.id == branchContext.activeBranchId)?.name || 'All Branches (Central Admin)'
                              : 'All Branches (Central Admin)'}
                          </span>
                          <ChevronDown className="w-3.5 h-3.5 text-slate-400 dark:text-slate-500 flex-shrink-0" />
                        </button>
                      </Dropdown.Trigger>

                      <Dropdown.Content align="right" width="auto" contentClasses="py-1 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 shadow-xl">
                        <button
                          type="button"
                          onClick={() => switchBranch('')}
                          className={`w-full text-left block px-4 py-2.5 text-xs transition duration-150 ease-in-out hover:bg-slate-100 dark:hover:bg-slate-800 ${
                            !branchContext.activeBranchId
                              ? 'bg-slate-50 dark:bg-slate-800/50 text-slate-900 dark:text-white font-bold'
                              : 'text-slate-700 dark:text-slate-300 font-medium'
                          }`}
                        >
                          All Branches (Central Admin)
                        </button>
                        {branchContext.availableBranches.map((b: any) => (
                          <button
                            type="button"
                            key={b.id}
                            onClick={() => switchBranch(b.id.toString())}
                            className={`w-full text-left block px-4 py-2.5 text-xs transition duration-150 ease-in-out hover:bg-slate-100 dark:hover:bg-slate-800 ${
                              branchContext.activeBranchId == b.id
                                ? 'bg-slate-50 dark:bg-slate-800/50 text-slate-900 dark:text-white font-bold'
                                : 'text-slate-700 dark:text-slate-300 font-medium'
                            }`}
                          >
                            {b.name} <span className="text-[10px] text-slate-400 dark:text-slate-500 ml-1">({b.code})</span>
                          </button>
                        ))}
                      </Dropdown.Content>
                    </Dropdown>
                  </div>
                )}

                {/* Notification Bell */}
                <div className="relative">
                  <button 
                    type="button" 
                    onClick={() => setShowNotifications(!showNotifications)}
                    className={`relative p-2 rounded-xl border transition-colors ${showNotifications ? `border-[${isPink ? '#FF0D8F' : '#0CA996'}] ${accentTextClass}` : 'border-slate-200 dark:border-slate-700 bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-200 hover:bg-slate-200 dark:hover:bg-slate-700'}`}
                  >
                    <Bell className="w-4 h-4" />
                    {unreadCount > 0 && (
                      <span className={`absolute -top-1 -right-1 min-w-[16px] h-4 ${accentBgClass} text-white text-[9px] font-bold rounded-full flex items-center justify-center px-1 shadow-xs`}>
                        {unreadCount}
                      </span>
                    )}
                  </button>

                  {/* Dropdown */}
                  {showNotifications && (
                    <div className="absolute right-0 mt-2 w-80 bg-white dark:bg-slate-900 rounded-2xl shadow-xl border border-slate-200 dark:border-slate-800 z-50 overflow-hidden flex flex-col">
                      <div className="p-3 border-b border-slate-100 dark:border-slate-800 flex items-center justify-between bg-slate-50/50 dark:bg-slate-900/50">
                        <h3 className="font-bold text-slate-800 dark:text-white text-sm">Notifications</h3>
                        {unreadCount > 0 && (
                          <button 
                            onClick={() => router.post(route('notifications.mark-all-as-read'), {}, { preserveScroll: true })}
                            className={`text-[10px] font-bold ${accentTextClass} hover:opacity-80`}
                          >
                            Mark all as read
                          </button>
                        )}
                      </div>
                      <div className="max-h-80 overflow-y-auto">
                        {recentNotifications.length > 0 ? (
                          recentNotifications.map((notification: any) => (
                            <div key={notification.id} className={`p-3 border-b border-slate-100 dark:border-slate-800 last:border-b-0 hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors flex items-start space-x-3 ${!notification.read_at ? (isPink ? 'bg-[#FDF1F3]/30 dark:bg-[#FF0D8F]/10' : 'bg-[#E6F6F4]/50 dark:bg-[#0CA996]/10') : ''}`}>
                              <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${!notification.read_at ? `${accentTextClass} bg-current/10` : 'bg-slate-100 dark:bg-slate-800 text-slate-500'}`}>
                                <Bell className="w-4 h-4" />
                              </div>
                              <div className="flex-1 min-w-0">
                                <p className="text-xs text-slate-800 dark:text-slate-200 font-medium">{notification.data?.message || 'New notification'}</p>
                                <p className="text-[10px] text-slate-500 mt-0.5">{new Date(notification.created_at).toLocaleString()}</p>
                              </div>
                              {!notification.read_at && (
                                <button onClick={() => markAsRead(notification.id)} className={`text-slate-400 hover:${accentTextClass} p-1`} title="Mark as read">
                                  <CheckCircle2 className="w-4 h-4" />
                                </button>
                              )}
                            </div>
                          ))
                        ) : (
                          <div className="p-8 text-center">
                            <Bell className="w-8 h-8 text-slate-300 dark:text-slate-700 mx-auto mb-2 opacity-50" />
                            <p className="text-xs text-slate-500 font-medium">No recent notifications</p>
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </div>

                {hasPermission('pos.access') && (
                  <Link
                    href={route('pos.index')}
                    className={`px-3.5 py-1.5 ${accentBgClass} ${accentHoverBgClass} text-white font-bold text-xs rounded-xl shadow-xs flex items-center space-x-1.5 transition-all hover:scale-[1.02]`}
                  >
                    <ShoppingCart className="w-3.5 h-3.5" />
                    <span className="hidden md:inline">POS Terminal</span>
                  </Link>
                )}
              </div>
            </div>
          </div>
        </header>

        {/* MOBILE DRAWER MENU */}
        {mobileMenuOpen && (
          <div className="fixed inset-0 z-50 lg:hidden flex">
            <div
              className="fixed inset-0 bg-slate-950/60 backdrop-blur-xs transition-opacity"
              onClick={() => setMobileMenuOpen(false)}
            />

            <div className="relative flex-1 flex flex-col max-w-xs w-full bg-white dark:bg-slate-900 text-slate-800 dark:text-slate-200 shadow-2xl">
              <div className="h-16 px-6 flex items-center justify-between border-b border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950">
                <div className="flex items-center space-x-2">
                  <div className={`w-7 h-7 rounded-lg ${accentBgClass} text-white flex items-center justify-center font-bold`}>
                    <Sparkles className="w-4 h-4 text-white" />
                  </div>
                  <span className="font-extrabold text-sm text-slate-900 dark:text-white">Laya's POS</span>
                </div>
                <button
                  onClick={() => setMobileMenuOpen(false)}
                  className="p-1.5 text-slate-500 hover:text-slate-900 dark:text-slate-400 dark:hover:text-white rounded-lg"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              <div className="flex-1 overflow-y-auto p-4 space-y-4">
                {hasPermission('pos.access') && (
                  <Link
                    href={route('pos.index')}
                    onClick={() => setMobileMenuOpen(false)}
                    className={`block px-4 py-2.5 ${accentBgClass} text-white font-bold text-sm rounded-xl text-center shadow-xs`}
                  >
                    POS Billing Terminal
                  </Link>
                )}

                <div className="space-y-1">
                  {hasPermission('invoice.view') && (
                    <Link
                      href={route('invoices.index')}
                      onClick={() => setMobileMenuOpen(false)}
                      className="block px-3.5 py-2 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900"
                    >
                      Invoices
                    </Link>
                  )}
                  {hasPermission('daily_closing.create') && (
                    <Link
                      href={route('daily-closing.index')}
                      onClick={() => setMobileMenuOpen(false)}
                      className="block px-3.5 py-2 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900"
                    >
                      Daily Closing
                    </Link>
                  )}
                  <Link
                    href={route('wastage.index')}
                    onClick={() => setMobileMenuOpen(false)}
                    className="block px-3.5 py-2 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900"
                  >
                    Wastage Register
                  </Link>
                  <Link
                    href={route('expenses.index')}
                    onClick={() => setMobileMenuOpen(false)}
                    className="block px-3.5 py-2 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900"
                  >
                    Branch Expenses
                  </Link>
                  {hasPermission('customers.view') && (
                    <Link
                      href={route('admin.customers.index')}
                      onClick={() => setMobileMenuOpen(false)}
                      className="block px-3.5 py-2 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900"
                    >
                      Customers CRM
                    </Link>
                  )}
                  {hasPermission('dashboard.view') && (
                    <Link
                      href={route('admin.dashboard')}
                      onClick={() => setMobileMenuOpen(false)}
                      className="block px-3.5 py-2 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900"
                    >
                      Admin Dashboard
                    </Link>
                  )}
                  {user?.is_admin && (
                    <Link
                      href={route('admin.branch-operations')}
                      onClick={() => setMobileMenuOpen(false)}
                      className="block px-3.5 py-2 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900"
                    >
                      Control Room (All Branches)
                    </Link>
                  )}
                  <Link
                    href={route('branch.dashboard')}
                    onClick={() => setMobileMenuOpen(false)}
                    className="block px-3.5 py-2 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900"
                  >
                    Branch Operations Dashboard
                  </Link>
                  {hasPermission('products.view') && (
                    <Link
                      href={route('admin.products.index')}
                      onClick={() => setMobileMenuOpen(false)}
                      className="block px-3.5 py-2 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900"
                    >
                      Products & Categories
                    </Link>
                  )}
                  {hasPermission('reports.sales') && (
                    <Link
                      href={route('admin.reports.index')}
                      onClick={() => setMobileMenuOpen(false)}
                      className="block px-3.5 py-2 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900"
                    >
                      Sales Reports
                    </Link>
                  )}
                  {hasPermission('users.view') && (
                    <Link
                      href={route('admin.users.index')}
                      onClick={() => setMobileMenuOpen(false)}
                      className="block px-3.5 py-2 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900"
                    >
                      Staff Users
                    </Link>
                  )}
                  {hasPermission('branches.view') && (
                    <Link
                      href={route('admin.branches.index')}
                      onClick={() => setMobileMenuOpen(false)}
                      className="block px-3.5 py-2 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900"
                    >
                      Branches Master
                    </Link>
                  )}
                  {hasPermission('settings.view') && (
                    <Link
                      href={route('admin.settings.index')}
                      onClick={() => setMobileMenuOpen(false)}
                      className="block px-3.5 py-2 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900"
                    >
                      Business Settings
                    </Link>
                  )}
                  {hasPermission('audit.view') && (
                    <Link
                      href={route('admin.audit-logs.index')}
                      onClick={() => setMobileMenuOpen(false)}
                      className="block px-3.5 py-2 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900"
                    >
                      Security Audit Logs
                    </Link>
                  )}
                </div>
              </div>

              <div className="p-4 border-t border-slate-800 bg-slate-950 flex items-center justify-between">
                <div>
                  <span className="block text-xs font-bold text-white">{user?.name}</span>
                  <span className={`block text-[10px] ${accentTextClass} capitalize`}>{user?.role?.label}</span>
                </div>
                <Link
                  href={route('logout')}
                  method="post"
                  as="button"
                  className="text-xs text-rose-400 font-bold hover:underline"
                >
                  Logout
                </Link>
              </div>
            </div>
          </div>
        )}

        {/* GLOBAL FLASH MESSAGES */}
        {flash?.success && (
          <div className="w-full px-4 sm:px-6 lg:px-8 mt-4 no-print">
            <div className="bg-emerald-50 dark:bg-emerald-950/40 border border-emerald-200 dark:border-emerald-800 text-emerald-800 dark:text-emerald-200 px-4 py-3 rounded-2xl flex items-center space-x-3 shadow-2xs">
              <CheckCircle2 className="w-5 h-5 text-emerald-600 dark:text-emerald-400 flex-shrink-0" />
              <span className="text-sm font-medium">{flash.success}</span>
            </div>
          </div>
        )}

        {flash?.error && (
          <div className="w-full px-4 sm:px-6 lg:px-8 mt-4 no-print">
            <div className="bg-rose-50 dark:bg-rose-950/40 border border-rose-200 dark:border-rose-800 text-rose-800 dark:text-rose-200 px-4 py-3 rounded-2xl flex items-center space-x-3 shadow-2xs">
              <AlertCircle className="w-5 h-5 text-rose-600 dark:text-rose-400 flex-shrink-0" />
              <span className="text-sm font-medium">{flash.error}</span>
            </div>
          </div>
        )}

        {/* MAIN PAGE CONTENT */}
        <main className="flex-1 w-full px-4 sm:px-6 lg:px-8 py-6">
          {children}
        </main>

        {/* Global Footer */}
        <footer className="w-full text-center py-4 mt-auto border-t border-slate-200 dark:border-slate-800 flex flex-col sm:flex-row items-center justify-center space-y-1 sm:space-y-0 sm:space-x-2 no-print bg-white/50 dark:bg-slate-950/50 backdrop-blur-sm">
          <span className="text-[11px] font-semibold text-slate-400 italic flex items-center justify-center">
            Baked with <Heart className="w-3 h-3 text-[#FF0D8F] fill-[#FF0D8F] mx-1" /> by Wspl Hosting Solution (OPC) Private Limited
          </span>
          <span className="hidden sm:inline text-slate-300 dark:text-slate-700">|</span>
          <span className="text-[11px] font-semibold text-slate-400 italic">
            {import.meta.env.VITE_APP_VERSION || 'v1.0.0'}
          </span>
        </footer>
      </div>
    </div>
  );
}


