<?php
// Obtener configuración de la app
use App\Services\Database;
$db = Database::getInstance();
$appSettings = $db->fetchOne("SELECT * FROM app_settings WHERE id = 1");
$appName = $appSettings['app_name'] ?? 'Sistema de Gestión de Proyectos';
$appLogo = $appSettings['app_logo'] ?? null;
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $title ?? $appName ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    <meta name="csrf-token" content="<?= $csrf_token ?? '' ?>">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: {
                            50: '#eff6ff',
                            500: '#3b82f6',
                            600: '#2563eb',
                            700: '#1d4ed8'
                        }
                    }
                }
            }
        }
    </script>
    
    <style>
        .sidebar-collapsed {
            width: 4rem;
        }
        .sidebar-collapsed .sidebar-text {
            display: none;
        }
        .sidebar-collapsed .sidebar-arrow {
            display: none;
        }
        .sidebar-expanded {
            width: 16rem;
        }
        .main-content-collapsed {
            margin-left: 4rem;
        }
        .main-content-expanded {
            margin-left: 16rem;
        }
        @media (max-width: 1024px) {
            .sidebar-collapsed,
            .sidebar-expanded {
                width: 16rem;
            }
            .main-content-collapsed,
            .main-content-expanded {
                margin-left: 0;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans">
    <div x-data="{ 
        sidebarOpen: false, 
        sidebarCollapsed: localStorage.getItem('sidebarCollapsed') === 'true',
        toggleSidebar() {
            this.sidebarOpen = !this.sidebarOpen;
        },
        toggleCollapse() {
            this.sidebarCollapsed = !this.sidebarCollapsed;
            localStorage.setItem('sidebarCollapsed', this.sidebarCollapsed);
        },
        init() {
            // Cerrar sidebar en móvil al hacer clic fuera
            this.$watch('sidebarOpen', (value) => {
                if (value) {
                    document.body.style.overflow = 'hidden';
                } else {
                    document.body.style.overflow = 'auto';
                }
            });
        }
    }" id="app">
        <?php if (isset($showSidebar) && $showSidebar): ?>
        
        <!-- Overlay para móvil -->
        <div x-show="sidebarOpen" 
             x-transition:enter="transition-opacity ease-linear duration-300"
             x-transition:enter-start="opacity-0"
             x-transition:enter-end="opacity-100"
             x-transition:leave="transition-opacity ease-linear duration-300"
             x-transition:leave-start="opacity-100"
             x-transition:leave-end="opacity-0"
             @click="sidebarOpen = false"
             class="fixed inset-0 z-40 bg-black bg-opacity-25 lg:hidden"></div>

        <!-- Sidebar -->
        <div class="fixed inset-y-0 left-0 z-50 bg-white shadow-xl transform transition-all duration-300 ease-in-out lg:translate-x-0"
             :class="{
                'translate-x-0': sidebarOpen,
                '-translate-x-full lg:translate-x-0': !sidebarOpen,
                'sidebar-collapsed': sidebarCollapsed && window.innerWidth >= 1024,
                'sidebar-expanded': !sidebarCollapsed || window.innerWidth < 1024
             }">
            
            <!-- Logo y botón de colapso -->
            <div class="flex items-center justify-between h-16 px-4" :class="{'px-1': sidebarCollapsed}">
                <div class="flex items-center">
                    <?php if ($appLogo): ?>
                    <img src="<?= htmlspecialchars($appLogo) ?>" alt="Logo" class="h-20 w-20 object-contain">
                    <?php else: ?>
                    <i class="fas fa-project-diagram text-white text-xl"></i>
                    <?php endif; ?>
                    <!-- <h1 class="sidebar-text text-white text-lg font-bold ml-3" x-show="!sidebarCollapsed || window.innerWidth < 1024">
                        <?= htmlspecialchars(substr($appName, 0, 20)) ?>
                    </h1> -->
                </div>
                
                <!-- Botón de colapso (solo desktop) -->
                <button @click="toggleCollapse()" 
                        class="hidden lg:block text-primary-700 hover:bg-gray-100 p-1 rounded transition-colors"
                        title="Contraer/Expandir">
                    <i class="fas fa-chevron-left transition-transform duration-300" 
                       :class="{'rotate-180': sidebarCollapsed}"></i>
                </button>
            </div>

            <!-- Navigation -->
            <nav class="mt-8 flex-1">
                <div class="px-4" x-show="!sidebarCollapsed || window.innerWidth < 1024">
                    <p class="sidebar-text text-xs font-semibold text-gray-400 uppercase tracking-wide mb-3">Principal</p>
                </div>

                <a href="/dashboard" 
                   class="flex items-center px-6 py-3 text-gray-700 hover:bg-primary-50 hover:text-primary-600 transition-colors group relative <?= ($current_page ?? '') === 'dashboard' ? 'bg-primary-50 text-primary-600 border-r-2 border-primary-600' : '' ?>"
                   :class="{'justify-center': sidebarCollapsed && window.innerWidth >= 1024}">
                    <i class="fas fa-tachometer-alt flex-shrink-0"></i>
                    <span class="sidebar-text ml-3" x-show="!sidebarCollapsed || window.innerWidth < 1024">Dashboard</span>
                    <!-- Tooltip para modo colapsado -->
                    <div x-show="sidebarCollapsed && window.innerWidth >= 1024" 
                         class="absolute left-full ml-2 px-2 py-1 bg-gray-800 text-white text-sm rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50">
                        Dashboard
                    </div>
                </a>

                <!-- Separador -->
                <div class="px-4 mt-6" x-show="!sidebarCollapsed || window.innerWidth < 1024">
                    <p class="sidebar-text text-xs font-semibold text-gray-400 uppercase tracking-wide mb-3">Administración</p>
                </div>

                <a href="/admin/users" 
                   class="flex items-center px-6 py-3 text-gray-700 hover:bg-primary-50 hover:text-primary-600 transition-colors group relative <?= ($current_page ?? '') === 'users' ? 'bg-primary-50 text-primary-600 border-r-2 border-primary-600' : '' ?>"
                   :class="{'justify-center': sidebarCollapsed && window.innerWidth >= 1024}">
                    <i class="fas fa-users flex-shrink-0"></i>
                    <span class="sidebar-text ml-3" x-show="!sidebarCollapsed || window.innerWidth < 1024">Usuarios</span>
                    <div x-show="sidebarCollapsed && window.innerWidth >= 1024" 
                         class="absolute left-full ml-2 px-2 py-1 bg-gray-800 text-white text-sm rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50">
                        Usuarios
                    </div>
                </a>

                <a href="/admin/roles" 
                   class="flex items-center px-6 py-3 text-gray-700 hover:bg-primary-50 hover:text-primary-600 transition-colors group relative <?= ($current_page ?? '') === 'roles' ? 'bg-primary-50 text-primary-600 border-r-2 border-primary-600' : '' ?>"
                   :class="{'justify-center': sidebarCollapsed && window.innerWidth >= 1024}">
                    <i class="fas fa-user-shield flex-shrink-0"></i>
                    <span class="sidebar-text ml-3" x-show="!sidebarCollapsed || window.innerWidth < 1024">Roles</span>
                    <div x-show="sidebarCollapsed && window.innerWidth >= 1024" 
                         class="absolute left-full ml-2 px-2 py-1 bg-gray-800 text-white text-sm rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50">
                        Roles
                    </div>
                </a>

                <a href="/admin/teams" 
                   class="flex items-center px-6 py-3 text-gray-700 hover:bg-primary-50 hover:text-primary-600 transition-colors group relative <?= ($current_page ?? '') === 'teams' ? 'bg-primary-50 text-primary-600 border-r-2 border-primary-600' : '' ?>"
                   :class="{'justify-center': sidebarCollapsed && window.innerWidth >= 1024}">
                    <i class="fas fa-people-group flex-shrink-0"></i>
                    <span class="sidebar-text ml-3" x-show="!sidebarCollapsed || window.innerWidth < 1024">Equipos</span>
                    <div x-show="sidebarCollapsed && window.innerWidth >= 1024" 
                         class="absolute left-full ml-2 px-2 py-1 bg-gray-800 text-white text-sm rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50">
                        Equipos
                    </div>
                </a>

                <!-- Separador -->
                <div class="px-4 mt-6" x-show="!sidebarCollapsed || window.innerWidth < 1024">
                    <p class="sidebar-text text-xs font-semibold text-gray-400 uppercase tracking-wide mb-3">Gestión</p>
                </div>

                <a href="/requirements" 
                   class="flex items-center px-6 py-3 text-gray-700 hover:bg-primary-50 hover:text-primary-600 transition-colors group relative <?= ($current_page ?? '') === 'requirements' ? 'bg-primary-50 text-primary-600 border-r-2 border-primary-600' : '' ?>"
                   :class="{'justify-center': sidebarCollapsed && window.innerWidth >= 1024}">
                    <i class="fas fa-clipboard-list flex-shrink-0"></i>
                    <span class="sidebar-text ml-3" x-show="!sidebarCollapsed || window.innerWidth < 1024">Requerimientos</span>
                    <div x-show="sidebarCollapsed && window.innerWidth >= 1024" 
                         class="absolute left-full ml-2 px-2 py-1 bg-gray-800 text-white text-sm rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50">
                        Requerimientos
                    </div>
                </a>

                <a href="/projects" 
                   class="flex items-center px-6 py-3 text-gray-700 hover:bg-primary-50 hover:text-primary-600 transition-colors group relative <?= ($current_page ?? '') === 'projects' ? 'bg-primary-50 text-primary-600 border-r-2 border-primary-600' : '' ?>"
                   :class="{'justify-center': sidebarCollapsed && window.innerWidth >= 1024}">
                    <i class="fas fa-project-diagram flex-shrink-0"></i>
                    <span class="sidebar-text ml-3" x-show="!sidebarCollapsed || window.innerWidth < 1024">Proyectos</span>
                    <div x-show="sidebarCollapsed && window.innerWidth >= 1024" 
                         class="absolute left-full ml-2 px-2 py-1 bg-gray-800 text-white text-sm rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50">
                        Proyectos
                    </div>
                </a>

                <a href="/reports" 
                   class="flex items-center px-6 py-3 text-gray-700 hover:bg-primary-50 hover:text-primary-600 transition-colors group relative"
                   :class="{'justify-center': sidebarCollapsed && window.innerWidth >= 1024}">
                    <i class="fas fa-chart-bar flex-shrink-0"></i>
                    <span class="sidebar-text ml-3" x-show="!sidebarCollapsed || window.innerWidth < 1024">Reportes</span>
                    <div x-show="sidebarCollapsed && window.innerWidth >= 1024" 
                         class="absolute left-full ml-2 px-2 py-1 bg-gray-800 text-white text-sm rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50">
                        Reportes
                    </div>
                </a>

                <!-- Separador -->
                <div class="px-4 mt-6" x-show="!sidebarCollapsed || window.innerWidth < 1024">
                    <p class="sidebar-text text-xs font-semibold text-gray-400 uppercase tracking-wide mb-3">Proyectos</p>
                </div>

                <a href="/tasks" 
                   class="flex items-center px-6 py-3 text-gray-700 hover:bg-primary-50 hover:text-primary-600 transition-colors group relative"
                   :class="{'justify-center': sidebarCollapsed && window.innerWidth >= 1024}">
                    <i class="fas fa-tasks flex-shrink-0"></i>
                    <span class="sidebar-text ml-3" x-show="!sidebarCollapsed || window.innerWidth < 1024">Tareas</span>
                    <div x-show="sidebarCollapsed && window.innerWidth >= 1024" 
                         class="absolute left-full ml-2 px-2 py-1 bg-gray-800 text-white text-sm rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50">
                        Tareas
                    </div>
                </a>

                <a href="/reports" 
                   class="flex items-center px-6 py-3 text-gray-700 hover:bg-primary-50 hover:text-primary-600 transition-colors group relative"
                   :class="{'justify-center': sidebarCollapsed && window.innerWidth >= 1024}">
                    <i class="fas fa-chart-bar flex-shrink-0"></i>
                    <span class="sidebar-text ml-3" x-show="!sidebarCollapsed || window.innerWidth < 1024">Reportes</span>
                    <div x-show="sidebarCollapsed && window.innerWidth >= 1024" 
                         class="absolute left-full ml-2 px-2 py-1 bg-gray-800 text-white text-sm rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50">
                        Reportes
                    </div>
                </a>

                <!-- Separador inferior -->
                <div class="mt-auto pt-6 border-t border-gray-200">
                    <a href="/settings" 
                       class="flex items-center px-6 py-3 text-gray-700 hover:bg-primary-50 hover:text-primary-600 transition-colors group relative"
                       :class="{'justify-center': sidebarCollapsed && window.innerWidth >= 1024}">
                        <i class="fas fa-cog flex-shrink-0"></i>
                        <span class="sidebar-text ml-3" x-show="!sidebarCollapsed || window.innerWidth < 1024">Configuración</span>
                        <div x-show="sidebarCollapsed && window.innerWidth >= 1024" 
                             class="absolute left-full ml-2 px-2 py-1 bg-gray-800 text-white text-sm rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 whitespace-nowrap z-50">
                            Configuración
                        </div>
                    </a>
                </div>
            </nav>
        </div>

        <!-- Contenido principal -->
        <div class="transition-all duration-300 ease-in-out"
             :class="{
                'main-content-collapsed': sidebarCollapsed && window.innerWidth >= 1024,
                'main-content-expanded': !sidebarCollapsed && window.innerWidth >= 1024,
                'ml-0': window.innerWidth < 1024
             }">
            
            <!-- Header -->
            <header class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-30">
                <div class="max-w-full mx-auto px-4 sm:px-6 lg:px-8">
                    <div class="flex justify-between items-center py-4">
                        <div class="flex items-center">
                            <!-- Botón hamburguesa móvil -->
                            <button @click="toggleSidebar()" class="lg:hidden text-gray-500 hover:text-gray-700 focus:outline-none focus:text-gray-700 mr-4">
                                <i class="fas fa-bars text-xl"></i>
                            </button>
                            
                            <h1 class="text-xl font-semibold text-gray-900"><?= $page_title ?? 'Dashboard' ?></h1>
                        </div>
                        
                        <div class="flex items-center space-x-4">
                            <!-- Indicador de sesión -->
                            <div id="session-indicator" class="hidden items-center text-sm">
                                <i class="fas fa-clock text-yellow-500 mr-2"></i>
                                <span id="session-time-left" class="text-yellow-600 font-medium"></span>
                            </div>
                            
                            <!-- Usuario -->
                            <div x-data="{ dropdownOpen: false }" class="relative">
                                <button @click="dropdownOpen = !dropdownOpen" 
                                        class="flex items-center text-sm rounded-full focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                                    <div class="h-8 w-8 rounded-full bg-primary-100 flex items-center justify-center">
                                        <span class="text-primary-600 font-medium"><?= strtoupper(substr($_SESSION['user']['first_name'] ?? 'U', 0, 1)) ?></span>
                                    </div>
                                    <span class="ml-3 text-gray-700"><?= $_SESSION['user']['first_name'] ?? 'Usuario' ?></span>
                                    <i class="fas fa-chevron-down ml-2 text-gray-400"></i>
                                </button>
                                
                                <div x-show="dropdownOpen" 
                                     @click.away="dropdownOpen = false"
                                     x-transition:enter="transition ease-out duration-100"
                                     x-transition:enter-start="transform opacity-0 scale-95"
                                     x-transition:enter-end="transform opacity-100 scale-100"
                                     x-transition:leave="transition ease-in duration-75"
                                     x-transition:leave-start="transform opacity-100 scale-100"
                                     x-transition:leave-end="transform opacity-0 scale-95"
                                     class="origin-top-right absolute right-0 mt-2 w-48 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-50">
                                    <div class="py-1">
                                        <a href="/profile" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                            <i class="fas fa-user mr-2"></i>
                                            Mi Perfil
                                        </a>
                                        <a href="/settings" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                            <i class="fas fa-cog mr-2"></i>
                                            Configuración
                                        </a>
                                        <div class="border-t border-gray-100"></div>
                                        <a href="/auth/logout" class="block px-4 py-2 text-sm text-red-600 hover:bg-red-50">
                                            <i class="fas fa-sign-out-alt mr-2"></i>
                                            Cerrar Sesión
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </header>

            <!-- Contenido de la página -->
            <main class="flex-1 relative overflow-x-hidden">
                <div class="py-6">
                    <div class="max-w-full mx-auto px-4 sm:px-6 lg:px-8">
                        <?= $content ?>
                    </div>
                </div>
            </main>
        </div>
        <?php else: ?>
        <!-- Layout sin sidebar para páginas de auth -->
        <div class="min-h-screen">
            <?= $content ?>
        </div>
        <?php endif; ?>
    </div>

    <!-- Toast notifications -->
    <div id="toast-container" class="fixed bottom-4 right-4 z-50 space-y-2"></div>

    <script>
        // Función global para mostrar toasts
        function showToast(message, type = 'info') {
            const container = document.getElementById('toast-container');
            const toast = document.createElement('div');
            
            const bgColor = {
                success: 'bg-green-500',
                error: 'bg-red-500',
                warning: 'bg-yellow-500',
                info: 'bg-blue-500'
            }[type] || 'bg-gray-500';

            const icon = {
                success: 'fas fa-check-circle',
                error: 'fas fa-exclamation-circle',
                warning: 'fas fa-exclamation-triangle',
                info: 'fas fa-info-circle'
            }[type] || 'fas fa-bell';

            toast.className = `${bgColor} text-white px-6 py-3 rounded-lg shadow-lg flex items-center space-x-3 transform transition-all duration-300 translate-x-full`;
            toast.innerHTML = `
                <i class="${icon}"></i>
                <span>${message}</span>
                <button onclick="this.parentElement.remove()" class="ml-4 text-white hover:text-gray-200">
                    <i class="fas fa-times"></i>
                </button>
            `;

            container.appendChild(toast);
            
            // Animar entrada
            setTimeout(() => toast.classList.remove('translate-x-full'), 100);
            
            // Auto-remover después de 5 segundos
            setTimeout(() => {
                if (toast.parentElement) {
                    toast.classList.add('translate-x-full');
                    setTimeout(() => toast.remove(), 300);
                }
            }, 5000);
        }

        // Manejar cierre de modales con ESC
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                // Cerrar modales abiertos
                document.querySelectorAll('.modal, [id$="-modal"]').forEach(modal => {
                    if (!modal.classList.contains('hidden')) {
                        modal.classList.add('hidden');
                    }
                });
            }
        });

        // Mostrar mensajes flash
        <?php if (isset($_SESSION['success'])): ?>
        showToast('<?= addslashes($_SESSION['success']) ?>', 'success');
        <?php unset($_SESSION['success']); ?>
        <?php endif; ?>

        <?php if (isset($_SESSION['error'])): ?>
        showToast('<?= addslashes($_SESSION['error']) ?>', 'error');
        <?php unset($_SESSION['error']); ?>
        <?php endif; ?>
    </script>
</body>
</html>