"use client";

import { useEffect, useState, Fragment } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import dynamic from 'next/dynamic';
import { Menu, Transition } from '@headlessui/react';
import {
    Bars3Icon,
    XMarkIcon,
    MagnifyingGlassIcon,
    BellIcon,
    Cog6ToothIcon,
    UserCircleIcon,
    ArrowRightOnRectangleIcon,
    ChevronDownIcon,
    ChevronRightIcon,
    UserGroupIcon,
    BuildingOfficeIcon,
    FolderIcon,
    CreditCardIcon,
    DocumentTextIcon,
    LifebuoyIcon,
    DocumentCheckIcon,
    UsersIcon,
    UserPlusIcon,
    PhoneIcon,
    FunnelIcon,
    ChartBarIcon,
    HomeIcon,
    CubeIcon,
    ShoppingCartIcon,
    BanknotesIcon,
    DocumentDuplicateIcon,
    ShareIcon,
    DocumentMagnifyingGlassIcon,
    TrashIcon,
    RectangleStackIcon,
    CalendarIcon,
    UserGroupIcon as TeamIcon,
    ReceiptPercentIcon,
    CreditCardIcon as PaymentIcon,
    ChatBubbleLeftRightIcon,
    BookOpenIcon,
    ArchiveBoxIcon,
    PencilSquareIcon,
} from '@heroicons/react/24/outline';

const ThemeToggle = dynamic(() => import('@/components/ThemeToggle'), { ssr: false });
const ThemeTester = dynamic(() => import('@/components/ThemeTester'), { ssr: false });
const DynamicFavicon = dynamic(() => import('@/components/DynamicFavicon'), { ssr: false });

const DEFAULT_GRADIENT = 'linear-gradient(135deg, #ff3a05, #ff0080)';

const setGradientVariables = (gradient: string) => {
    document.documentElement.style.setProperty('--gradient-primary', gradient);
    document.documentElement.style.setProperty('--gradient', gradient);
    document.documentElement.style.setProperty('--gradient-text', gradient.replace('90deg', 'to right'));
    document.documentElement.style.setProperty('--color-gradient-brand', gradient.replace('90deg', 'to right'));
};

