<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="description" content="Sistema de gestión de tickets y soporte técnico - InnoScale">
    <title>@yield('title', 'Ticketera') - Sistema de Tickets</title>
    
    <!-- DNS Prefetch para CDNs -->
    <link rel="dns-prefetch" href="//cdn.jsdelivr.net">
    <link rel="dns-prefetch" href="//fonts.googleapis.com">
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    
    <!-- Preconnect para recursos críticos -->
    <link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>
    <link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    
    <!-- Preload recursos críticos -->
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" as="style">
    <link rel="preload" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" as="style">
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" as="script">
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <!-- Toastify CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
    
    <style>
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        }
        
        * {
            transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        :root {
            --sidebar-width: 260px;
            --sidebar-bg: #0f1729;
            --sidebar-hover: #1a2742;
            --sidebar-active: #1e3a5f;
            --primary-color: #0066cc;
            --text-muted: #94a3b8;
            
            /* Light Mode Colors */
            --bg-primary: #ffffff;
            --bg-secondary: #f8f9fa;
            --bg-tertiary: #f3f4f6;
            --text-primary: #111827;
            --text-secondary: #374151;
            --text-tertiary: #6b7280;
            --border-color: #e5e7eb;
            --card-bg: #ffffff;
            --card-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
            --input-bg: #ffffff;
            --input-border: #e5e7eb;
        }
        
        /* Dark Mode Colors */
        [data-theme="dark"] {
            --bg-primary: #0f172a;
            --bg-secondary: #1e293b;
            --bg-tertiary: #334155;
            --text-primary: #f1f5f9;
            --text-secondary: #e2e8f0;
            --text-tertiary: #cbd5e1;
            --border-color: #334155;
            --card-bg: #1e293b;
            --card-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
            --input-bg: #0f172a;
            --input-border: #334155;
        }
        
        body {
            background: var(--bg-secondary);
            color: var(--text-primary);
        }
        
        /* Accessibility - Skip Links */
        .skip-link {
            position: absolute;
            top: -40px;
            left: 0;
            background: var(--primary-color);
            color: white;
            padding: 8px 16px;
            text-decoration: none;
            border-radius: 0 0 4px 0;
            z-index: 10000;
            font-weight: 600;
            transition: top 0.2s;
        }
        
        .skip-link:focus {
            top: 0;
            outline: 3px solid #ffc107;
            outline-offset: 2px;
        }
        
        /* Focus Visible - Mejora navegación por teclado */
        *:focus-visible {
            outline: 2px solid var(--primary-color);
            outline-offset: 2px;
            border-radius: 4px;
        }
        
        button:focus-visible,
        a:focus-visible,
        input:focus-visible,
        select:focus-visible,
        textarea:focus-visible {
            outline: 2px solid var(--primary-color);
            outline-offset: 2px;
        }
        
        /* Mejora contraste de enlaces */
        a {
            text-decoration: underline;
            text-decoration-thickness: 1px;
            text-underline-offset: 2px;
        }
        
        a:hover {
            text-decoration-thickness: 2px;
        }
        
        /* Sidebar moderno con tema oscuro */
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            bottom: 0;
            width: var(--sidebar-width);
            background: var(--sidebar-bg);
            padding-top: 70px;
            z-index: 1000;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
        }
        
        .sidebar .nav-link {
            color: var(--text-muted);
            padding: 14px 20px;
            margin: 4px 12px;
            border-radius: 10px;
            font-size: 0.95rem;
            font-weight: 500;
            display: flex;
            align-items: center;
            position: relative;
        }
        
        .sidebar .nav-link:hover {
            background: var(--sidebar-hover);
            color: #ffffff;
            padding-left: 24px;
        }
        
        .sidebar .nav-link.active {
            background: var(--sidebar-active);
            color: #ffffff;
            border-left: 4px solid var(--primary-color);
            padding-left: 16px;
        }
        
        .sidebar .nav-link.active::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 60%;
            background: var(--primary-color);
            border-radius: 0 4px 4px 0;
        }
        
        .sidebar .nav-link i {
            margin-right: 12px;
            width: 20px;
            font-size: 1.1rem;
        }
        
        /* Main content */
        .main-content {
            margin-left: var(--sidebar-width);
            padding-top: 70px;
            min-height: 100vh;
            background: var(--bg-secondary);
        }
        
        /* Top navbar mejorado */
        .top-navbar {
            position: fixed;
            top: 0;
            left: var(--sidebar-width);
            right: 0;
            height: 70px;
            background: var(--bg-primary);
            border-bottom: 1px solid var(--border-color);
            z-index: 999;
            padding: 0 30px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: var(--card-shadow);
        }
        
        /* Logo container mejorado */
        .logo-container {
            position: fixed;
            top: 0;
            left: 0;
            width: var(--sidebar-width);
            height: 70px;
            background: var(--sidebar-bg);
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1001;
        }
        
        .logo-container h4 {
            color: white;
            margin: 0;
            font-weight: 700;
            font-size: 1.3rem;
            letter-spacing: -0.5px;
        }
        
        .logo-container i {
            color: var(--primary-color);
            font-size: 1.5rem;
        }
        
        /* Command Palette Trigger */
        .command-palette-trigger {
            background: var(--input-bg);
            border: 1px solid var(--border-color);
            border-radius: 10px;
            padding: 10px 16px;
            display: flex;
            align-items: center;
            gap: 12px;
            cursor: pointer;
            transition: all 0.2s;
            width: 400px;
            color: var(--text-tertiary);
        }
        
        .command-palette-trigger:hover {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .command-palette-trigger i {
            font-size: 1rem;
        }
        
        .command-palette-trigger span {
            flex: 1;
            text-align: left;
            font-size: 0.9rem;
        }
        
        .shortcut-badge {
            background: var(--bg-tertiary);
            border: 1px solid var(--border-color);
            border-radius: 4px;
            padding: 2px 8px;
            font-size: 0.75rem;
            font-family: monospace;
            color: var(--text-secondary);
        }
        
        /* Command Palette Modal */
        .command-palette {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: 9999;
            display: flex;
            align-items: flex-start;
            justify-content: center;
            padding-top: 10vh;
        }
        
        .command-palette-backdrop {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(4px);
        }
        
        .command-palette-container {
            position: relative;
            width: 90%;
            max-width: 640px;
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            display: flex;
            flex-direction: column;
            max-height: 70vh;
            animation: commandPaletteSlide 0.2s ease-out;
        }
        
        @keyframes commandPaletteSlide {
            from {
                opacity: 0;
                transform: translateY(-20px) scale(0.95);
            }
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }
        
        .command-palette-header {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 20px;
            border-bottom: 1px solid var(--border-color);
        }
        
        .command-palette-header i {
            color: var(--text-tertiary);
            font-size: 1.2rem;
        }
        
        .command-palette-header input {
            flex: 1;
            border: none;
            outline: none;
            font-size: 1rem;
            background: transparent;
            color: var(--text-primary);
        }
        
        .command-palette-header input::placeholder {
            color: var(--text-tertiary);
        }
        
        .command-palette-close {
            background: none;
            border: none;
            color: var(--text-tertiary);
            cursor: pointer;
            padding: 4px;
            border-radius: 6px;
            transition: all 0.2s;
        }
        
        .command-palette-close:hover {
            background: var(--bg-tertiary);
            color: var(--text-primary);
        }
        
        .command-palette-body {
            flex: 1;
            overflow-y: auto;
            padding: 8px;
        }
        
        .command-section {
            margin-bottom: 16px;
        }
        
        .command-section-title {
            padding: 8px 12px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: var(--text-tertiary);
        }
        
        .command-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.15s;
            text-decoration: none;
            color: var(--text-primary);
        }
        
        .command-item:hover,
        .command-item.active {
            background: var(--bg-tertiary);
        }
        
        .command-icon {
            width: 36px;
            height: 36px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            font-size: 1.1rem;
        }
        
        .command-content {
            flex: 1;
        }
        
        .command-title {
            font-size: 0.95rem;
            font-weight: 500;
            color: var(--text-primary);
            margin-bottom: 2px;
        }
        
        .command-subtitle {
            font-size: 0.8rem;
            color: var(--text-secondary);
        }
        
        .command-kbd {
            background: var(--bg-tertiary);
            border: 1px solid var(--border-color);
            border-radius: 4px;
            padding: 4px 8px;
            font-size: 0.75rem;
            font-family: monospace;
            color: var(--text-secondary);
            min-width: 24px;
            text-align: center;
        }
        
        .command-no-results {
            text-align: center;
            padding: 60px 20px;
            color: var(--text-tertiary);
        }
        
        .command-no-results i {
            font-size: 3rem;
            margin-bottom: 16px;
            opacity: 0.5;
        }
        
        .command-no-results p {
            margin: 0;
            font-size: 0.95rem;
        }
        
        .command-palette-footer {
            border-top: 1px solid var(--border-color);
            padding: 12px 20px;
            background: var(--bg-secondary);
            border-radius: 0 0 16px 16px;
        }
        
        .command-footer-tips {
            display: flex;
            gap: 20px;
            font-size: 0.8rem;
            color: var(--text-secondary);
        }
        
        .command-footer-tips span {
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .command-footer-tips kbd {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 4px;
            padding: 2px 6px;
            font-size: 0.7rem;
            font-family: monospace;
        }
        
        /* Tooltips Personalizados */
        .tooltip {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
        }
        
        .tooltip-inner {
            background-color: var(--text-primary);
            color: var(--bg-primary);
            padding: 8px 12px;
            border-radius: 8px;
            font-size: 0.85rem;
            font-weight: 500;
            max-width: 280px;
            text-align: left;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        
        .tooltip.bs-tooltip-top .tooltip-arrow::before,
        .tooltip.bs-tooltip-auto[data-popper-placement^="top"] .tooltip-arrow::before {
            border-top-color: var(--text-primary);
        }
        
        .tooltip.bs-tooltip-end .tooltip-arrow::before,
        .tooltip.bs-tooltip-auto[data-popper-placement^="right"] .tooltip-arrow::before {
            border-right-color: var(--text-primary);
        }
        
        .tooltip.bs-tooltip-bottom .tooltip-arrow::before,
        .tooltip.bs-tooltip-auto[data-popper-placement^="bottom"] .tooltip-arrow::before {
            border-bottom-color: var(--text-primary);
        }
        
        .tooltip.bs-tooltip-start .tooltip-arrow::before,
        .tooltip.bs-tooltip-auto[data-popper-placement^="left"] .tooltip-arrow::before {
            border-left-color: var(--text-primary);
        }
        
        /* Help Icon Style */
        .help-icon {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 18px;
            height: 18px;
            border-radius: 50%;
            background: var(--bg-tertiary);
            color: var(--text-secondary);
            font-size: 0.75rem;
            cursor: help;
            margin-left: 6px;
            transition: all 0.2s;
        }
        
        .help-icon:hover {
            background: var(--primary-color);
            color: white;
            transform: scale(1.1);
        }
        
        /* User dropdown menu */
        .user-dropdown {
            position: relative;
        }
        
        .user-dropdown .dropdown-toggle {
            background: none;
            border: none;
            padding: 8px 16px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
            color: var(--text-primary);
            font-weight: 500;
        }
        
        .user-dropdown .dropdown-toggle:hover {
            background: var(--bg-tertiary);
        }
        
        .user-dropdown .user-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: linear-gradient(135deg, #0066cc 0%, #004c99 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            font-size: 0.9rem;
        }
        
        .user-dropdown .dropdown-menu {
            position: absolute;
            top: 120%;
            right: 0;
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 10px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            min-width: 220px;
            padding: 8px;
            display: none;
        }
        
        .user-dropdown.show .dropdown-menu {
            display: block;
        }
        
        .user-dropdown .dropdown-item {
            padding: 10px 14px;
            border-radius: 6px;
            color: var(--text-secondary);
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 0.9rem;
        }
        
        .user-dropdown .dropdown-item:hover {
            background: var(--bg-tertiary);
        }
        
        .user-dropdown .dropdown-item i {
            width: 20px;
            text-align: center;
        }
        
        .user-dropdown .dropdown-divider {
            height: 1px;
            background: var(--border-color);
            margin: 8px 0;
        }
        
        .user-dropdown .user-info {
            padding: 12px 14px;
            border-bottom: 1px solid var(--border-color);
            margin-bottom: 8px;
        }
        
        .user-dropdown .user-info .user-name {
            font-weight: 600;
            color: var(--text-primary);
            font-size: 0.95rem;
        }
        
        .user-dropdown .user-info .user-role {
            font-size: 0.8rem;
            color: var(--text-tertiary);
            margin-top: 2px;
        }
        
        /* Dark Mode Toggle */
        .theme-toggle {
            background: none;
            border: none;
            padding: 8px 12px;
            border-radius: 10px;
            cursor: pointer;
            color: var(--text-secondary);
            font-size: 1.2rem;
            transition: all 0.2s;
        }
        
        .theme-toggle:hover {
            background: var(--bg-tertiary);
        }
        
        .theme-icon {
            display: none;
        }
        
        .theme-icon.sun {
            display: inline-block;
        }
        
        [data-theme="dark"] .theme-icon.sun {
            display: none;
        }
        
        [data-theme="dark"] .theme-icon.moon {
            display: inline-block;
        }
        
        /* Hamburger menu para móvil */
        .hamburger-menu {
            display: none;
            background: none;
            border: none;
            font-size: 1.5rem;
            color: var(--text-primary);
            cursor: pointer;
            padding: 8px;
        }
        
        /* Notification badge mejorado */
        .notification-badge {
            position: absolute;
            top: 8px;
            right: 8px;
            background: #ef4444;
            color: white;
            border-radius: 10px;
            padding: 2px 6px;
            font-size: 0.7rem;
            font-weight: 600;
            min-width: 18px;
            text-align: center;
            box-shadow: 0 2px 4px rgba(239, 68, 68, 0.3);
        }
        
        /* Badges con colores mejorados */
        .badge-priority-baja { background: #10b981; }
        .badge-priority-media { background: #3b82f6; }
        .badge-priority-alta { background: #f59e0b; }
        .badge-priority-critica { background: #ef4444; }
        
        .badge-status-abierto { background: #3b82f6; }
        .badge-status-en_progreso { background: #f59e0b; }
        .badge-status-resuelto { background: #10b981; }
        .badge-status-cerrado { background: #6b7280; }
        
        /* Cards mejorados */
        .card {
            border: 1px solid var(--border-color);
            background: var(--card-bg);
            box-shadow: var(--card-shadow);
            margin-bottom: 20px;
            border-radius: 12px;
        }
        
        .card-header, .card-body, .card-footer {
            background: var(--card-bg);
            color: var(--text-primary);
        }
        
        .stats-card {
            border-left: 4px solid;
            transition: all 0.3s;
        }
        
        .stats-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
        }
        
        /* Form inputs */
        .form-control, .form-select {
            background: var(--input-bg);
            border-color: var(--input-border);
            color: var(--text-primary);
        }
        
        .form-control:focus, .form-select:focus {
            background: var(--input-bg);
            border-color: var(--primary-color);
            color: var(--text-primary);
        }
        
        .form-label {
            color: var(--text-secondary);
        }
        
        /* Tables */
        .table {
            color: var(--text-primary);
        }
        
        .table thead th {
            border-color: var(--border-color);
            background: var(--bg-tertiary);
            color: var(--text-primary);
        }
        
        .table tbody td {
            border-color: var(--border-color);
        }
        
        .table-hover tbody tr:hover {
            background: var(--bg-tertiary);
        }
        
        /* Breadcrumbs */
        .breadcrumb-nav {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
        }
        
        /* Modals */
        .modal-content {
            background: var(--card-bg);
            border-color: var(--border-color);
        }
        
        .modal-header, .modal-footer {
            border-color: var(--border-color);
        }
        
        .modal-title {
            color: var(--text-primary);
        }
        
        /* Focus states para accesibilidad */
        *:focus {
            outline: 2px solid var(--primary-color);
            outline-offset: 2px;
        }
        
        button:focus,
        a:focus {
            outline: 2px solid var(--primary-color);
            outline-offset: 2px;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }
            
            .sidebar.show {
                transform: translateX(0);
            }
            
            .main-content,
            .top-navbar {
                margin-left: 0;
                left: 0;
            }
            
            .logo-container {
                display: none;
            }
            
            .hamburger-menu {
                display: block;
            }
            
            .search-global {
                display: none;
            }
            
            .top-navbar {
                padding: 0 15px;
            }
        }
        
        @media (max-width: 992px) {
            .command-palette-trigger {
                width: 300px;
            }
            
            .command-palette-trigger span {
                display: none;
            }
        }
        
        /* Loading Spinner */
        .btn-loading {
            position: relative;
            pointer-events: none;
        }
        
        .btn-loading::after {
            content: '';
            position: absolute;
            width: 16px;
            height: 16px;
            top: 50%;
            left: 50%;
            margin-left: -8px;
            margin-top: -8px;
            border: 2px solid transparent;
            border-top-color: currentColor;
            border-radius: 50%;
            animation: spinner 0.6s linear infinite;
        }
        
        @keyframes spinner {
            to { transform: rotate(360deg); }
        }
        
        /* Skeleton Loader */
        .skeleton {
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 200% 100%;
            animation: skeleton-loading 1.5s ease-in-out infinite;
            border-radius: 4px;
        }
        
        @keyframes skeleton-loading {
            0% { background-position: 200% 0; }
            100% { background-position: -200% 0; }
        }
        
        .skeleton-text {
            height: 1rem;
            margin-bottom: 0.5rem;
        }
        
        .skeleton-title {
            height: 1.5rem;
            width: 60%;
            margin-bottom: 1rem;
        }
        
        /* Pulse Animation for new items */
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.7; }
        }
        
        .pulse {
            animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }
        
        /* Slide in animations */
        @keyframes slideInRight {
            from {
                opacity: 0;
                transform: translateX(30px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }
        
        .slide-in {
            animation: slideInRight 0.3s ease-out;
        }
        
        /* Scale in for modals */
        @keyframes scaleIn {
            from {
                opacity: 0;
                transform: scale(0.95);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }
        
        .modal.show .modal-dialog {
            animation: scaleIn 0.2s ease-out;
        }
        
        /* Fade in for alerts */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .alert {
            animation: fadeIn 0.3s ease-out;
        }
        
        /* Ripple effect for buttons */
        .btn {
            position: relative;
            overflow: hidden;
        }
        
        .btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.3);
            transform: translate(-50%, -50%);
            transition: width 0.6s, height 0.6s;
        }
        
        .btn:active::before {
            width: 300px;
            height: 300px;
        }
        
        /* Smooth page transitions */
        .main-content > .container-fluid {
            animation: fadeIn 0.4s ease-out;
        }
        
        /* Ticket Cards for Mobile */
        .ticket-card-mobile {
            display: none;
            background: white;
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 12px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
            border-left: 4px solid;
            transition: all 0.2s;
        }
        
        .ticket-card-mobile:hover {
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12);
            transform: translateY(-2px);
        }
        
        .ticket-card-mobile.priority-baja {
            border-left-color: #10b981;
        }
        
        .ticket-card-mobile.priority-media {
            border-left-color: #3b82f6;
        }
        
        .ticket-card-mobile.priority-alta {
            border-left-color: #f59e0b;
        }
        
        .ticket-card-mobile.priority-critica {
            border-left-color: #ef4444;
        }
        
        .ticket-card-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 12px;
        }
        
        .ticket-card-number {
            font-weight: 700;
            color: #374151;
            font-size: 0.9rem;
        }
        
        .ticket-card-badges {
            display: flex;
            gap: 6px;
            flex-wrap: wrap;
        }
        
        .ticket-card-title {
            font-size: 1rem;
            font-weight: 600;
            color: #111827;
            margin-bottom: 8px;
            line-height: 1.4;
        }
        
        .ticket-card-meta {
            display: flex;
            flex-direction: column;
            gap: 8px;
            font-size: 0.85rem;
            color: #6b7280;
        }
        
        .ticket-card-meta-item {
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .ticket-card-meta-item i {
            width: 16px;
            text-align: center;
        }
        
        .ticket-card-footer {
            margin-top: 12px;
            padding-top: 12px;
            border-top: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        @media (max-width: 768px) {
            .table-responsive table {
                display: none !important;
            }
            
            .ticket-card-mobile {
                display: block;
            }
            
            .pagination {
                font-size: 0.85rem;
            }
            
            .pagination .page-link {
                padding: 6px 12px;
            }
            
            .command-palette-trigger {
                width: auto;
                min-width: 44px;
                padding: 10px 12px;
            }
            
            .command-palette-container {
                width: 95%;
                padding-top: 5vh;
            }
        }
        
        /* Notification Center */
        .notification-center {
            position: relative;
        }
        
        .notification-bell {
            background: none;
            border: none;
            padding: 8px 12px;
            border-radius: 10px;
            cursor: pointer;
            color: var(--text-primary);
            font-size: 1.3rem;
            position: relative;
            transition: all 0.2s;
        }
        
        .notification-bell:hover {
            background: var(--bg-tertiary);
        }
        
        .notification-bell .notification-count {
            position: absolute;
            top: 4px;
            right: 6px;
            background: #ef4444;
            color: white;
            border-radius: 10px;
            padding: 2px 6px;
            font-size: 0.7rem;
            font-weight: 600;
            min-width: 18px;
            text-align: center;
            box-shadow: 0 2px 4px rgba(239, 68, 68, 0.3);
            animation: pulse 2s infinite;
        }
        
        .notification-dropdown {
            position: absolute;
            top: 120%;
            right: 0;
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 10px;
            box-shadow: var(--card-shadow);
            width: 380px;
            max-height: 500px;
            display: none;
            flex-direction: column;
            z-index: 1000;
        }
        
        .notification-center.show .notification-dropdown {
            display: flex;
        }
        
        .notification-header {
            padding: 16px 20px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .notification-header h6 {
            margin: 0;
            font-weight: 600;
            color: var(--text-primary);
        }
        
        .notification-mark-all {
            font-size: 0.85rem;
            color: #0066cc;
            cursor: pointer;
            text-decoration: none;
        }
        
        .notification-mark-all:hover {
            text-decoration: underline;
        }
        
        .notification-list {
            overflow-y: auto;
            max-height: 400px;
        }
        
        .notification-item {
            padding: 14px 20px;
            border-bottom: 1px solid var(--border-color);
            cursor: pointer;
            transition: background 0.2s;
            display: flex;
            gap: 12px;
        }
        
        .notification-item:hover {
            background: var(--bg-tertiary);
        }
        
        .notification-item.unread {
            background: rgba(102, 126, 234, 0.05);
        }
        
        .notification-item.unread::before {
            content: '';
            width: 8px;
            height: 8px;
            background: #3b82f6;
            border-radius: 50%;
            flex-shrink: 0;
            margin-top: 6px;
        }
        
        .notification-icon {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            font-size: 1rem;
        }
        
        .notification-icon.comment {
            background: #dbeafe;
            color: #3b82f6;
        }
        
        .notification-icon.ticket {
            background: #fef3c7;
            color: #f59e0b;
        }
        
        .notification-icon.assigned {
            background: #d1fae5;
            color: #10b981;
        }
        
        .notification-content {
            flex: 1;
        }
        
        .notification-title {
            font-size: 0.9rem;
            color: var(--text-primary);
            margin-bottom: 4px;
            line-height: 1.4;
        }
        
        .notification-meta {
            font-size: 0.8rem;
            color: var(--text-secondary);
        }
        
        .notification-footer {
            padding: 12px 20px;
            border-top: 1px solid var(--border-color);
            text-align: center;
        }
        
        .notification-footer a {
            font-size: 0.9rem;
            color: #0066cc;
            text-decoration: none;
            font-weight: 500;
        }
        
        .notification-footer a:hover {
            text-decoration: underline;
        }
        
        .notification-empty {
            padding: 40px 20px;
            text-align: center;
            color: #9ca3af;
        }
        
        .notification-empty i {
            font-size: 3rem;
            margin-bottom: 12px;
            opacity: 0.5;
        }
        
        @media (max-width: 768px) {
            .notification-dropdown {
                width: 320px;
                right: -60px;
            }
        }
    </style>
    
    @stack('styles')
</head>
<body>
    <!-- Skip Links para accesibilidad -->
    <a href="#main-content" class="skip-link">Saltar al contenido principal</a>
    <a href="#sidebar-nav" class="skip-link">Saltar a navegación</a>
    
    <!-- Logo -->
    <div class="logo-container" role="banner">
        <h4><i class="bi bi-ticket-perforated" aria-hidden="true"></i> Ticketera</h4>
    </div>
    
    <!-- Sidebar -->
    <nav class="sidebar" id="sidebar-nav" aria-label="Navegación principal">
        <div class="nav flex-column mt-3">
            <a class="nav-link {{ request()->routeIs('dashboard') ? 'active' : '' }}" 
               href="{{ route('dashboard') }}"
               aria-label="Dashboard - Vista general del sistema"
               aria-current="{{ request()->routeIs('dashboard') ? 'page' : 'false' }}">
                <i class="bi bi-speedometer2" aria-hidden="true"></i> Dashboard
            </a>
            
            <a class="nav-link {{ request()->routeIs('tickets.*') ? 'active' : '' }}" 
               href="{{ route('tickets.index') }}"
               aria-label="Tickets - Gestión de solicitudes{{ isset($unreadTicketsCount) && $unreadTicketsCount > 0 ? ', ' . $unreadTicketsCount . ' sin leer' : '' }}"
               aria-current="{{ request()->routeIs('tickets.*') ? 'page' : 'false' }}">
                <i class="bi bi-ticket" aria-hidden="true"></i> Tickets
                @if(isset($unreadTicketsCount) && $unreadTicketsCount > 0)
                <span class="badge bg-danger rounded-pill ms-auto" aria-label="{{ $unreadTicketsCount }} tickets sin leer">{{ $unreadTicketsCount }}</span>
                @endif
            </a>
            
            @if(auth()->user()->hasRole('administrador'))
            <a class="nav-link {{ request()->routeIs('companies.*') ? 'active' : '' }}" 
               href="{{ route('companies.index') }}"
               aria-label="Empresas - Gestión de compañías cliente"
               aria-current="{{ request()->routeIs('companies.*') ? 'page' : 'false' }}">
                <i class="bi bi-building" aria-hidden="true"></i> Empresas
            </a>
            @endif
            
            @if(auth()->user()->hasRole('administrador'))
            <a class="nav-link {{ request()->routeIs('invitations.*') ? 'active' : '' }}" 
               href="{{ route('invitations.index') }}"
               aria-label="Invitaciones - Enviar accesos a nuevos usuarios"
               aria-current="{{ request()->routeIs('invitations.*') ? 'page' : 'false' }}">
                <i class="bi bi-envelope-check" aria-hidden="true"></i> Invitaciones
            </a>
            @endif
            
            @if(auth()->user()->hasRole('administrador'))
            <a class="nav-link {{ request()->routeIs('users.*') ? 'active' : '' }}" 
               href="{{ route('users.index') }}"
               aria-label="Usuarios - Administrar cuentas del sistema"
               aria-current="{{ request()->routeIs('users.*') ? 'page' : 'false' }}">
                <i class="bi bi-people" aria-hidden="true"></i> Usuarios
            </a>
            @endif
            
            <a class="nav-link {{ request()->routeIs('projects.*') ? 'active' : '' }}" 
               href="{{ route('projects.index') }}"
               aria-label="Proyectos - Gestión de proyectos"
               aria-current="{{ request()->routeIs('projects.*') ? 'page' : 'false' }}">
                <i class="bi bi-folder" aria-hidden="true"></i> Proyectos
            </a>
            
            <a class="nav-link {{ request()->routeIs('knowledge-base.*') ? 'active' : '' }}" 
               href="{{ route('knowledge-base.index') }}"
               aria-label="Base de Conocimiento - Artículos y documentación"
               aria-current="{{ request()->routeIs('knowledge-base.*') ? 'page' : 'false' }}">
                <i class="bi bi-book" aria-hidden="true"></i> Base de Conocimiento
            </a>
            
            @if(auth()->user()->hasRole('administrador'))
            <a class="nav-link {{ request()->routeIs('api.documentation') ? 'active' : '' }}" 
               href="{{ route('api.documentation') }}"
               aria-label="API - Documentación para desarrolladores"
               aria-current="{{ request()->routeIs('api.documentation') ? 'page' : 'false' }}">
                <i class="bi bi-code-square" aria-hidden="true"></i> API
            </a>
            @endif
            
            @if(auth()->user()->hasRole(['administrador', 'supervisor']))
            <a class="nav-link {{ request()->routeIs('reports.*') ? 'active' : '' }}" 
               href="{{ route('reports.index') }}"
               aria-label="Reportes - Estadísticas y análisis"
               aria-current="{{ request()->routeIs('reports.*') ? 'page' : 'false' }}">
                <i class="bi bi-graph-up" aria-hidden="true"></i> Reportes
            </a>
            @endif
            
            <hr class="text-white mx-3" role="separator" aria-orientation="horizontal">
            
            <a class="nav-link" 
               href="#" 
               onclick="event.preventDefault(); document.getElementById('logout-form').submit();"
               aria-label="Cerrar sesión y salir del sistema">
                <i class="bi bi-box-arrow-right" aria-hidden="true"></i> Cerrar Sesión
            </a>
        </div>
        
        <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
            @csrf
        </form>
    </nav>
    
    <!-- Top Navbar -->
    <header class="top-navbar" role="banner">
        <div style="display: flex; align-items: center; gap: 20px;">
            <!-- Hamburger menu para móvil -->
            <button class="hamburger-menu" 
                    onclick="toggleSidebar()"
                    aria-label="Abrir menú de navegación"
                    aria-expanded="false"
                    aria-controls="sidebar-nav">
                <i class="bi bi-list" aria-hidden="true"></i>
            </button>
            
            <!-- Command Palette Trigger -->
            <button class="command-palette-trigger" 
                    onclick="openCommandPalette()"
                    aria-label="Abrir paleta de comandos - Atajo: Control + K">
                <i class="bi bi-search" aria-hidden="true"></i>
                <span>Buscar o ejecutar comando...</span>
                <kbd class="shortcut-badge">Ctrl+K</kbd>
            </button>
        </div>
        
        <div style="display: flex; align-items: center; gap: 12px;">
            <!-- Theme Toggle -->
            <button class="theme-toggle" 
                    onclick="toggleTheme()" 
                    aria-label="Cambiar tema de color"
                    title="Cambiar entre modo claro y oscuro">
                <i class="bi bi-sun-fill theme-icon sun" aria-hidden="true"></i>
                <i class="bi bi-moon-stars-fill theme-icon moon" aria-hidden="true"></i>
            </button>
            
            <!-- Notification Center -->
            <div class="notification-center" id="notificationCenter" role="region" aria-label="Centro de notificaciones">
                <button class="notification-bell" 
                        onclick="toggleNotifications()"
                        aria-label="{{ isset($unreadTicketsCount) && $unreadTicketsCount > 0 ? $unreadTicketsCount . ' notificaciones sin leer' : 'Ver notificaciones' }}"
                        aria-expanded="false"
                        aria-haspopup="true">
                    <i class="bi bi-bell" aria-hidden="true"></i>
                    @if(isset($unreadTicketsCount) && $unreadTicketsCount > 0)
                    <span class="notification-count" aria-label="{{ $unreadTicketsCount }} sin leer">{{ $unreadTicketsCount }}</span>
                    @endif
                </button>
                
                <div class="notification-dropdown" role="menu" aria-label="Lista de notificaciones">
                    <div class="notification-header">
                        <h6>Notificaciones</h6>
                        <a href="#" 
                           class="notification-mark-all" 
                           onclick="markAllAsRead(event)"
                           role="button"
                           aria-label="Marcar todas las notificaciones como leídas">
                            Marcar todas como leídas
                        </a>
                    </div>
                    
                    <div class="notification-list" id="notificationList" role="list">
                        @if(isset($unreadTicketsCount) && $unreadTicketsCount > 0)
                            <div class="notification-item unread" 
                                 onclick="window.location.href='{{ route('tickets.index') }}'"
                                 role="listitem"
                                 tabindex="0">
                                <div class="notification-icon ticket" aria-hidden="true">
                                    <i class="bi bi-ticket"></i>
                                </div>
                                <div class="notification-content">
                                    <div class="notification-title">
                                        Tienes {{ $unreadTicketsCount }} ticket(s) con comentarios nuevos
                                    </div>
                                    <div class="notification-meta">
                                        Revisa los tickets pendientes
                                    </div>
                                </div>
                            </div>
                        @else
                            <div class="notification-empty">
                                <i class="bi bi-bell-slash"></i>
                                <div>No hay notificaciones nuevas</div>
                            </div>
                        @endif
                    </div>
                    
                    <div class="notification-footer">
                        <a href="{{ route('tickets.index') }}">Ver todos los tickets</a>
                    </div>
                </div>
            </div>
            
            <!-- User dropdown -->
            <div class="user-dropdown" id="userDropdown" role="navigation" aria-label="Menú de usuario">
            <button class="dropdown-toggle" 
                    onclick="toggleUserDropdown()"
                    aria-label="Menú de {{ auth()->user()->name }}"
                    aria-expanded="false"
                    aria-haspopup="true">
                <div class="user-avatar" aria-hidden="true">
                    {{ strtoupper(substr(auth()->user()->name, 0, 1)) }}
                </div>
                <div style="text-align: left;">
                    <div style="font-size: 0.9rem;">{{ auth()->user()->name }}</div>
                    <div style="font-size: 0.75rem; color: #6b7280;">
                        {{ role_name(auth()->user()->role) }}
                    </div>
                </div>
                <i class="bi bi-chevron-down" style="font-size: 0.8rem;" aria-hidden="true"></i>
            </button>
            
            <div class="dropdown-menu" role="menu">
                <div class="user-info" role="presentation">
                    <div class="user-name">{{ auth()->user()->name }}</div>
                    <div class="user-role">{{ auth()->user()->email }}</div>
                </div>
                
                <a href="{{ route('profile.edit') }}" class="dropdown-item" role="menuitem">
                    <i class="bi bi-person" aria-hidden="true"></i> Mi Perfil
                </a>
                <a href="{{ route('settings.index') }}" class="dropdown-item" role="menuitem">
                    <i class="bi bi-gear" aria-hidden="true"></i> Configuración
                </a>
                <a href="{{ route('help.index') }}" class="dropdown-item">
                    <i class="bi bi-question-circle"></i> Ayuda
                </a>
                
                <div class="dropdown-divider"></div>
                
                <a href="#" class="dropdown-item" style="color: #ef4444;" onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
                    <i class="bi bi-box-arrow-right"></i> Cerrar Sesión
                </a>
            </div>
        </div>
    </div>
    </header>
    
    <!-- Main Content -->
    <main class="main-content" id="main-content" role="main" aria-label="Contenido principal">
        <div class="container-fluid p-4">
            @yield('content')
        </div>
    </main>
    
    <!-- Bootstrap 5 JS Bundle - Defer para no bloquear rendering -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" defer></script>
    <!-- Toastify JS - Defer -->
    <script src="https://cdn.jsdelivr.net/npm/toastify-js" defer></script>
    
    <script>
        // Performance: Lazy loading de imágenes
        document.addEventListener('DOMContentLoaded', function() {
            // Implementar Intersection Observer para lazy loading
            if ('IntersectionObserver' in window) {
                const imageObserver = new IntersectionObserver((entries, observer) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            const img = entry.target;
                            if (img.dataset.src) {
                                img.src = img.dataset.src;
                                img.removeAttribute('data-src');
                                observer.unobserve(img);
                            }
                        }
                    });
                }, {
                    rootMargin: '50px' // Cargar 50px antes de que sea visible
                });
                
                // Observar todas las imágenes con data-src
                document.querySelectorAll('img[data-src]').forEach(img => {
                    imageObserver.observe(img);
                });
            } else {
                // Fallback para navegadores antiguos
                document.querySelectorAll('img[data-src]').forEach(img => {
                    img.src = img.dataset.src;
                });
            }
        });
        
        // Función helper para mostrar toasts
        function showToast(message, type = 'success') {
            const colors = {
                success: 'linear-gradient(135deg, #10b981 0%, #059669 100%)',
                error: 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)',
                warning: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)',
                info: 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)'
            };
            
            Toastify({
                text: message,
                duration: 4000,
                close: true,
                gravity: "top",
                position: "right",
                stopOnFocus: true,
                style: {
                    background: colors[type] || colors.success,
                    borderRadius: "10px",
                    padding: "16px 20px",
                    fontSize: "0.95rem",
                    fontWeight: "500",
                    boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)"
                },
                onClick: function(){} // Callback after click
            }).showToast();
        }
        
        // Mostrar mensajes de sesión como toasts
        @if(session('success'))
            showToast("✓ {{ session('success') }}", 'success');
        @endif
        
        @if(session('error'))
            showToast("✕ {{ session('error') }}", 'error');
        @endif
        
        @if($errors->any())
            @foreach($errors->all() as $error)
                showToast("✕ {{ $error }}", 'error');
            @endforeach
        @endif
    </script>
    
    <script>
        // Toggle sidebar móvil
        function toggleSidebar() {
            const sidebar = document.querySelector('.sidebar');
            const hamburger = document.querySelector('.hamburger-menu');
            const isExpanded = sidebar.classList.toggle('show');
            
            // Update aria-expanded
            if (hamburger) {
                hamburger.setAttribute('aria-expanded', isExpanded);
            }
        }
        
        // Toggle user dropdown
        function toggleUserDropdown() {
            const userDropdown = document.getElementById('userDropdown');
            const button = userDropdown?.querySelector('.dropdown-toggle');
            
            // Cerrar notificaciones si están abiertas
            const notificationCenter = document.getElementById('notificationCenter');
            const notifButton = notificationCenter?.querySelector('.notification-bell');
            notificationCenter?.classList.remove('show');
            if (notifButton) notifButton.setAttribute('aria-expanded', 'false');
            
            // Toggle user dropdown
            const isExpanded = userDropdown.classList.toggle('show');
            if (button) button.setAttribute('aria-expanded', isExpanded);
        }
        
        // Toggle notifications
        function toggleNotifications() {
            const notificationCenter = document.getElementById('notificationCenter');
            const button = notificationCenter?.querySelector('.notification-bell');
            
            // Cerrar user dropdown si está abierto
            const userDropdown = document.getElementById('userDropdown');
            const userButton = userDropdown?.querySelector('.dropdown-toggle');
            userDropdown?.classList.remove('show');
            if (userButton) userButton.setAttribute('aria-expanded', 'false');
            
            // Toggle notifications
            const isExpanded = notificationCenter.classList.toggle('show');
            if (button) button.setAttribute('aria-expanded', isExpanded);
        }
        
        // Marcar todas como leídas
        function markAllAsRead(event) {
            event.preventDefault();
            event.stopPropagation();
            
            // Remover clase unread de todos los items
            document.querySelectorAll('.notification-item.unread').forEach(item => {
                item.classList.remove('unread');
            });
            
            // Ocultar contador
            const counter = document.querySelector('.notification-count');
            if (counter) {
                counter.style.display = 'none';
            }
            
            showToast('Todas las notificaciones marcadas como leídas', 'success');
        }
        
        // Cerrar dropdown al hacer clic fuera
        document.addEventListener('click', function(event) {
            const userDropdown = document.getElementById('userDropdown');
            const notificationCenter = document.getElementById('notificationCenter');
            
            if (userDropdown && !userDropdown.contains(event.target)) {
                userDropdown.classList.remove('show');
                const button = userDropdown.querySelector('.dropdown-toggle');
                if (button) button.setAttribute('aria-expanded', 'false');
            }
            
            if (notificationCenter && !notificationCenter.contains(event.target)) {
                notificationCenter.classList.remove('show');
                const button = notificationCenter.querySelector('.notification-bell');
                if (button) button.setAttribute('aria-expanded', 'false');
            }
        });
        
        // Atajo de teclado Ctrl+K para búsqueda
        document.addEventListener('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                e.preventDefault();
                const searchInput = document.getElementById('globalSearch');
                if (searchInput) {
                    searchInput.focus();
                }
            }
            
            // ESC para cerrar dropdown
            if (e.key === 'Escape') {
                document.getElementById('userDropdown')?.classList.remove('show');
                document.getElementById('notificationCenter')?.classList.remove('show');
            }
        });
        
        // Búsqueda global (funcionalidad básica)
        const globalSearch = document.getElementById('globalSearch');
        if (globalSearch) {
            let searchTimeout;
            globalSearch.addEventListener('input', function(e) {
                clearTimeout(searchTimeout);
                const query = e.target.value.trim();
                
                if (query.length >= 2) {
                    searchTimeout = setTimeout(() => {
                        // TODO: Implementar búsqueda AJAX
                        console.log('Buscando:', query);
                    }, 300);
                }
            });
            
            // Enter para buscar
            globalSearch.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    const query = e.target.value.trim();
                    if (query) {
                        window.location.href = `/tickets?search=${encodeURIComponent(query)}`;
                    }
                }
            });
        }
        
        // Cerrar sidebar al hacer clic fuera en móvil
        document.addEventListener('click', function(event) {
            const sidebar = document.querySelector('.sidebar');
            const hamburger = document.querySelector('.hamburger-menu');
            
            if (window.innerWidth <= 768 && 
                sidebar?.classList.contains('show') && 
                !sidebar.contains(event.target) && 
                !hamburger?.contains(event.target)) {
                sidebar.classList.remove('show');
            }
        });
        
        // Theme Management
        function toggleTheme() {
            const html = document.documentElement;
            const currentTheme = html.getAttribute('data-theme') || 'light';
            const newTheme = currentTheme === 'light' ? 'dark' : 'light';
            html.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
        }

        // Initialize theme on page load
        (function initTheme() {
            const savedTheme = localStorage.getItem('theme') || 
                              (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
            document.documentElement.setAttribute('data-theme', savedTheme);
        })();

        // Command Palette Management
        let commandPaletteOpen = false;
        let currentCommandIndex = -1;
        let searchTimeout = null;

        function openCommandPalette() {
            const palette = document.getElementById('commandPalette');
            const input = document.getElementById('commandPaletteInput');
            palette.style.display = 'flex';
            commandPaletteOpen = true;
            setTimeout(() => input.focus(), 100);
        }

        function closeCommandPalette() {
            const palette = document.getElementById('commandPalette');
            const input = document.getElementById('commandPaletteInput');
            palette.style.display = 'none';
            commandPaletteOpen = false;
            input.value = '';
            currentCommandIndex = -1;
            document.getElementById('searchResultsSection').style.display = 'none';
            document.getElementById('noResults').style.display = 'none';
        }

        // Global keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Ctrl+K or Cmd+K to open command palette
            if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                e.preventDefault();
                if (commandPaletteOpen) {
                    closeCommandPalette();
                } else {
                    openCommandPalette();
                }
            }
            
            // ESC to close command palette
            if (e.key === 'Escape' && commandPaletteOpen) {
                closeCommandPalette();
            }
            
            // Arrow navigation in command palette
            if (commandPaletteOpen && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
                e.preventDefault();
                navigateCommands(e.key === 'ArrowDown' ? 1 : -1);
            }
            
            // Enter to select command
            if (commandPaletteOpen && e.key === 'Enter') {
                e.preventDefault();
                selectCommand();
            }
            
            // Quick action shortcuts when palette is open
            if (commandPaletteOpen && !e.ctrlKey && !e.metaKey && !e.altKey) {
                const quickActions = {
                    'n': '{{ route("tickets.create") }}',
                    'p': '{{ route("projects.index") }}',
                    @if(auth()->user()->role === 'Administrador')
                    'u': '{{ route("users.index") }}',
                    @endif
                    'h': '{{ route("dashboard") }}'
                };
                
                if (quickActions[e.key.toLowerCase()]) {
                    window.location.href = quickActions[e.key.toLowerCase()];
                }
            }
        });

        function navigateCommands(direction) {
            const items = document.querySelectorAll('.command-item');
            if (items.length === 0) return;
            
            // Remove active class from current item
            if (currentCommandIndex >= 0 && currentCommandIndex < items.length) {
                items[currentCommandIndex].classList.remove('active');
            }
            
            // Update index
            currentCommandIndex += direction;
            if (currentCommandIndex < 0) currentCommandIndex = items.length - 1;
            if (currentCommandIndex >= items.length) currentCommandIndex = 0;
            
            // Add active class to new item
            items[currentCommandIndex].classList.add('active');
            items[currentCommandIndex].scrollIntoView({ block: 'nearest', behavior: 'smooth' });
        }

        function selectCommand() {
            const items = document.querySelectorAll('.command-item');
            if (currentCommandIndex >= 0 && currentCommandIndex < items.length) {
                items[currentCommandIndex].click();
            }
        }

        // Search functionality
        document.getElementById('commandPaletteInput')?.addEventListener('input', function(e) {
            const query = e.target.value.trim();
            
            clearTimeout(searchTimeout);
            
            if (query.length < 2) {
                document.getElementById('searchResultsSection').style.display = 'none';
                document.getElementById('noResults').style.display = 'none';
                return;
            }
            
            searchTimeout = setTimeout(() => {
                searchCommands(query);
            }, 300);
        });

        async function searchCommands(query) {
            try {
                const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
                    headers: {
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });
                
                if (!response.ok) throw new Error('Search failed');
                
                const data = await response.json();
                displaySearchResults(data);
            } catch (error) {
                console.error('Search error:', error);
                document.getElementById('searchResultsSection').style.display = 'none';
                document.getElementById('noResults').style.display = 'block';
            }
        }

        function displaySearchResults(data) {
            const resultsContainer = document.getElementById('searchResults');
            const resultsSection = document.getElementById('searchResultsSection');
            const noResults = document.getElementById('noResults');
            
            let html = '';
            let hasResults = false;
            
            // Display tickets
            if (data.tickets && data.tickets.length > 0) {
                hasResults = true;
                data.tickets.forEach(ticket => {
                    const priorityColors = {
                        'Baja': { bg: '#d1fae5', color: '#10b981' },
                        'Media': { bg: '#dbeafe', color: '#3b82f6' },
                        'Alta': { bg: '#fef3c7', color: '#f59e0b' },
                        'Crítica': { bg: '#fee2e2', color: '#ef4444' }
                    };
                    const colors = priorityColors[ticket.priority] || priorityColors['Media'];
                    
                    html += `
                        <a href="/tickets/${ticket.id}" class="command-item">
                            <div class="command-icon" style="background: ${colors.bg}; color: ${colors.color};">
                                <i class="bi bi-ticket-detailed"></i>
                            </div>
                            <div class="command-content">
                                <div class="command-title">#TK${String(ticket.id).padStart(4, '0')} - ${ticket.title}</div>
                                <div class="command-subtitle">${ticket.state} • ${ticket.priority}</div>
                            </div>
                        </a>
                    `;
                });
            }
            
            // Display projects
            if (data.projects && data.projects.length > 0) {
                hasResults = true;
                data.projects.forEach(project => {
                    html += `
                        <a href="/projects/${project.id}" class="command-item">
                            <div class="command-icon" style="background: #fef3c7; color: #f59e0b;">
                                <i class="bi bi-folder"></i>
                            </div>
                            <div class="command-content">
                                <div class="command-title">${project.name}</div>
                                <div class="command-subtitle">${project.company?.name || 'Sin empresa'}</div>
                            </div>
                        </a>
                    `;
                });
            }
            
            // Display users (only for admins)
            if (data.users && data.users.length > 0) {
                hasResults = true;
                data.users.forEach(user => {
                    html += `
                        <a href="/users/${user.id}" class="command-item">
                            <div class="command-icon" style="background: #d1fae5; color: #10b981;">
                                <i class="bi bi-person"></i>
                            </div>
                            <div class="command-content">
                                <div class="command-title">${user.name}</div>
                                <div class="command-subtitle">${user.email} • ${user.role}</div>
                            </div>
                        </a>
                    `;
                });
            }
            
            if (hasResults) {
                resultsContainer.innerHTML = html;
                resultsSection.style.display = 'block';
                noResults.style.display = 'none';
                currentCommandIndex = -1;
            } else {
                resultsSection.style.display = 'none';
                noResults.style.display = 'block';
            }
        }

        // Loading states para formularios
        document.addEventListener('DOMContentLoaded', function() {
            // Agregar loading state a todos los formularios al enviar
            document.querySelectorAll('form').forEach(form => {
                form.addEventListener('submit', function(e) {
                    const submitBtn = this.querySelector('button[type="submit"]');
                    if (submitBtn && !submitBtn.classList.contains('btn-loading')) {
                        const originalText = submitBtn.innerHTML;
                        submitBtn.classList.add('btn-loading');
                        submitBtn.disabled = true;
                        
                        // Guardar el texto original para restaurarlo si hay error
                        submitBtn.dataset.originalText = originalText;
                        submitBtn.innerHTML = '<span style="visibility: hidden;">' + originalText + '</span>';
                    }
                });
            });
            
            // Loading state para enlaces que causan navegación
            document.querySelectorAll('a[data-loading="true"]').forEach(link => {
                link.addEventListener('click', function() {
                    if (!this.classList.contains('disabled')) {
                        this.classList.add('btn-loading', 'disabled');
                    }
                });
            });
            
            // Confirmar acciones destructivas
            document.querySelectorAll('[data-confirm]').forEach(element => {
                element.addEventListener('click', function(e) {
                    const message = this.dataset.confirm || '¿Estás seguro de realizar esta acción?';
                    if (!confirm(message)) {
                        e.preventDefault();
                        return false;
                    }
                });
            });
            
            // Initialize Bootstrap Tooltips
            const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl, {
                    trigger: 'hover',
                    animation: true,
                    delay: { show: 300, hide: 100 }
                });
            });
        });
        
        // Helper function para mostrar loading en cualquier botón
        function showButtonLoading(button) {
            if (button && !button.classList.contains('btn-loading')) {
                button.dataset.originalText = button.innerHTML;
                button.classList.add('btn-loading');
                button.disabled = true;
                button.innerHTML = '<span style="visibility: hidden;">' + button.dataset.originalText + '</span>';
            }
        }
        
        function hideButtonLoading(button) {
            if (button && button.classList.contains('btn-loading')) {
                button.classList.remove('btn-loading');
                button.disabled = false;
                button.innerHTML = button.dataset.originalText;
            }
        }
    </script>

    <!-- Command Palette Modal -->
    <div id="commandPalette" class="command-palette" style="display: none;">
        <div class="command-palette-backdrop" onclick="closeCommandPalette()"></div>
        <div class="command-palette-container">
            <div class="command-palette-header">
                <i class="bi bi-search"></i>
                <input type="text" 
                       id="commandPaletteInput" 
                       placeholder="Buscar tickets, proyectos, usuarios o ejecutar comandos..."
                       autocomplete="off"
                       autofocus>
                <button class="command-palette-close" onclick="closeCommandPalette()">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>
            
            <div class="command-palette-body">
                <div id="commandPaletteResults" class="command-results">
                    <!-- Quick Actions -->
                    <div class="command-section">
                        <div class="command-section-title">Acciones Rápidas</div>
                        <a href="{{ route('tickets.create') }}" class="command-item">
                            <div class="command-icon" style="background: #dbeafe; color: #3b82f6;">
                                <i class="bi bi-plus-circle"></i>
                            </div>
                            <div class="command-content">
                                <div class="command-title">Crear Nuevo Ticket</div>
                                <div class="command-subtitle">Registrar nueva solicitud</div>
                            </div>
                            <kbd class="command-kbd">N</kbd>
                        </a>
                        
                        <a href="{{ route('projects.index') }}" class="command-item">
                            <div class="command-icon" style="background: #fef3c7; color: #f59e0b;">
                                <i class="bi bi-folder"></i>
                            </div>
                            <div class="command-content">
                                <div class="command-title">Ver Proyectos</div>
                                <div class="command-subtitle">Gestionar proyectos activos</div>
                            </div>
                            <kbd class="command-kbd">P</kbd>
                        </a>
                        
                        @if(auth()->user()->role === 'Administrador')
                        <a href="{{ route('users.index') }}" class="command-item">
                            <div class="command-icon" style="background: #d1fae5; color: #10b981;">
                                <i class="bi bi-people"></i>
                            </div>
                            <div class="command-content">
                                <div class="command-title">Gestionar Usuarios</div>
                                <div class="command-subtitle">Administrar cuentas de usuario</div>
                            </div>
                            <kbd class="command-kbd">U</kbd>
                        </a>
                        @endif
                        
                        <a href="{{ route('dashboard') }}" class="command-item">
                            <div class="command-icon" style="background: #e0e7ff; color: #6366f1;">
                                <i class="bi bi-speedometer2"></i>
                            </div>
                            <div class="command-content">
                                <div class="command-title">Dashboard</div>
                                <div class="command-subtitle">Ver estadísticas generales</div>
                            </div>
                            <kbd class="command-kbd">H</kbd>
                        </a>
                    </div>
                    
                    <!-- Search Results will be inserted here dynamically -->
                    <div id="searchResultsSection" class="command-section" style="display: none;">
                        <div class="command-section-title">Resultados de Búsqueda</div>
                        <div id="searchResults"></div>
                    </div>
                    
                    <div id="noResults" class="command-no-results" style="display: none;">
                        <i class="bi bi-search"></i>
                        <p>No se encontraron resultados</p>
                    </div>
                </div>
            </div>
            
            <div class="command-palette-footer">
                <div class="command-footer-tips">
                    <span><kbd>↑</kbd><kbd>↓</kbd> navegar</span>
                    <span><kbd>Enter</kbd> seleccionar</span>
                    <span><kbd>Esc</kbd> cerrar</span>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Script para manejar logout y sesión expirada -->
    <script>
        // Actualizar token CSRF en el formulario de logout al cargar la página
        document.addEventListener('DOMContentLoaded', function() {
            const csrfToken = document.querySelector('meta[name="csrf-token"]');
            const logoutForm = document.getElementById('logout-form');
            
            if (csrfToken && logoutForm) {
                const tokenInput = logoutForm.querySelector('input[name="_token"]');
                if (tokenInput) {
                    tokenInput.value = csrfToken.getAttribute('content');
                }
            }
            
            // Capturar errores de fetch/ajax para detectar sesión expirada
            window.addEventListener('unhandledrejection', function(event) {
                if (event.reason && event.reason.status === 419) {
                    window.location.href = "{{ route('login') }}";
                }
            });
        });
    </script>
    
    @stack('scripts')
</body>
</html>
