import React, { useState, useEffect } from 'react';
import { NavLink, useLocation, useNavigate } from 'react-router-dom';
import { 
  LayoutDashboard, Users, UserCircle, Bell, Search, Menu, X, LogOut, 
  Hexagon, Settings, Building2, Sun, Moon, Loader2, Layers,
  ChevronLeft, ChevronRight
} from 'lucide-react';
import { 
  getAttendances, getUsers, getUserById, logout, searchGlobal, 
  getNotifications, markNotificationAsRead, markAllNotificationsAsRead,
  deleteNotification, clearAllNotifications, returnToSuperAdmin
} from '../services/dataService';
import { User } from '../types';

const SidebarItem = ({ to, icon: Icon, label, collapsed }: { to: string, icon: any, label: string, collapsed: boolean }) => (
  <NavLink
    to={to}
    className={({ isActive }) =>
      `flex items-center gap-3 px-4 py-3 rounded-xl transition-all duration-200 group ${
        isActive
          ? 'bg-brand-yellow text-zinc-950 font-semibold shadow-md shadow-brand-yellow/20'
          : 'text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border hover:text-zinc-900 dark:hover:text-dark-text'
      }`
    }
  >
    <Icon size={20} className="shrink-0" />
    {!collapsed && <span>{label}</span>}
  </NavLink>
);