export default function AgencyLayout({
    children,
}: {
    children: React.ReactNode;
}) {
    const router = useRouter();
    const pathname = usePathname();
    const [user, setUser] = useState<any>(null);
    const [agencyName, setAgencyName] = useState('');
    const [agencyLogo, setAgencyLogo] = useState('');
    const [sidebarOpen, setSidebarOpen] = useState(true);
    const [searchOpen, setSearchOpen] = useState(false);
    const [activeSubmenu, setActiveSubmenu] = useState<number | null>(null);
    const [selectedClient, setSelectedClient] = useState<any>(null);

    // Mock de clientes - no futuro virá da API
    const clients = [
        { id: 1, name: 'Todos os Clientes', avatar: null },
        { id: 2, name: 'Empresa ABC Ltda', avatar: 'A' },
        { id: 3, name: 'Tech Solutions Inc', avatar: 'T' },
        { id: 4, name: 'Marketing Pro', avatar: 'M' },
        { id: 5, name: 'Design Studio', avatar: 'D' },
    ];

    useEffect(() => {
        const token = localStorage.getItem('token');
        const userData = localStorage.getItem('user');

        if (!token || !userData) {
            router.push('/login');
            return;
        }
        const parsedUser = JSON.parse(userData);
        setUser(parsedUser);

        if (parsedUser.role === 'SUPERADMIN') {
            router.push('/superadmin');
            return;
        }

        const hostname = window.location.hostname;
        const hostSubdomain = hostname.split('.')[0] || 'default';
        const themeKey = parsedUser?.subdomain || parsedUser?.tenantId || parsedUser?.tenant_id || hostSubdomain;

        setAgencyName(parsedUser?.subdomain || hostSubdomain);

        // Buscar logo da agência
        const fetchAgencyLogo = async () => {
            try {
                const response = await fetch('/api/agency/profile', {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json',
                    },
                });

                if (response.ok) {
                    const data = await response.json();
                    if (data.logo_url) {
                        setAgencyLogo(data.logo_url);
                    }
                }
            } catch (error) {
                console.error('Erro ao buscar logo da agência:', error);
            }
        };

        fetchAgencyLogo();

        const storedGradient = localStorage.getItem(`agency-theme:${themeKey}`);
        setGradientVariables(storedGradient || DEFAULT_GRADIENT);

        // Inicializar com "Todos os Clientes"
        setSelectedClient(clients[0]);

        // Atalho de teclado para abrir pesquisa (Ctrl/Cmd + K)
        const handleKeyDown = (e: KeyboardEvent) => {
            if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                e.preventDefault();
                setSearchOpen(true);
            }
            if (e.key === 'Escape') {
                setSearchOpen(false);
            }
        };

        window.addEventListener('keydown', handleKeyDown);
        return () => {
            window.removeEventListener('keydown', handleKeyDown);
            setGradientVariables(DEFAULT_GRADIENT);
        };
    }, [router]);

    useEffect(() => {
        const hostname = window.location.hostname;
        const hostSubdomain = hostname.split('.')[0] || 'default';
        const userData = localStorage.getItem('user');
        const parsedUser = userData ? JSON.parse(userData) : null;
        const themeKey = parsedUser?.subdomain || parsedUser?.tenantId || parsedUser?.tenant_id || hostSubdomain;
        const storedGradient = localStorage.getItem(`agency-theme:${themeKey}`) || DEFAULT_GRADIENT;

        setGradientVariables(storedGradient);
    }, [pathname]);

    if (!user) {
        return null;
    }

    const menuItems = [
        {
            icon: UserGroupIcon,
            label: 'CRM',
            href: '/crm',
            submenu: [
                { icon: UsersIcon, label: 'Clientes', href: '/crm/clientes' },
                { icon: UserPlusIcon, label: 'Leads', href: '/crm/leads' },
                { icon: PhoneIcon, label: 'Contatos', href: '/crm/contatos' },
                { icon: FunnelIcon, label: 'Funil de Vendas', href: '/crm/funil' },
                { icon: ChartBarIcon, label: 'Relatórios', href: '/crm/relatorios' },
            ]
        },
        {
            icon: BuildingOfficeIcon,
            label: 'ERP',
            href: '/erp',
            submenu: [
                { icon: HomeIcon, label: 'Dashboard', href: '/erp/dashboard' },
                { icon: CubeIcon, label: 'Estoque', href: '/erp/estoque' },
                { icon: ShoppingCartIcon, label: 'Compras', href: '/erp/compras' },
                { icon: BanknotesIcon, label: 'Vendas', href: '/erp/vendas' },
                { icon: ChartBarIcon, label: 'Financeiro', href: '/erp/financeiro' },
            ]
        },
        {
            icon: FolderIcon,
            label: 'Projetos',
            href: '/projetos',
            submenu: [
                { icon: RectangleStackIcon, label: 'Todos Projetos', href: '/projetos/todos' },
                { icon: RectangleStackIcon, label: 'Kanban', href: '/projetos/kanban' },
                { icon: CalendarIcon, label: 'Calendário', href: '/projetos/calendario' },
                { icon: TeamIcon, label: 'Equipes', href: '/projetos/equipes' },
            ]
        },
        {
            icon: CreditCardIcon,
            label: 'Pagamentos',
            href: '/pagamentos',
            submenu: [
                { icon: DocumentTextIcon, label: 'Faturas', href: '/pagamentos/faturas' },
                { icon: ReceiptPercentIcon, label: 'Recebimentos', href: '/pagamentos/recebimentos' },
                { icon: PaymentIcon, label: 'Assinaturas', href: '/pagamentos/assinaturas' },
                { icon: BanknotesIcon, label: 'Gateway', href: '/pagamentos/gateway' },
            ]
        },
        {
            icon: DocumentTextIcon,
            label: 'Documentos',
            href: '/documentos',
            submenu: [
                { icon: FolderIcon, label: 'Meus Arquivos', href: '/documentos/arquivos' },
                { icon: ShareIcon, label: 'Compartilhados', href: '/documentos/compartilhados' },
                { icon: DocumentDuplicateIcon, label: 'Modelos', href: '/documentos/modelos' },
                { icon: TrashIcon, label: 'Lixeira', href: '/documentos/lixeira' },
            ]
        },
        {
            icon: LifebuoyIcon,
            label: 'Suporte',
            href: '/suporte',
            submenu: [
                { icon: DocumentMagnifyingGlassIcon, label: 'Tickets', href: '/suporte/tickets' },
                { icon: BookOpenIcon, label: 'Base de Conhecimento', href: '/suporte/kb' },
                { icon: ChatBubbleLeftRightIcon, label: 'Chat', href: '/suporte/chat' },
            ]
        },
        {
            icon: DocumentCheckIcon,
            label: 'Contratos',
            href: '/contratos',
            submenu: [
                { icon: DocumentCheckIcon, label: 'Ativos', href: '/contratos/ativos' },
                { icon: PencilSquareIcon, label: 'Rascunhos', href: '/contratos/rascunhos' },
                { icon: ArchiveBoxIcon, label: 'Arquivados', href: '/contratos/arquivados' },
                { icon: DocumentDuplicateIcon, label: 'Modelos', href: '/contratos/modelos' },
            ]
        },
    ];

    const handleLogout = () => {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        router.push('/login');
    };

    return (
        <div className="flex h-screen bg-gray-50 dark:bg-gray-950">
            {/* Favicon Dinâmico */}
            <DynamicFavicon logoUrl={agencyLogo} />

            {/* Sidebar */}
            <aside className={`${activeSubmenu !== null ? 'w-20' : (sidebarOpen ? 'w-64' : 'w-20')} transition-all duration-300 bg-white dark:bg-gray-900 border-r border-gray-200 dark:border-gray-800 flex flex-col`}>
                {/* Logo */}
                <div className="h-16 flex items-center justify-center border-b border-gray-200 dark:border-gray-800">
                    {(sidebarOpen && activeSubmenu === null) ? (
                        <div className="flex items-center justify-between px-4 w-full">
                            <div className="flex items-center space-x-3">
                                {agencyLogo ? (
                                    <img src={agencyLogo} alt="Logo" className="w-8 h-8 rounded-lg object-contain shrink-0" />
                                ) : (
                                    <div className="w-8 h-8 rounded-lg shrink-0" style={{ background: 'var(--gradient-primary)' }}></div>
                                )}
                                <span className="font-bold text-lg dark:text-white capitalize">{agencyName}</span>
                            </div>
                            <button
                                onClick={() => setSidebarOpen(!sidebarOpen)}
                                className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors cursor-pointer"
                            >
                                <XMarkIcon className="w-4 h-4 text-gray-500 dark:text-gray-400" />
                            </button>
                        </div>
                    ) : (
                        <>
                            {agencyLogo ? (
                                <img src={agencyLogo} alt="Logo" className="w-8 h-8 rounded-lg object-contain" />
                            ) : (
                                <div className="w-8 h-8 rounded-lg" style={{ background: 'var(--gradient-primary)' }}></div>
                            )}
                        </>
                    )}
                </div>

                {/* Menu */}
                <nav className="flex-1 overflow-y-auto py-4 px-3">
                    {menuItems.map((item, idx) => {
                        const Icon = item.icon;
                        const isActive = activeSubmenu === idx;
                        return (
                            <button
                                key={idx}
                                onClick={() => setActiveSubmenu(isActive ? null : idx)}
                                className={`w-full flex items-center ${(sidebarOpen && activeSubmenu === null) ? 'space-x-3 px-3' : 'justify-center px-0'} py-2.5 mb-1 rounded-lg transition-all group cursor-pointer ${isActive
                                        ? 'bg-gray-900 dark:bg-gray-100 text-white dark:text-gray-900'
                                        : 'hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
                                    }`}
                            >
                                <Icon className={`${(sidebarOpen && activeSubmenu === null) ? 'w-5 h-5' : 'w-[18px] h-[18px]'} stroke-[1.5]`} />
                                {(sidebarOpen && activeSubmenu === null) && (
                                    <>
                                        <span className="flex-1 text-left text-sm font-normal">{item.label}</span>
                                        <ChevronRightIcon className={`w-4 h-4 transition-transform ${isActive ? 'rotate-90' : ''}`} />
                                    </>
                                )}
                            </button>
                        );
                    })}
                </nav>

                {/* User Menu */}
                <div className="p-4 border-t border-gray-200 dark:border-gray-800">
                    {(sidebarOpen && activeSubmenu === null) ? (
                        <Menu as="div" className="relative">
                            <Menu.Button className="w-full flex items-center space-x-3 p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-xl transition-colors">
                                <div className="w-10 h-10 rounded-full flex items-center justify-center text-white font-semibold" style={{ background: 'var(--gradient-primary)' }}>
                                    {user?.name?.charAt(0).toUpperCase()}
                                </div>
                                <div className="flex-1 text-left">
                                    <p className="text-sm font-medium text-gray-900 dark:text-white truncate">{user?.name}</p>
                                    <p className="text-xs text-gray-500 dark:text-gray-400">{user?.role === 'ADMIN_AGENCIA' ? 'Admin' : 'Cliente'}</p>
                                </div>
                                <ChevronDownIcon className="w-4 h-4 text-gray-400" />
                            </Menu.Button>
                            <Transition
                                as={Fragment}
                                enter="transition ease-out duration-100"
                                enterFrom="transform opacity-0 scale-95"
                                enterTo="transform opacity-100 scale-100"
                                leave="transition ease-in duration-75"
                                leaveFrom="transform opacity-100 scale-100"
                                leaveTo="transform opacity-0 scale-95"
                            >
                                <Menu.Items className="absolute bottom-full left-0 right-0 mb-2 bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
                                    <Menu.Item>
                                        {({ active }) => (
                                            <a
                                                href="/perfil"
                                                className={`${active ? 'bg-gray-100 dark:bg-gray-700' : ''} flex items-center px-4 py-3 text-sm text-gray-700 dark:text-gray-300`}
                                            >
                                                <UserCircleIcon className="w-5 h-5 mr-3" />
                                                Meu Perfil
                                            </a>
                                        )}
                                    </Menu.Item>
                                    <Menu.Item>
                                        {({ active }) => (
                                            <button
                                                onClick={handleLogout}
                                                className={`${active ? 'bg-gray-100 dark:bg-gray-700' : ''} w-full flex items-center px-4 py-3 text-sm text-red-600 dark:text-red-400`}
                                            >
                                                <ArrowRightOnRectangleIcon className="w-5 h-5 mr-3" />
                                                Sair
                                            </button>
                                        )}
                                    </Menu.Item>
                                </Menu.Items>
                            </Transition>
                        </Menu>
                    ) : (
                        <button
                            onClick={handleLogout}
                            className="w-10 h-10 mx-auto rounded-full flex items-center justify-center text-white cursor-pointer"
                            style={{ background: 'var(--gradient-primary)' }}
                            title="Sair"
                        >
                            <ArrowRightOnRectangleIcon className="w-5 h-5" />
                        </button>
                    )}
                </div>
            </aside>

            {/* Submenu Lateral */}
            <Transition
                show={activeSubmenu !== null}
                as={Fragment}
                enter="transition ease-out duration-200"
                enterFrom="transform -translate-x-full opacity-0"
                enterTo="transform translate-x-0 opacity-100"
                leave="transition ease-in duration-150"
                leaveFrom="transform translate-x-0 opacity-100"
                leaveTo="transform -translate-x-full opacity-0"
            >
                <aside className="w-64 bg-white dark:bg-gray-900 border-r border-gray-200 dark:border-gray-800 flex flex-col">
                    {activeSubmenu !== null && (
                        <>
                            <div className="h-16 flex items-center justify-between px-4 border-b border-gray-200 dark:border-gray-800">
                                <h2 className="font-semibold text-gray-900 dark:text-white">{menuItems[activeSubmenu].label}</h2>
                                <button
                                    onClick={() => setActiveSubmenu(null)}
                                    className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors cursor-pointer"
                                >
                                    <XMarkIcon className="w-4 h-4 text-gray-500 dark:text-gray-400" />
                                </button>
                            </div>
                            <nav className="flex-1 overflow-y-auto py-4 px-3">
                                {menuItems[activeSubmenu].submenu?.map((subItem, idx) => {
                                    const SubIcon = subItem.icon;
                                    return (
                                        <a
                                            key={idx}
                                            href={subItem.href}
                                            className="flex items-center space-x-3 px-4 py-2.5 mb-1 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 text-sm text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white transition-colors cursor-pointer"
                                        >
                                            <SubIcon className="w-5 h-5 stroke-[1.5]" />
                                            <span>{subItem.label}</span>
                                        </a>
                                    );
                                })}
                            </nav>
                        </>
                    )}
                </aside>
            </Transition>

            {/* Main Content */}
            <div className="flex-1 flex flex-col overflow-hidden">
                {/* Header */}
                <header className="h-16 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800 flex items-center justify-between px-6">
                    <div className="flex items-center space-x-4">
                        <h1 className="text-lg font-semibold text-gray-900 dark:text-white">
                            Dashboard
                        </h1>

                        {/* Seletor de Cliente */}
                        <Menu as="div" className="relative">
                            <Menu.Button className="flex items-center space-x-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors cursor-pointer">
                                {selectedClient?.avatar ? (
                                    <div className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-semibold" style={{ background: 'var(--gradient-primary)' }}>
                                        {selectedClient.avatar}
                                    </div>
                                ) : (
                                    <UsersIcon className="w-4 h-4 text-gray-600 dark:text-gray-400" />
                                )}
                                <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                    {selectedClient?.name || 'Selecionar Cliente'}
                                </span>
                                <ChevronDownIcon className="w-4 h-4 text-gray-500 dark:text-gray-400" />
                            </Menu.Button>
                            <Transition
                                as={Fragment}
                                enter="transition ease-out duration-100"
                                enterFrom="transform opacity-0 scale-95"
                                enterTo="transform opacity-100 scale-100"
                                leave="transition ease-in duration-75"
                                leaveFrom="transform opacity-100 scale-100"
                                leaveTo="transform opacity-0 scale-95"
                            >
                                <Menu.Items className="absolute left-0 mt-2 w-72 bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 overflow-hidden z-50">
                                    <div className="p-3 border-b border-gray-200 dark:border-gray-700">
                                        <div className="relative">
                                            <MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                                            <input
                                                type="text"
                                                placeholder="Buscar cliente..."
                                                className="w-full pl-9 pr-3 py-2 bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg text-sm text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-600"
                                            />
                                        </div>
                                    </div>
                                    <div className="max-h-64 overflow-y-auto p-2">
                                        {clients.map((client) => (
                                            <Menu.Item key={client.id}>
                                                {({ active }) => (
                                                    <button
                                                        onClick={() => setSelectedClient(client)}
                                                        className={`${active ? 'bg-gray-100 dark:bg-gray-700' : ''
                                                            } ${selectedClient?.id === client.id ? 'bg-gray-100 dark:bg-gray-800' : ''
                                                            } w-full flex items-center space-x-3 px-3 py-2.5 rounded-lg transition-colors cursor-pointer`}
                                                    >
                                                        {client.avatar ? (
                                                            <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-sm font-semibold shrink-0" style={{ background: 'var(--gradient-primary)' }}>
                                                                {client.avatar}
                                                            </div>
                                                        ) : (
                                                            <div className="w-8 h-8 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center shrink-0">
                                                                <UsersIcon className="w-4 h-4 text-gray-600 dark:text-gray-400" />
                                                            </div>
                                                        )}
                                                        <span className="flex-1 text-left text-sm font-medium text-gray-900 dark:text-white">
                                                            {client.name}
                                                        </span>
                                                        {selectedClient?.id === client.id && (
                                                            <div className="w-2 h-2 rounded-full bg-gray-900 dark:bg-gray-100"></div>
                                                        )}
                                                    </button>
                                                )}
                                            </Menu.Item>
                                        ))}
                                    </div>
                                </Menu.Items>
                            </Transition>
                        </Menu>
                    </div>

                    <div className="flex items-center space-x-2">
                        {/* Pesquisa */}
                        <button
                            onClick={() => setSearchOpen(true)}
                            className="flex items-center space-x-2 px-3 py-2 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
                        >
                            <MagnifyingGlassIcon className="w-4 h-4 text-gray-500 dark:text-gray-400" />
                            <span className="text-sm text-gray-500 dark:text-gray-400">Pesquisar...</span>
                            <kbd className="hidden sm:inline-flex items-center px-2 py-0.5 text-xs font-medium text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded">
                                Ctrl K
                            </kbd>
                        </button>

                        <ThemeToggle />

                        {/* Notificações */}
                        <Menu as="div" className="relative">
                            <Menu.Button className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg relative transition-colors">
                                <BellIcon className="w-5 h-5 text-gray-600 dark:text-gray-400" />
                                <span className="absolute top-1.5 right-1.5 w-2 h-2 bg-red-500 rounded-full"></span>
                            </Menu.Button>
                            <Transition
                                as={Fragment}
                                enter="transition ease-out duration-100"
                                enterFrom="transform opacity-0 scale-95"
                                enterTo="transform opacity-100 scale-100"
                                leave="transition ease-in duration-75"
                                leaveFrom="transform opacity-100 scale-100"
                                leaveTo="transform opacity-0 scale-95"
                            >
                                <Menu.Items className="absolute right-0 mt-2 w-80 bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
                                    <div className="p-4 border-b border-gray-200 dark:border-gray-700">
                                        <h3 className="font-semibold text-gray-900 dark:text-white">Notificações</h3>
                                    </div>
                                    <div className="p-4 text-center text-sm text-gray-500 dark:text-gray-400">
                                        Nenhuma notificação no momento
                                    </div>
                                </Menu.Items>
                            </Transition>
                        </Menu>

                        {/* Configurações */}
                        <a
                            href="/configuracoes"
                            className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
                        >
                            <Cog6ToothIcon className="w-5 h-5 text-gray-600 dark:text-gray-400" />
                        </a>
                    </div>
                </header>

                {/* Page Content */}
                <main className="flex-1 overflow-y-auto bg-gray-50 dark:bg-gray-950">
                    {children}
                </main>
            </div>

            {/* Modal de Pesquisa */}
            <Transition appear show={searchOpen} as={Fragment}>
                <div className="fixed inset-0 z-50 overflow-y-auto">
                    <Transition.Child
                        as={Fragment}
                        enter="ease-out duration-200"
                        enterFrom="opacity-0"
                        enterTo="opacity-100"
                        leave="ease-in duration-150"
                        leaveFrom="opacity-100"
                        leaveTo="opacity-0"
                    >
                        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm" onClick={() => setSearchOpen(false)} />
                    </Transition.Child>

                    <div className="flex min-h-full items-start justify-center p-4 pt-[15vh]">
                        <Transition.Child
                            as={Fragment}
                            enter="ease-out duration-200"
                            enterFrom="opacity-0 scale-95"
                            enterTo="opacity-100 scale-100"
                            leave="ease-in duration-150"
                            leaveFrom="opacity-100 scale-100"
                            leaveTo="opacity-0 scale-95"
                        >
                            <div className="w-full max-w-2xl bg-white dark:bg-gray-900 rounded-xl shadow-2xl border border-gray-200 dark:border-gray-800 overflow-hidden relative z-10">
                                <div className="flex items-center px-4 border-b border-gray-200 dark:border-gray-800">
                                    <MagnifyingGlassIcon className="w-5 h-5 text-gray-400" />
                                    <input
                                        type="text"
                                        placeholder="Pesquisar páginas, clientes, projetos..."
                                        autoFocus
                                        className="w-full px-4 py-4 bg-transparent text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none"
                                    />
                                    <button
                                        onClick={() => setSearchOpen(false)}
                                        className="text-xs text-gray-500 dark:text-gray-400 px-2 py-1 border border-gray-300 dark:border-gray-700 rounded"
                                    >
                                        ESC
                                    </button>
                                </div>

                                <div className="p-4 max-h-96 overflow-y-auto">
                                    <div className="text-center py-12">
                                        <MagnifyingGlassIcon className="w-12 h-12 text-gray-300 dark:text-gray-700 mx-auto mb-3" />
                                        <p className="text-sm text-gray-500 dark:text-gray-400">
                                            Digite para buscar...
                                        </p>
                                    </div>
                                </div>

                                <div className="px-4 py-3 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-950">
                                    <div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
                                        <div className="flex items-center space-x-4">
                                            <span className="flex items-center">
                                                <kbd className="px-2 py-1 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded mr-1">↑↓</kbd>
                                                navegar
                                            </span>
                                            <span className="flex items-center">
                                                <kbd className="px-2 py-1 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded mr-1">↵</kbd>
                                                selecionar
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </Transition.Child>
                    </div>
                </div>
            </Transition>

            {/* Theme Tester - Temporário para desenvolvimento */}
            <ThemeTester />
        </div>
    );
}