export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(() => {
    return localStorage.getItem('ctms_sidebar_collapsed') === 'true';
  });
  const [isDark, setIsDark] = useState(document.documentElement.classList.contains('dark'));
  const location = useLocation();
  const navigate = useNavigate();
  const [currentUser, setCurrentUser] = useState<User | null>(null);

  const toggleSidebar = () => {
    const newState = !isSidebarCollapsed;
    setIsSidebarCollapsed(newState);
    localStorage.setItem('ctms_sidebar_collapsed', String(newState));
  };

  // Search State
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<{ members: User[], teams: any[], attendances: any[], organizations?: any[] }>({ members: [], teams: [], attendances: [], organizations: [] });
  const [isSearching, setIsSearching] = useState(false);
  const [showSearchResults, setShowSearchResults] = useState(false);

  // Notifications State
  const [notifications, setNotifications] = useState<any[]>([]);
  const [showNotifications, setShowNotifications] = useState(false);
  const unreadCount = notifications.filter(n => !n.is_read).length;
  const previousUnreadCountRef = React.useRef(0);
  const isInitialLoadRef = React.useRef(true);
  
  // Pre-initialize audio to ensure it's loaded and ready
  const audioRef = React.useRef<HTMLAudioElement | null>(null);

  const playNotificationSound = () => {
    if (currentUser?.sound_enabled !== false && audioRef.current) {
      // Reset time to 0 to allow rapid replays
      audioRef.current.currentTime = 0;
      const playPromise = audioRef.current.play();
      if (playPromise !== undefined) {
        playPromise.catch(e => console.log('Audio play blocked by browser policy:', e));
      }
    }
  };

  const loadNotifications = async () => {
    const data = await getNotifications();
    
    const newUnreadCount = data.filter((n: any) => !n.is_read).length;
    
    // Only play sound if it's NOT the first load AND the count actually increased
    if (!isInitialLoadRef.current && newUnreadCount > previousUnreadCountRef.current) {
      playNotificationSound();
    }
    
    setNotifications(data);
    previousUnreadCountRef.current = newUnreadCount;
    isInitialLoadRef.current = false;
  };

  const handleBellClick = async () => {
    const willOpen = !showNotifications;
    setShowNotifications(willOpen);
    
    if (willOpen && unreadCount > 0) {
      // Optimistic update
      setNotifications(prev => prev.map(n => ({ ...n, is_read: true })));
      previousUnreadCountRef.current = 0;
      await markAllNotificationsAsRead();
      loadNotifications();
    }
  };

  useEffect(() => {
    const delayDebounceFn = setTimeout(async () => {
      if (searchQuery.length >= 2) {
        setIsSearching(true);
        const results = await searchGlobal(searchQuery);
        setSearchResults(results);
        setIsSearching(false);
        setShowSearchResults(true);
      } else {
        setSearchResults({ members: [], teams: [], attendances: [], organizations: [] });
        setShowSearchResults(false);
      }
    }, 300);

    return () => clearTimeout(delayDebounceFn);
  }, [searchQuery]);

  const getSearchPlaceholder = () => {
    if (currentUser?.role === 'super_admin') return 'Buscar membros, equipes, atendimentos ou organizações...';
    if (currentUser?.role === 'agent') return 'Buscar atendimentos...';
    return 'Buscar membros, equipes ou atendimentos...';
  };

  useEffect(() => {
    const fetchCurrentUser = async () => {
      const storedUserId = localStorage.getItem('ctms_user_id');
      if (!storedUserId) {
        navigate('/login');
        return;
      }

      try {
        const user = await getUserById(storedUserId);
        if (user) {
          setCurrentUser(user);
        } else {
          navigate('/login');
        }
      } catch (err) {
        console.error("Layout fetch failed:", err);
      }
    };
    fetchCurrentUser();
    loadNotifications();
    const interval = setInterval(loadNotifications, 10000);
    return () => clearInterval(interval);
  }, [navigate]);

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  const toggleDarkMode = () => {
    const newDark = !isDark;
    setIsDark(newDark);
    if (newDark) {
      document.documentElement.classList.add('dark');
      document.cookie = "dark_mode=1; path=/; max-age=31536000";
    } else {
      document.documentElement.classList.remove('dark');
      document.cookie = "dark_mode=0; path=/; max-age=31536000";
    }
  };

  // Simple title mapping based on route
  const getPageTitle = () => {
    if (location.pathname === '/') return 'Dashboard';
    if (location.pathname.includes('/admin/users')) return 'Membros';
    if (location.pathname.includes('/admin/teams')) return 'Times';
    if (location.pathname.includes('/users/')) return 'Histórico do Usuário';
    if (location.pathname.includes('/attendances')) return 'Detalhes do Atendimento';
    if (location.pathname.includes('/super-admin')) return 'Gestão de Organizações';
    if (location.pathname.includes('/profile')) return 'Meu Perfil';
    return 'CTMS';
  };

  if (!currentUser) return null;

  const isSuperAdmin = currentUser.role === 'super_admin';

  return (
    <div className="flex h-screen bg-zinc-50 dark:bg-dark-bg overflow-hidden transition-colors duration-300">
      {/* Sidebar */}
      <aside
        className={`fixed inset-y-0 left-0 z-50 bg-white dark:bg-dark-sidebar border-r border-zinc-200 dark:border-dark-border transform transition-all duration-300 ease-in-out lg:relative lg:translate-x-0 ${
          isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full'
        } flex flex-col ${isSidebarCollapsed ? 'w-20' : 'w-64'}`}
      >
        {/* Logo & Toggle */}
        <div className="flex items-center justify-between px-4 h-20 border-b border-zinc-100 dark:border-dark-border shrink-0">
          <div className={`flex items-center gap-3 overflow-hidden ${isSidebarCollapsed ? 'mx-auto' : ''}`}>
            <div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors shrink-0">
              <Hexagon size={24} fill="currentColor" />
            </div>
            {!isSidebarCollapsed && (
              <span className="text-xl font-bold text-zinc-900 dark:text-white tracking-tight whitespace-nowrap">Fasto<span className="text-brand-yellow">.</span></span>
            )}
          </div>
          
          {!isSidebarCollapsed && (
            <button 
              onClick={toggleSidebar} 
              className="hidden lg:flex p-1.5 text-zinc-400 hover:bg-zinc-100 dark:hover:bg-dark-border rounded-lg transition-colors shrink-0"
              title="Recolher Menu"
            >
              <ChevronLeft size={18} />
            </button>
          )}
          <button onClick={() => setIsMobileMenuOpen(false)} className="lg:hidden text-zinc-400 hover:text-zinc-900 dark:hover:text-white">
            <X size={24} />
          </button>
        </div>

        {/* Expand Button when collapsed */}
        {isSidebarCollapsed && (
            <div className="hidden lg:flex justify-center p-2 border-b border-zinc-100 dark:border-dark-border shrink-0">
              <button 
                onClick={toggleSidebar} 
                className="p-1.5 text-zinc-400 hover:bg-zinc-100 dark:hover:bg-dark-border rounded-lg transition-colors"
                title="Expandir Menu"
              >
                <ChevronRight size={18} />
              </button>
            </div>
        )}

        {/* Navigation */}
        <nav className={`flex-1 py-6 space-y-2 overflow-y-auto overflow-x-hidden ${isSidebarCollapsed ? 'px-2' : 'px-4'}`}>
          
          {/* Standard User Links */}
          {!isSuperAdmin && (
            <>
              <SidebarItem to="/" icon={LayoutDashboard} label="Dashboard" collapsed={isSidebarCollapsed} />
              {currentUser.role !== 'agent' && (
                <>
                  <SidebarItem to="/admin/users" icon={Users} label="Membros" collapsed={isSidebarCollapsed} />
                  <SidebarItem to="/admin/teams" icon={Building2} label={currentUser.role === 'manager' ? 'Meu Time' : 'Times'} collapsed={isSidebarCollapsed} />
                  <SidebarItem to="/admin/funnels" icon={Layers} label="Gerenciar Funis" collapsed={isSidebarCollapsed} />
                </>
              )}
            </>
          )}

          {/* Super Admin Links */}
          {isSuperAdmin && (
            <>
              {!isSidebarCollapsed && (
                <div className="pt-2 pb-2 px-4 text-[10px] font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-widest whitespace-nowrap">
                    Super Admin
                </div>
              )}
              <SidebarItem to="/super-admin" icon={Building2} label="Organizações" collapsed={isSidebarCollapsed} />
              <SidebarItem to="/admin/users" icon={Users} label="Usuários Globais" collapsed={isSidebarCollapsed} />
            </>
          )}
        </nav>

        {/* User Profile Mini - Now Clickable to Profile */}
        <div className="p-3 border-t border-zinc-100 dark:border-dark-border space-y-3 shrink-0">
          {localStorage.getItem('ctms_super_admin_token') && (
            <button
              onClick={() => {
                returnToSuperAdmin();
              }}
              className={`w-full flex items-center justify-center gap-2 py-2 px-3 bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 rounded-lg text-xs font-bold hover:opacity-90 transition-colors ${isSidebarCollapsed ? 'px-0' : ''}`}
              title="Retornar ao Painel Central"
            >
              {isSidebarCollapsed ? <LogOut size={16} /> : 'Retornar ao Painel Central'}
            </button>
          )}
          <div className={`flex items-center gap-3 rounded-xl bg-zinc-50 dark:bg-dark-bg/50 border border-zinc-100 dark:border-dark-border group transition-all ${isSidebarCollapsed ? 'justify-center p-2' : 'p-2'}`}>
            <div 
              onClick={() => navigate('/profile')}
              className={`flex items-center gap-3 flex-1 min-w-0 cursor-pointer hover:opacity-80 transition-opacity ${isSidebarCollapsed ? 'justify-center' : ''}`}
              title={isSidebarCollapsed ? currentUser.name : undefined}
            >
              <img 
                src={currentUser.avatar_url 
                  ? (currentUser.avatar_url.startsWith('http') ? currentUser.avatar_url : `${import.meta.env.PROD ? '' : 'http://localhost:3001'}${currentUser.avatar_url}`)
                  : `https://ui-avatars.com/api/?name=${encodeURIComponent(currentUser.name)}&background=random`} 
                alt={currentUser.name} 
                className="w-10 h-10 rounded-full object-cover border border-zinc-200 dark:border-dark-border shrink-0" 
              />
              {!isSidebarCollapsed && (
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-semibold text-zinc-900 dark:text-dark-text truncate">{currentUser.name}</p>
                  <p className="text-xs text-zinc-500 dark:text-dark-muted truncate capitalize">
                    {currentUser.role === 'super_admin' ? 'Super Admin' : 
                      currentUser.role === 'admin' ? 'Administrador' :
                      currentUser.role === 'manager' ? 'Gerente' : 'Agente'}
                  </p>
                </div>
              )}
            </div>
            {!isSidebarCollapsed && (
              <button 
                onClick={handleLogout}
                className="text-zinc-400 hover:text-red-500 transition-colors shrink-0 p-2"
                title="Sair"
              >
                <LogOut size={18} />
              </button>
            )}
          </div>
        </div>
      </aside>

      {/* Main Content */}
      <div className="flex-1 flex flex-col min-w-0">
        {/* Header */}
        <header className="h-20 bg-white dark:bg-dark-header border-b border-zinc-200 dark:border-dark-border px-4 sm:px-8 flex items-center gap-4 sm:gap-8 z-10 sticky top-0 transition-colors">
          <div className="flex items-center gap-4 shrink-0">
            <button onClick={() => setIsMobileMenuOpen(true)} className="lg:hidden text-zinc-500 hover:text-zinc-900 dark:hover:text-white">
              <Menu size={24} />
            </button>
          </div>

          {/* Search Bar - Moved to left/center and made wider */}
          <div className="hidden md:block relative flex-1 max-w-2xl">
            <div className="flex items-center bg-zinc-100 dark:bg-dark-bg rounded-xl px-4 py-2.5 w-full border border-transparent focus-within:bg-white dark:focus-within:bg-dark-card focus-within:border-brand-yellow focus-within:ring-2 focus-within:ring-brand-yellow/20 dark:focus-within:ring-brand-yellow/10 transition-all">
              {isSearching ? <Loader2 size={18} className="text-brand-yellow animate-spin" /> : <Search size={18} className="text-zinc-400 dark:text-dark-muted" />}
              <input 
                type="text" 
                placeholder={getSearchPlaceholder()} 
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onFocus={() => searchQuery.length >= 2 && setShowSearchResults(true)}
                className="bg-transparent border-none outline-none text-sm ml-3 w-full text-zinc-700 dark:text-dark-text placeholder-zinc-400 dark:placeholder-dark-muted" 
              />
            </div>

            {/* Search Results Dropdown */}
            {showSearchResults && (
              <div className="absolute top-full mt-2 left-0 w-full bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl shadow-2xl overflow-hidden z-50 animate-in fade-in slide-in-from-top-2 duration-200">
                <div className="max-h-[480px] overflow-y-auto p-2">
                  {/* Organizations Section (Super Admin only) */}
                  {searchResults.organizations && searchResults.organizations.length > 0 && (
                    <div className="mb-4">
                      <div className="px-3 py-2 text-[10px] font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-widest border-b border-zinc-50 dark:border-dark-border/50 mb-1">Organizações</div>
                      {searchResults.organizations.map(o => (
                        <button
                          key={o.id}
                          onClick={() => {
                            navigate(`/super-admin`);
                            setShowSearchResults(false);
                            setSearchQuery('');
                          }}
                          className="w-full flex items-center gap-3 p-2 hover:bg-zinc-50 dark:hover:bg-dark-border rounded-xl transition-colors text-left"
                        >
                          <div className="w-9 h-9 rounded-lg bg-zinc-100 dark:bg-dark-bg flex items-center justify-center text-brand-yellow border border-zinc-200 dark:border-dark-border">
                            <Hexagon size={18} fill="currentColor" />
                          </div>
                          <div>
                            <div className="text-sm font-semibold text-zinc-900 dark:text-dark-text">{o.name}</div>
                            <div className="text-xs text-zinc-500 dark:text-dark-muted">{o.slug} • {o.status}</div>
                          </div>
                        </button>
                      ))}
                    </div>
                  )}

                  {/* Members Section */}
                  {searchResults.members.length > 0 && (
                    <div className="mb-4">
                      <div className="px-3 py-2 text-[10px] font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-widest border-b border-zinc-50 dark:border-dark-border/50 mb-1">Membros</div>
                      {searchResults.members.map(m => {
                        const backendUrl = import.meta.env.PROD ? '' : 'http://localhost:3001';
                        const avatarSrc = m.avatar_url 
                          ? (m.avatar_url.startsWith('http') ? m.avatar_url : `${backendUrl}${m.avatar_url}`)
                          : `https://ui-avatars.com/api/?name=${encodeURIComponent(m.name)}&background=random`;

                        return (
                          <button
                            key={m.id}
                            onClick={() => {
                              navigate(`/users/${m.slug || m.id}`);
                              setShowSearchResults(false);
                              setSearchQuery('');
                            }}
                            className="w-full flex items-center gap-3 p-2 hover:bg-zinc-50 dark:hover:bg-dark-border rounded-xl transition-colors text-left"
                          >
                            <img 
                              src={avatarSrc} 
                              alt={m.name} 
                              className="w-9 h-9 rounded-full border border-zinc-100 dark:border-dark-border object-cover"
                              onError={(e) => { (e.target as HTMLImageElement).src = `https://ui-avatars.com/api/?name=${encodeURIComponent(m.name)}&background=random`; }}
                            />
                            <div>
                              <div className="text-sm font-semibold text-zinc-900 dark:text-dark-text">{m.name}</div>
                              <div className="text-xs text-zinc-500 dark:text-dark-muted">{m.email}</div>
                            </div>
                          </button>
                        );
                      })}
                    </div>
                  )}

                  {/* Teams Section */}
                  {searchResults.teams.length > 0 && (
                    <div className="mb-4">
                      <div className="px-3 py-2 text-[10px] font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-widest border-b border-zinc-50 dark:border-dark-border/50 mb-1">Equipes</div>
                      {searchResults.teams.map(t => (
                        <button
                          key={t.id}
                          onClick={() => {
                            navigate(`/admin/teams`);
                            setShowSearchResults(false);
                            setSearchQuery('');
                          }}
                          className="w-full flex items-center gap-3 p-2 hover:bg-zinc-50 dark:hover:bg-dark-border rounded-xl transition-colors text-left"
                        >
                          <div className="w-9 h-9 rounded-lg bg-zinc-100 dark:bg-dark-bg flex items-center justify-center text-zinc-500 dark:text-dark-muted border border-zinc-200 dark:border-dark-border">
                            <Building2 size={18} />
                          </div>
                          <div>
                            <div className="text-sm font-semibold text-zinc-900 dark:text-dark-text">{t.name}</div>
                            <div className="text-xs text-zinc-500 dark:text-dark-muted line-clamp-1">{t.description || 'Sem descrição'}</div>
                          </div>
                        </button>
                      ))}
                    </div>
                  )}

                  {/* Attendances Section */}
                  {searchResults.attendances.length > 0 && (
                    <div className="mb-2">
                      <div className="px-3 py-2 text-[10px] font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-widest border-b border-zinc-50 dark:border-dark-border/50 mb-1">Atendimentos</div>
                      {searchResults.attendances.map(a => (
                        <button
                          key={a.id}
                          onClick={() => {
                            navigate(`/attendances/${a.id}`);
                            setShowSearchResults(false);
                            setSearchQuery('');
                          }}
                          className="w-full flex items-center gap-3 p-2 hover:bg-zinc-50 dark:hover:bg-dark-border rounded-xl transition-colors text-left"
                        >
                          <div className="w-9 h-9 rounded-lg bg-zinc-100 dark:bg-dark-bg flex items-center justify-center text-zinc-500 dark:text-dark-muted text-[10px] font-bold border border-zinc-200 dark:border-dark-border">
                            KPI
                          </div>
                          <div className="flex-1 min-w-0">
                            <div className="text-sm font-semibold text-zinc-900 dark:text-dark-text truncate">{a.summary}</div>
                            <div className="text-[10px] text-zinc-500 dark:text-dark-muted flex justify-between mt-0.5">
                              <span className="font-medium">{a.user_name}</span>
                              <span>{new Date(a.created_at).toLocaleDateString()}</span>
                            </div>
                          </div>
                        </button>
                      ))}
                    </div>
                  )}

                  {searchResults.members.length === 0 && searchResults.teams.length === 0 && searchResults.attendances.length === 0 && (!searchResults.organizations || searchResults.organizations.length === 0) && (
                    <div className="p-8 text-center text-zinc-500 dark:text-dark-muted text-sm">
                      Nenhum resultado encontrado para "{searchQuery}"
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>

          <div className="flex items-center gap-4 sm:gap-6 ml-auto shrink-0">
            {/* Dark Mode Toggle */}
            <button 
              onClick={toggleDarkMode}
              className="p-2.5 text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border rounded-xl transition-all"
              title={isDark ? "Mudar para Modo Claro" : "Mudar para Modo Escuro"}
            >
              {isDark ? <Sun size={20} /> : <Moon size={20} />}
            </button>

            {/* Notifications */}
            <div className="relative">
              <button
                onClick={handleBellClick}
                className="p-2 text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border rounded-full relative transition-colors"
              >                <Bell size={20} />
                {unreadCount > 0 && (
                  <span className="absolute top-1.5 right-2 w-2.5 h-2.5 bg-brand-yellow rounded-full border-2 border-white dark:border-dark-header"></span>
                )}
              </button>

              {showNotifications && (
                <div className="absolute top-full mt-2 right-0 w-80 bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl shadow-2xl overflow-hidden z-50 animate-in fade-in slide-in-from-top-2 duration-200">
                  <div className="p-4 border-b border-zinc-100 dark:border-dark-border flex justify-between items-center bg-zinc-50/50 dark:bg-dark-bg/50">
                    <h3 className="font-bold text-zinc-900 dark:text-dark-text">Notificações</h3>
                    <div className="flex gap-3">
                      {unreadCount > 0 && (
                        <button 
                          onClick={async (e) => {
                            e.stopPropagation();
                            await markAllNotificationsAsRead();
                            loadNotifications();
                          }}
                          className="text-xs text-brand-yellow hover:underline"
                        >
                          Marcar lidas
                        </button>
                      )}
                      {notifications.length > 0 && (
                        <button 
                          onClick={async (e) => {
                            e.stopPropagation();
                            await clearAllNotifications();
                            loadNotifications();
                          }}
                          className="text-xs text-zinc-400 hover:text-red-500 hover:underline transition-colors"
                        >
                          Limpar tudo
                        </button>
                      )}
                    </div>
                  </div>
                  <div className="max-h-96 overflow-y-auto">
                    {notifications.length > 0 ? (
                      notifications.map(n => (
                        <div
                          key={n.id}
                          className={`w-full relative group p-4 text-left hover:bg-zinc-50 dark:hover:bg-dark-border transition-colors border-b border-zinc-50 dark:border-dark-border/50 last:border-0 ${!n.is_read ? 'bg-brand-yellow/5 dark:bg-brand-yellow/5' : ''}`}
                        >
                          <div 
                            className="cursor-pointer pr-6" 
                            onClick={async () => {
                              if (!n.is_read) await markNotificationAsRead(n.id);
                              if (n.link) navigate(n.link);
                              setShowNotifications(false);
                              loadNotifications();
                            }}
                          >
                            <div className="flex justify-between items-start mb-1">
                              <span className={`text-xs font-bold uppercase tracking-wider ${
                                n.type === 'success' ? 'text-green-500' : 
                                n.type === 'warning' ? 'text-orange-500' : 
                                n.type === 'error' ? 'text-red-500' : 'text-blue-500'
                              }`}>
                                {n.type === 'success' ? 'SUCESSO' : n.type === 'warning' ? 'AVISO' : n.type === 'error' ? 'ERRO' : 'INFO'}
                              </span>
                              <span className="text-[10px] text-zinc-400 dark:text-dark-muted">
                                {new Date(n.created_at).toLocaleDateString()}
                              </span>
                            </div>
                            <div className="text-sm font-bold text-zinc-900 dark:text-dark-text mb-0.5">{n.title}</div>
                            <p className="text-xs text-zinc-500 dark:text-dark-muted line-clamp-2">{n.message}</p>
                          </div>
                          
                          {/* Delete Button */}
                          <button
                            onClick={async (e) => {
                              e.stopPropagation();
                              await deleteNotification(n.id);
                              loadNotifications();
                            }}
                            className="absolute top-4 right-4 p-1 text-zinc-300 hover:text-red-500 transition-all rounded-md hover:bg-red-50 dark:hover:bg-red-900/30"
                            title="Remover notificação"
                          >
                            <X size={14} />
                          </button>
                        </div>
                      ))
                    ) : (
                      <div className="p-8 text-center text-zinc-500 dark:text-dark-muted text-sm">
                        Nenhuma notificação por enquanto.
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>

            {/* Close notifications when clicking outside */}
            {showNotifications && <div className="fixed inset-0 z-40" onClick={() => setShowNotifications(false)} />}
          </div>
        </header>

        {/* Scrollable Content Area */}
        <main className="flex-1 overflow-y-auto p-4 sm:p-8">
          {children}
        </main>
      </div>
      
      {/* Overlay for mobile */}
      {isMobileMenuOpen && (
        <div
          className="fixed inset-0 bg-zinc-950/50 z-40 lg:hidden"
          onClick={() => setIsMobileMenuOpen(false)}
        />
      )}

      {/* Hidden Audio Player for Notifications */}
      <audio 
        ref={audioRef} 
        src={`${import.meta.env.PROD ? '' : 'http://localhost:3001'}/audio/notification.mp3`} 
        preload="auto" 
      />
    </div>
  );
};
