<script lang="ts">
  import Modal from '$lib/components/Modal.svelte';
  import { auth } from '$lib/stores/auth';
  import { toast } from '$lib/stores/toast';
  import { api } from '$lib/utils/api';
  import { onMount } from 'svelte';

  // Estado de carga y datos
  let logs: any[] = [];
  let stats: any = null;
  let users: any[] = [];
  let incidents: any[] = [];
  let securityAnalysis: any = null;
  let isLoading = false;
  let isLoadingIncidents = false;
  let selectedLog: any = null;
  let selectedIncident: any = null;
  let showDetailModal = false;
  let showIncidentModal = false;

  // Paginación
  let currentPage = 1;
  let totalPages = 1;
  let totalLogs = 0;
  const perPage = 20;

  // Paginación de incidentes
  let incidentsPage = 1;
  let incidentsTotalPages = 1;
  let totalIncidents = 0;
  const incidentsPerPage = 10;

  // Filtros básicos
  let filterUserId = '';
  let filterAction = '';
  let filterResourceType = '';
  let searchText = '';

  // Filtros de incidentes
  let filterSeverity = '';
  let filterIncidentType = '';
  let filterStatus = '';
  let incidentSearchText = '';

  // Filtro multi-tenant (solo para ADMIN/SUPPORT_MANAGER)
  let allTenants = false;

  // Filtro de período
  let periodFilter: 'today' | 'yesterday' | 'last7days' | 'last30days' | 'custom' = 'today';
  let customDateFrom = '';
  let customDateTo = '';

  // Control de visibilidad de filtros avanzados
  let showAdvancedFilters = false;

  // Usuario actual
  $: currentUser = $auth.user;
  $: canSeeAllTenants =
    currentUser && (currentUser.role === 'ADMIN' || currentUser.role === 'SUPPORT_MANAGER');

  // Contador de filtros activos (excluyendo el período que es por defecto)
  $: activeFiltersCount = [filterUserId, filterAction, filterResourceType, searchText].filter(
    f => f && f.trim()
  ).length;

  // Configuración de tarjetas estadísticas
  $: statsCards = [
    {
      label: 'Total de Registros',
      value: stats?.total_actions,
      icon: 'clipboard',
      color: 'gray',
      desc: 'Todas las acciones registradas'
    },
    {
      label: 'Actividad Hoy',
      value: stats?.actions_today,
      icon: 'zap',
      color: 'blue',
      desc: 'Registros del día actual'
    },
    {
      label: 'Esta Semana',
      value: stats?.actions_this_week,
      icon: 'calendar',
      color: 'indigo',
      desc: 'Últimos 7 días de actividad'
    },
    {
      label: 'Incidentes Críticos',
      value: stats?.critical_actions_today || 0,
      icon: 'alert',
      color: 'red',
      desc: 'Requieren atención inmediata',
      action: true
    }
  ];

  // Configuración de botones de período
  const periodButtons: Array<{
    id: 'today' | 'yesterday' | 'last7days' | 'last30days' | 'custom';
    label: string;
    icon?: boolean;
  }> = [
    { id: 'today', label: 'Hoy' },
    { id: 'yesterday', label: 'Ayer' },
    { id: 'last7days', label: 'Últimos 7 días' },
    { id: 'last30days', label: 'Últimos 30 días' },
    { id: 'custom', label: 'Personalizado', icon: true }
  ];

  // Tipos de acciones y recursos (extraídos de los logs)
  let availableActions = new Set<string>();
  let availableResourceTypes = new Set<string>();

  /**
   * Obtener fechas según el período seleccionado
   */
  function getDateRangeForPeriod(): { from: string; to: string } {
    // Trabajar en UTC para evitar problemas de zona horaria
    const now = new Date();

    let from: Date;
    let to: Date;

    switch (periodFilter) {
      case 'today':
        // Hoy desde las 00:00:00 hasta ahora en UTC
        from = new Date(
          Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), 0, 0, 0)
        );
        to = new Date(); // Ahora en UTC
        break;
      case 'yesterday':
        // Ayer completo en UTC
        from = new Date(
          Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - 1, 0, 0, 0)
        );
        to = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), 0, 0, 0));
        break;
      case 'last7days':
        // Últimos 7 días en UTC
        from = new Date(
          Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - 7, 0, 0, 0)
        );
        to = new Date();
        break;
      case 'last30days':
        // Últimos 30 días en UTC
        from = new Date(
          Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - 30, 0, 0, 0)
        );
        to = new Date();
        break;
      case 'custom':
        // Para fechas custom, parsear como UTC
        if (!customDateFrom || !customDateTo) {
          return { from: '', to: '' };
        }
        const fromParts = customDateFrom.split('-').map(Number);
        const toParts = customDateTo.split('-').map(Number);
        from = new Date(Date.UTC(fromParts[0], fromParts[1] - 1, fromParts[2], 0, 0, 0));
        to = new Date(Date.UTC(toParts[0], toParts[1] - 1, toParts[2], 23, 59, 59));
        return {
          from: from.toISOString(),
          to: to.toISOString()
        };
      default:
        from = new Date(
          Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), 0, 0, 0)
        );
        to = new Date();
    }

    return {
      from: from.toISOString(),
      to: to.toISOString()
    };
  }

  /**
   * Cambiar período y actualizar datos
   */
  function changePeriod(period: typeof periodFilter) {
    periodFilter = period;
    currentPage = 1;
    loadLogs();
  }

  /**
   * Cargar estadísticas de auditoría
   */
  async function loadStats() {
    try {
      const params: any = {};
      if (allTenants && canSeeAllTenants) {
        params.all_tenants = true;
      }
      stats = await api.get('/audit/stats', params);
    } catch (e: any) {
      console.error('Error cargando estadísticas:', e);
    }
  }

  /**
   * Cargar incidentes de seguridad
   */
  async function loadIncidents() {
    isLoadingIncidents = true;
    try {
      const params: any = {
        page: incidentsPage,
        per_page: incidentsPerPage
      };

      // Aplicar filtros de incidentes
      if (filterSeverity) params.severity = filterSeverity;
      if (filterIncidentType) params.type = filterIncidentType;
      if (filterStatus) params.status = filterStatus;
      if (incidentSearchText) params.search = incidentSearchText;

      // Aplicar filtro multi-tenant si el usuario tiene permiso
      if (allTenants && canSeeAllTenants) {
        params.all_tenants = true;
      }

      const response: any = await api.get('/audit/security/incidents', params);

      incidents = response.incidents || [];
      totalIncidents = response.total || 0;
      incidentsTotalPages = response.total_pages || 1;
      incidentsPage = response.page || 1;
    } catch (e: any) {
      console.error('Error cargando incidentes:', e);
      incidents = [];
    } finally {
      isLoadingIncidents = false;
    }
  }

  /**
   * Cargar análisis de seguridad
   */
  async function loadSecurityAnalysis() {
    try {
      const params: any = { hours: 24 };
      if (allTenants && canSeeAllTenants) {
        params.all_tenants = true;
      }
      securityAnalysis = await api.get('/audit/security/analysis', params);
    } catch (e: any) {
      console.error('Error cargando análisis de seguridad:', e);
    }
  }

  /**
   * Cargar logs de auditoría con filtros
   */
  async function loadLogs() {
    isLoading = true;
    try {
      const params: any = {
        page: currentPage,
        per_page: perPage
      };

      // Aplicar rango de fechas según período
      const dateRange = getDateRangeForPeriod();
      if (dateRange.from) params.date_from = dateRange.from;
      if (dateRange.to) params.date_to = dateRange.to;

      // Aplicar filtros adicionales
      if (filterUserId) params.user_id = filterUserId;
      if (filterAction) params.action = filterAction;
      if (filterResourceType) params.resource_type = filterResourceType;
      if (searchText) params.search = searchText;

      // Aplicar filtro multi-tenant si el usuario tiene permiso
      if (allTenants && canSeeAllTenants) {
        params.all_tenants = true;
      }

      const response: any = await api.get('/audit/', params);

      logs = response.logs;
      totalLogs = response.total;
      totalPages = response.total_pages;
      currentPage = response.page;

      // Extraer acciones y tipos de recursos únicos para los selectores
      logs.forEach((log: any) => {
        availableActions.add(log.action);
        availableResourceTypes.add(log.resource_type);
      });

      // Convertir Sets a Arrays para bind:value
      availableActions = new Set(availableActions);
      availableResourceTypes = new Set(availableResourceTypes);
    } catch (e: any) {
      toast.error('Error cargando logs: ' + (e.message || 'Error desconocido'));
    } finally {
      isLoading = false;
    }
  }

  /**
   * Cargar usuarios para el filtro
   */
  async function loadUsers() {
    try {
      users = (await api.get('/users/')) as any[];
    } catch (e: any) {
      console.error('Error cargando usuarios:', e);
      users = [];
    }
  }

  /**
   * Aplicar filtros y recargar desde página 1
   */
  function applyFilters() {
    currentPage = 1;
    loadLogs();
  }

  /**
   * Limpiar todos los filtros (excepto el período)
   */
  function clearFilters() {
    filterUserId = '';
    filterAction = '';
    filterResourceType = '';
    searchText = '';
    currentPage = 1;
    loadLogs();
  }

  /**
   * Filtrar por acciones críticas (vulnerabilidad)
   */
  function filterCriticalActions() {
    // Aplicar filtro de severidad crítica en incidentes
    filterSeverity = 'critical';
    filterStatus = '';
    filterIncidentType = '';
    incidentSearchText = '';

    // Recargar incidentes con el filtro
    incidentsPage = 1;
    loadIncidents();

    // Hacer scroll suave a la sección de incidentes
    setTimeout(() => {
      const incidentsSection = document.getElementById('incidents-section');
      if (incidentsSection) {
        incidentsSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    }, 100);
  }

  /**
   * Cambiar página
   */
  function goToPage(page: number) {
    if (page >= 1 && page <= totalPages) {
      currentPage = page;
      loadLogs();
    }
  }

  /**
   * Ver detalle de un log
   */
  function viewDetail(log: any) {
    selectedLog = log;
    showDetailModal = true;
  }

  /**
   * Formatear fecha de manera amigable
   */
  function formatDate(dateString: string): string {
    const date = new Date(dateString);
    return date.toLocaleString('es-MX', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  }

  /**
   * Formatear fecha corta (solo hora para hoy)
   */
  function formatDateShort(dateString: string): string {
    const date = new Date(dateString);
    const today = new Date();
    const isToday = date.toDateString() === today.toDateString();

    if (isToday) {
      return date.toLocaleTimeString('es-MX', {
        hour: '2-digit',
        minute: '2-digit'
      });
    }

    return date.toLocaleDateString('es-MX', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  }

  /**
   * Obtener color de badge según tipo de acción
   */
  function getActionColor(action: string): string {
    if (action.includes('delete')) return 'bg-red-600 text-white';
    if (action.includes('update')) return 'bg-blue-600 text-white';
    if (action.includes('login') || action.includes('logout')) return 'bg-indigo-600 text-white';
    if (action.includes('create')) return 'bg-green-600 text-white';
    return 'bg-gray-600 text-white';
  }

  /**
   * Obtener color de severidad
   */
  function getSeverityColor(severity: string): string {
    switch (severity?.toLowerCase()) {
      case 'critical':
        return 'bg-red-600 text-white';
      case 'high':
        return 'bg-orange-600 text-white';
      case 'medium':
        return 'bg-yellow-500 text-white';
      case 'low':
        return 'bg-blue-600 text-white';
      default:
        return 'bg-gray-600 text-white';
    }
  }

  /**
   * Obtener color de estado
   */
  function getStatusColor(status: string): string {
    switch (status?.toLowerCase()) {
      case 'active':
      case 'open':
        return 'bg-blue-600 text-white';
      case 'resolved':
      case 'closed':
        return 'bg-green-600 text-white';
      case 'investigating':
        return 'bg-yellow-500 text-white';
      default:
        return 'bg-gray-600 text-white';
    }
  }

  /**
   * Formatear acción de forma legible
   */
  function formatActionText(action: string): string {
    const parts = action.split('.');
    if (parts.length !== 2) return action;

    const [resource, verb] = parts;

    const verbMap: Record<string, string> = {
      login: 'Inicio de sesión',
      logout: 'Cierre de sesión',
      create: 'Creó',
      update: 'Actualizó',
      delete: 'Eliminó',
      assign: 'Asignó',
      close: 'Cerró',
      reopen: 'Reabrió'
    };

    const verbText = verbMap[verb] || verb;
    return `${verbText} ${resource}`;
  }

  /**
   * Obtener texto del rol
   */
  function getRoleText(role: string): string {
    const roleMap: Record<string, string> = {
      ADMIN: 'Administrador',
      SUPPORT_MANAGER: 'Gerente',
      AGENT: 'Agente',
      AUDITOR: 'Auditor',
      CLIENT_ADMIN: 'Admin Cliente',
      CLIENT_USER: 'Usuario'
    };
    return roleMap[role] || role;
  }

  /**
   * Ver detalle de un incidente
   */
  function viewIncidentDetail(incident: any) {
    selectedIncident = incident;
    showIncidentModal = true;
  }

  /**
   * Aplicar filtros de incidentes y recargar desde página 1
   */
  function applyIncidentFilters() {
    incidentsPage = 1;
    loadIncidents();
  }

  /**
   * Limpiar filtros de incidentes
   */
  function clearIncidentFilters() {
    filterSeverity = '';
    filterIncidentType = '';
    filterStatus = '';
    incidentSearchText = '';
    incidentsPage = 1;
    loadIncidents();
  }

  /**
   * Cambiar página de incidentes
   */
  function goToIncidentsPage(page: number) {
    if (page >= 1 && page <= incidentsTotalPages) {
      incidentsPage = page;
      loadIncidents();
    }
  }

  /**
   * Formatear fecha simple
   */
  function formatSimpleDate(dateString: string): string {
    const date = new Date(dateString);
    return date.toLocaleDateString('es-MX', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  }

  /**
   * Inicializar datos
   */
  onMount(() => {
    loadStats();
    loadUsers();
    loadLogs();
    loadIncidents();
    loadSecurityAnalysis();
  });
</script>

<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
  <!-- Encabezado -->
  <div class="mb-8">
    <h1 class="text-3xl font-bold text-gray-900 mb-2">Auditoría y Seguridad</h1>
    <p class="text-gray-600">
      Monitoreo de actividades, análisis de seguridad e incidentes críticos
    </p>
  </div>

  <!-- Selector de Período -->
  <div class="bg-white shadow-sm rounded-lg p-6 mb-8 border border-gray-200">
    <h3 class="text-sm font-semibold text-gray-700 mb-3">Período de Consulta</h3>
    <div class="flex flex-wrap gap-2">
      {#each periodButtons as btn}
        <button
          on:click={() => changePeriod(btn.id)}
          class="px-4 py-2 rounded-lg text-sm font-medium transition-colors {periodFilter === btn.id
            ? 'bg-indigo-600 text-white'
            : 'bg-gray-100 text-gray-700 hover:bg-indigo-50'}"
        >
          {#if btn.icon}
            <svg
              class="w-4 h-4 inline-block mr-1"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
              />
            </svg>
          {/if}
          {btn.label}
        </button>
      {/each}
    </div>

    {#if periodFilter === 'custom'}
      <div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t">
        <div>
          <label for="custom-date-from" class="block text-sm font-medium text-gray-700 mb-1"
            >Desde</label
          >
          <input
            type="date"
            id="custom-date-from"
            bind:value={customDateFrom}
            on:change={applyFilters}
            class="block w-full rounded-md border-gray-300 shadow-sm focus:border-gray-500 focus:ring-gray-500 sm:text-sm"
          />
        </div>
        <div>
          <label for="custom-date-to" class="block text-sm font-medium text-gray-700 mb-1"
            >Hasta</label
          >
          <input
            type="date"
            id="custom-date-to"
            bind:value={customDateTo}
            on:change={applyFilters}
            class="block w-full rounded-md border-gray-300 shadow-sm focus:border-gray-500 focus:ring-gray-500 sm:text-sm"
          />
        </div>
      </div>
    {/if}
  </div>

  <!-- Multi-tenant Toggle -->
  {#if canSeeAllTenants}
    <div class="bg-white shadow-sm rounded-lg p-6 mb-8 border border-gray-200">
      <h3 class="text-sm font-semibold text-gray-700 mb-4">Alcance de Visualización</h3>
      <div class="flex items-center justify-between">
        <div class="flex items-center">
          <label for="all-tenants-toggle" class="flex items-center cursor-pointer">
            <input
              type="checkbox"
              id="all-tenants-toggle"
              bind:checked={allTenants}
              on:change={() => {
                currentPage = 1;
                loadLogs();
                loadStats();
              }}
              class="rounded border-gray-300 text-gray-600 shadow-sm focus:border-gray-500 focus:ring-gray-500 h-4 w-4 mr-3"
            />
            <div>
              <span class="text-sm font-medium text-gray-900">Ver todos los clientes</span>
              <p class="text-xs text-gray-500">
                Mostrar registros de auditoría de todas las organizaciones
              </p>
            </div>
          </label>
        </div>
        {#if allTenants}
          <span
            class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-200 text-gray-800"
          >
            <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
              <path
                d="M10 2a8 8 0 100 16 8 8 0 000-16zM9 9a1 1 0 012 0v4a1 1 0 11-2 0V9zm1-5a1 1 0 100 2 1 1 0 000-2z"
              />
            </svg>
            Multi-tenant activo
          </span>
        {/if}
      </div>
    </div>
  {/if}

  <!-- Estadísticas Generales -->
  {#if stats}
    <div class="mb-8">
      <h2 class="text-xl font-semibold text-gray-900 mb-4">Resumen de Actividad</h2>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {#each statsCards as card}
          <div
            class="bg-white rounded-lg shadow-sm border {card.color === 'red'
              ? 'border-red-200 bg-gradient-to-br from-red-50 to-orange-50 border-2'
              : 'border-' + card.color + '-200'} p-5 hover:shadow-md transition-all"
          >
            <div class="flex items-center gap-2 mb-2">
              <div
                class="p-2 rounded-lg {card.color === 'gray'
                  ? 'bg-gray-100'
                  : 'bg-' + card.color + '-50'}"
              >
                {#if card.icon === 'clipboard'}
                  <svg
                    class="w-5 h-5 text-{card.color}-600"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                    ><path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"
                    /></svg
                  >
                {:else if card.icon === 'zap'}
                  <svg
                    class="w-5 h-5 text-{card.color}-600"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                    ><path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M13 10V3L4 14h7v7l9-11h-7z"
                    /></svg
                  >
                {:else if card.icon === 'calendar'}
                  <svg
                    class="w-5 h-5 text-{card.color}-600"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                    ><path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
                    /></svg
                  >
                {:else if card.icon === 'alert'}
                  <svg
                    class="w-5 h-5 text-{card.color}-600"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                    ><path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
                    /></svg
                  >
                {/if}
              </div>
              <span
                class="text-sm font-medium text-{card.color === 'gray'
                  ? 'gray-600'
                  : card.color + '-' + (card.color === 'red' ? '700' : '600')}">{card.label}</span
              >
            </div>
            <div class="flex items-center justify-between">
              <div
                class="text-3xl font-bold text-{card.color === 'gray'
                  ? 'gray-900'
                  : card.color + '-600'}"
              >
                {card.value?.toLocaleString() || 0}
              </div>
              {#if card.action}
                <button
                  type="button"
                  class="px-3 py-1.5 bg-red-600 text-white text-xs font-medium rounded-lg hover:bg-red-700 transition-colors flex items-center gap-1"
                  on:click={() => filterCriticalActions()}
                  title="Ver incidentes críticos"
                >
                  Ver detalles
                  <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                    ><path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M9 5l7 7-7 7"
                    /></svg
                  >
                </button>
              {/if}
            </div>
            <p
              class="text-xs text-{card.color === 'red' ? 'red-700 font-medium' : 'gray-500'} mt-1"
            >
              {card.desc}
            </p>
          </div>
        {/each}
      </div>
    </div>
  {/if}

  <!-- Filtros Avanzados -->
  <div class="bg-white shadow-sm rounded-lg mb-8 border border-gray-200 overflow-hidden">
    <button
      on:click={() => (showAdvancedFilters = !showAdvancedFilters)}
      class="w-full px-6 py-4 flex items-center justify-between text-left hover:bg-gray-50 transition-colors"
    >
      <div class="flex items-center gap-3">
        <div class="p-2 bg-gray-100 rounded-lg">
          <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"
            />
          </svg>
        </div>
        <div>
          <span class="text-base font-semibold text-gray-900">Filtros Avanzados</span>
          {#if activeFiltersCount > 0}
            <span
              class="ml-2 px-2.5 py-1 bg-indigo-100 text-indigo-800 text-xs font-semibold rounded-full"
            >
              {activeFiltersCount}
            </span>
          {/if}
        </div>
      </div>
      <svg
        class="w-5 h-5 text-gray-400 transition-transform {showAdvancedFilters ? 'rotate-180' : ''}"
        fill="none"
        stroke="currentColor"
        viewBox="0 0 24 24"
      >
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
      </svg>
    </button>

    {#if showAdvancedFilters}
      <div class="px-4 pb-4 border-t">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mt-4">
          <div>
            <label for="search" class="block text-sm font-medium text-gray-700 mb-1">Buscar</label>
            <input
              type="text"
              id="search"
              bind:value={searchText}
              on:input={applyFilters}
              placeholder="Buscar en acciones..."
              class="block w-full px-4 py-2.5 rounded-lg border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition-all text-sm"
            />
          </div>

          <div>
            <label for="user" class="block text-sm font-medium text-gray-700 mb-1">Usuario</label>
            <select
              id="user"
              bind:value={filterUserId}
              on:change={applyFilters}
              class="block w-full rounded-md border-gray-300 shadow-sm focus:border-gray-500 focus:ring-gray-500 sm:text-sm"
            >
              <option value="">Todos</option>
              {#each users as user}
                <option value={user.id}>{user.first_name} {user.last_name}</option>
              {/each}
            </select>
          </div>

          <div>
            <label for="action" class="block text-sm font-medium text-gray-700 mb-1">Acción</label>
            <select
              id="action"
              bind:value={filterAction}
              on:change={applyFilters}
              class="block w-full rounded-md border-gray-300 shadow-sm focus:border-gray-500 focus:ring-gray-500 sm:text-sm"
            >
              <option value="">Todas</option>
              {#each Array.from(availableActions).sort() as action}
                <option value={action}>{formatActionText(action)}</option>
              {/each}
            </select>
          </div>

          <div>
            <label for="resource-type" class="block text-sm font-medium text-gray-700 mb-1"
              >Tipo de Recurso</label
            >
            <select
              id="resource-type"
              bind:value={filterResourceType}
              on:change={applyFilters}
              class="block w-full rounded-md border-gray-300 shadow-sm focus:border-gray-500 focus:ring-gray-500 sm:text-sm"
            >
              <option value="">Todos</option>
              {#each Array.from(availableResourceTypes).sort() as resourceType}
                <option value={resourceType}>{resourceType}</option>
              {/each}
            </select>
          </div>
        </div>

        {#if activeFiltersCount > 0}
          <div class="mt-4 flex justify-end">
            <button
              on:click={clearFilters}
              class="text-sm text-gray-600 hover:text-gray-800 font-medium"
            >
              Limpiar filtros
            </button>
          </div>
        {/if}
      </div>
    {/if}
  </div>

  <!-- Análisis de Seguridad - Tarjeta Resumen con Enlace -->
  {#if securityAnalysis}
    <div class="mb-8">
      <a
        href="/audit/security"
        class="block bg-gradient-to-br from-indigo-500 to-purple-600 rounded-lg shadow-md hover:shadow-xl transition-all overflow-hidden group"
      >
        <div class="p-6">
          <div class="flex items-center justify-between mb-4">
            <div class="flex items-center gap-3">
              <div class="p-3 bg-white/20 backdrop-blur-sm rounded-lg">
                <svg
                  class="w-8 h-8 text-white"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"
                  />
                </svg>
              </div>
              <div>
                <h2 class="text-2xl font-bold text-white">Análisis de Seguridad Completo</h2>
                <p class="text-indigo-100 text-sm">
                  Panel especializado de amenazas, riesgos y acciones
                </p>
              </div>
            </div>
            <div class="flex items-center gap-3">
              <div class="text-right">
                <div
                  class="px-4 py-2 rounded-lg {securityAnalysis.overall_risk_level === 'critical'
                    ? 'bg-red-500'
                    : securityAnalysis.overall_risk_level === 'high'
                    ? 'bg-orange-500'
                    : securityAnalysis.overall_risk_level === 'medium'
                    ? 'bg-yellow-400'
                    : 'bg-green-500'} shadow-lg"
                >
                  <span class="font-bold text-white text-lg uppercase"
                    >{securityAnalysis.overall_risk_level}</span
                  >
                </div>
              </div>
              <svg
                class="w-6 h-6 text-white group-hover:translate-x-1 transition-transform"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M9 5l7 7-7 7"
                />
              </svg>
            </div>
          </div>

          <div class="grid grid-cols-3 gap-4">
            <div class="bg-white/10 backdrop-blur-sm rounded-lg p-4">
              <div class="text-3xl font-bold text-white mb-1">
                {securityAnalysis.failed_login_attempts}
              </div>
              <p class="text-indigo-100 text-xs">Intentos fallidos</p>
            </div>
            <div class="bg-white/10 backdrop-blur-sm rounded-lg p-4">
              <div class="text-3xl font-bold text-white mb-1">
                {securityAnalysis.suspicious_ips_count}
              </div>
              <p class="text-indigo-100 text-xs">IPs sospechosas</p>
            </div>
            <div class="bg-white/10 backdrop-blur-sm rounded-lg p-4">
              <div class="text-3xl font-bold text-white mb-1">
                {securityAnalysis.total_threats_detected || 0}
              </div>
              <p class="text-indigo-100 text-xs">Amenazas detectadas</p>
            </div>
          </div>

          <div class="mt-4 flex items-center justify-center gap-2 text-white font-medium">
            <span>Ir al análisis detallado de seguridad</span>
            <svg
              class="w-5 h-5 group-hover:translate-x-2 transition-transform"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M13 7l5 5m0 0l-5 5m5-5H6"
              />
            </svg>
          </div>
        </div>
      </a>
    </div>
  {/if}

  <!-- Incidentes de Seguridad -->
  <div id="incidents-section" class="mb-8 scroll-mt-6">
    <h2 class="text-xl font-semibold text-gray-900 mb-4">Incidentes de Seguridad</h2>
    <div class="bg-white shadow-sm rounded-lg border border-gray-200">
      <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-2">
            <svg
              class="w-5 h-5 text-gray-600"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
              />
            </svg>
            <span class="text-sm font-medium text-gray-700">Eventos de seguridad detectados</span>
          </div>
          <div class="flex items-center gap-2">
            <span class="px-3 py-1 bg-gray-100 text-gray-700 text-sm font-medium rounded-full"
              >{totalIncidents} incidentes</span
            >
          </div>
        </div>
      </div>

      <div class="px-6 py-4 border-b border-gray-200">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <input
            type="text"
            placeholder="Buscar incidentes..."
            bind:value={incidentSearchText}
            on:input={applyIncidentFilters}
            class="block w-full px-4 py-2.5 rounded-lg border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition-all text-sm"
          />
          <select
            bind:value={filterSeverity}
            on:change={applyIncidentFilters}
            class="block w-full px-4 py-2.5 rounded-lg border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition-all text-sm"
          >
            <option value="">Toda severidad</option>
            <option value="critical">Crítico</option>
            <option value="high">Alto</option>
            <option value="medium">Medio</option>
            <option value="low">Bajo</option>
          </select>
          <select
            bind:value={filterStatus}
            on:change={applyIncidentFilters}
            class="block w-full px-4 py-2.5 rounded-lg border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition-all text-sm"
          >
            <option value="">Todo estado</option>
            <option value="active">Activo</option>
            <option value="investigating">Investigando</option>
            <option value="resolved">Resuelto</option>
          </select>
          <button
            type="button"
            on:click={clearIncidentFilters}
            class="px-4 py-2.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors text-sm font-medium flex items-center gap-2"
          >
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
            Limpiar
          </button>
        </div>
      </div>

      <div class="overflow-x-auto">
        {#if isLoadingIncidents}
          <div class="flex flex-col items-center justify-center p-12">
            <div
              class="animate-spin rounded-full h-10 w-10 border-4 border-indigo-200 border-t-indigo-600"
            />
            <span class="mt-3 text-sm font-medium text-gray-600">Cargando incidentes...</span>
          </div>
        {:else if incidents.length === 0}
          <div class="text-center py-12">
            <div
              class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4"
            >
              <svg
                class="w-8 h-8 text-gray-400"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
                />
              </svg>
            </div>
            <h3 class="text-base font-semibold text-gray-900">No hay incidentes</h3>
            <p class="mt-2 text-sm text-gray-500">
              No se encontraron incidentes de seguridad para los filtros seleccionados.
            </p>
          </div>
        {:else}
          <div class="divide-y divide-gray-200">
            {#each incidents as incident (incident.id)}
              <button
                type="button"
                class="w-full text-left p-5 hover:bg-gray-50 transition-colors focus:outline-none focus:bg-gray-50"
                on:click={() => viewIncidentDetail(incident)}
              >
                <div class="flex items-start justify-between gap-4">
                  <div class="flex items-start gap-4 flex-1 min-w-0">
                    <div class="flex-shrink-0 mt-0.5">
                      <div
                        class="p-2 rounded-lg {incident.severity === 'critical'
                          ? 'bg-red-100'
                          : incident.severity === 'high'
                          ? 'bg-orange-100'
                          : 'bg-yellow-100'}"
                      >
                        <svg
                          class="w-5 h-5 {incident.severity === 'critical'
                            ? 'text-red-600'
                            : incident.severity === 'high'
                            ? 'text-orange-600'
                            : 'text-yellow-600'}"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            stroke-width="2"
                            d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
                          />
                        </svg>
                      </div>
                    </div>
                    <div class="min-w-0 flex-1">
                      <p class="text-sm font-semibold text-gray-900 mb-1">{incident.title}</p>
                      <p class="text-sm text-gray-600 line-clamp-2">
                        {incident.description || 'Sin descripción'}
                      </p>
                    </div>
                  </div>
                  <div class="flex flex-col items-end gap-2 flex-shrink-0">
                    <span
                      class="px-3 py-1 text-xs font-bold rounded-full {getSeverityColor(
                        incident.severity
                      )}"
                    >
                      {incident.severity?.toUpperCase()}
                    </span>
                    <span
                      class="px-3 py-1 text-xs font-semibold rounded-full {getStatusColor(
                        incident.status
                      )}"
                    >
                      {incident.status?.toUpperCase()}
                    </span>
                    <span class="text-xs text-gray-500 font-medium">
                      {formatSimpleDate(incident.created_at)}
                    </span>
                  </div>
                </div>
              </button>
            {/each}
          </div>

          {#if incidentsTotalPages > 1}
            <div
              class="px-6 py-4 border-t border-gray-200 bg-gray-50 flex items-center justify-between"
            >
              <div class="text-sm font-medium text-gray-700">
                Página <span class="text-indigo-600">{incidentsPage}</span> de
                <span class="text-gray-900">{incidentsTotalPages}</span>
              </div>
              <div class="flex gap-2">
                <button
                  type="button"
                  on:click={() => goToIncidentsPage(incidentsPage - 1)}
                  disabled={incidentsPage === 1}
                  class="px-4 py-2 text-sm font-medium bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center gap-1"
                >
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M15 19l-7-7 7-7"
                    />
                  </svg>
                  Anterior
                </button>
                <button
                  type="button"
                  on:click={() => goToIncidentsPage(incidentsPage + 1)}
                  disabled={incidentsPage === incidentsTotalPages}
                  class="px-4 py-2 text-sm font-medium bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center gap-1"
                >
                  Siguiente
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M9 5l7 7-7 7"
                    />
                  </svg>
                </button>
              </div>
            </div>
          {/if}
        {/if}
      </div>
    </div>

    <!-- Registros de Auditoría -->
    <div class="mb-8">
      <h2 class="text-xl font-semibold text-gray-900 mb-4">Registros de Auditoría</h2>
      <div
        class="bg-white shadow-sm rounded-lg border border-gray-200 overflow-hidden flex flex-col"
        style="max-height: calc(100vh - 500px); min-height: 400px;"
      >
        <div
          class="px-6 py-4 border-b border-gray-200 bg-gradient-to-r from-gray-50 to-white flex-shrink-0"
        >
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-3">
              <div class="p-2 bg-white rounded-lg shadow-sm">
                <svg
                  class="w-5 h-5 text-gray-600"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"
                  />
                </svg>
              </div>
              <span class="text-sm font-medium text-gray-700"
                >Historial completo de actividades</span
              >
              <span class="px-3 py-1 bg-indigo-50 text-indigo-700 text-sm font-medium rounded-full"
                >{totalLogs} registros</span
              >
            </div>
            <button
              type="button"
              on:click={loadLogs}
              class="px-4 py-2 bg-white border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors flex items-center gap-2"
            >
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                />
              </svg>
              Actualizar
            </button>
          </div>
        </div>

        {#if isLoading}
          <div class="flex items-center justify-center flex-1">
            <div class="text-center">
              <div
                class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mx-auto"
              />
              <p class="mt-2 text-sm text-gray-500">Cargando registros...</p>
            </div>
          </div>
        {:else if logs.length === 0}
          <div class="flex items-center justify-center flex-1">
            <div class="text-center py-12">
              <svg
                class="mx-auto h-12 w-12 text-gray-400"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"
                />
              </svg>
              <h3 class="mt-2 text-sm font-medium text-gray-900">No hay registros</h3>
              <p class="mt-1 text-sm text-gray-500">
                {periodFilter === 'today'
                  ? 'No hay actividad registrada hoy.'
                  : 'No se encontraron registros para el período seleccionado.'}
              </p>
            </div>
          </div>
        {:else}
          <div class="overflow-y-auto flex-1">
            <div class="hidden lg:block">
              <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50 sticky top-0 z-10">
                  <tr>
                    <th
                      scope="col"
                      class="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider w-28"
                    >
                      Hora
                    </th>
                    <th
                      scope="col"
                      class="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider"
                    >
                      Usuario
                    </th>
                    <th
                      scope="col"
                      class="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider"
                    >
                      Acción
                    </th>
                    <th
                      scope="col"
                      class="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider"
                    >
                      Recurso
                    </th>
                    <th scope="col" class="relative px-4 py-3 w-24 text-center">
                      <span class="text-xs font-semibold text-gray-700 uppercase tracking-wider"
                        >Acciones</span
                      >
                    </th>
                  </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                  {#each logs as log (log.id)}
                    <tr class="hover:bg-gray-50 transition-colors">
                      <td class="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900">
                        {formatDateShort(log.created_at)}
                      </td>
                      <td class="px-4 py-3 text-sm">
                        {#if log.user_email}
                          <div class="flex items-center gap-3">
                            <div
                              class="flex-shrink-0 w-9 h-9 bg-gradient-to-br from-indigo-400 to-indigo-600 rounded-full flex items-center justify-center shadow-sm"
                            >
                              <span class="text-xs font-semibold text-white">
                                {(log.user_name || '?').charAt(0).toUpperCase()}
                              </span>
                            </div>
                            <div class="min-w-0 flex-1">
                              <div class="font-medium text-gray-900 truncate">
                                {log.user_name || 'N/A'}
                              </div>
                              <div class="text-xs text-gray-500">{getRoleText(log.user_role)}</div>
                            </div>
                          </div>
                        {:else}
                          <div class="flex items-center gap-2">
                            <svg
                              class="w-5 h-5 text-gray-400"
                              fill="none"
                              stroke="currentColor"
                              viewBox="0 0 24 24"
                            >
                              <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
                              /><path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                              />
                            </svg>
                            <span class="text-gray-600 font-medium italic">Sistema</span>
                          </div>
                        {/if}
                      </td>
                      <td class="px-4 py-3 whitespace-nowrap">
                        <div class="flex items-center gap-2">
                          {#if log.action === 'CREATE'}
                            <div class="p-1.5 bg-green-50 rounded-lg">
                              <svg
                                class="w-4 h-4 text-green-600"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                              >
                                <path
                                  stroke-linecap="round"
                                  stroke-linejoin="round"
                                  stroke-width="2"
                                  d="M12 4v16m8-8H4"
                                />
                              </svg>
                            </div>
                          {:else if log.action === 'UPDATE'}
                            <div class="p-1.5 bg-blue-50 rounded-lg">
                              <svg
                                class="w-4 h-4 text-blue-600"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                              >
                                <path
                                  stroke-linecap="round"
                                  stroke-linejoin="round"
                                  stroke-width="2"
                                  d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
                                />
                              </svg>
                            </div>
                          {:else if log.action === 'DELETE'}
                            <div class="p-1.5 bg-red-50 rounded-lg">
                              <svg
                                class="w-4 h-4 text-red-600"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                              >
                                <path
                                  stroke-linecap="round"
                                  stroke-linejoin="round"
                                  stroke-width="2"
                                  d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                                />
                              </svg>
                            </div>
                          {:else if log.action === 'LOGIN'}
                            <div class="p-1.5 bg-indigo-50 rounded-lg">
                              <svg
                                class="w-4 h-4 text-indigo-600"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                              >
                                <path
                                  stroke-linecap="round"
                                  stroke-linejoin="round"
                                  stroke-width="2"
                                  d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"
                                />
                              </svg>
                            </div>
                          {:else if log.action === 'LOGIN_FAILED'}
                            <div class="p-1.5 bg-orange-50 rounded-lg">
                              <svg
                                class="w-4 h-4 text-orange-600"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                              >
                                <path
                                  stroke-linecap="round"
                                  stroke-linejoin="round"
                                  stroke-width="2"
                                  d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
                                />
                              </svg>
                            </div>
                          {:else}
                            <div class="p-1.5 bg-gray-50 rounded-lg">
                              <svg
                                class="w-4 h-4 text-gray-600"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                              >
                                <path
                                  stroke-linecap="round"
                                  stroke-linejoin="round"
                                  stroke-width="2"
                                  d="M13 10V3L4 14h7v7l9-11h-7z"
                                />
                              </svg>
                            </div>
                          {/if}
                          <span
                            class="px-2.5 py-1 text-xs font-semibold rounded-full {getActionColor(
                              log.action
                            )}"
                          >
                            {formatActionText(log.action)}
                          </span>
                        </div>
                      </td>
                      <td class="px-4 py-3 text-sm">
                        <div class="font-medium text-gray-900">{log.resource_type}</div>
                        {#if log.ip_address}
                          <div class="flex items-center gap-1 text-xs text-gray-500">
                            <svg
                              class="w-3 h-3"
                              fill="none"
                              stroke="currentColor"
                              viewBox="0 0 24 24"
                            >
                              <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"
                              />
                            </svg>
                            {log.ip_address}
                          </div>
                        {/if}
                      </td>
                      <td class="px-4 py-3 whitespace-nowrap text-center text-sm">
                        <button
                          type="button"
                          on:click={() => viewDetail(log)}
                          class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-indigo-50 text-indigo-600 hover:bg-indigo-100 rounded-lg text-xs font-medium transition-colors"
                        >
                          <svg
                            class="w-3.5 h-3.5"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <path
                              stroke-linecap="round"
                              stroke-linejoin="round"
                              stroke-width="2"
                              d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                            />
                            <path
                              stroke-linecap="round"
                              stroke-linejoin="round"
                              stroke-width="2"
                              d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
                            />
                          </svg>
                          Ver
                        </button>
                      </td>
                    </tr>
                  {/each}
                </tbody>
              </table>
            </div>

            <div class="lg:hidden divide-y divide-gray-200">
              {#each logs as log (log.id)}
                <button
                  type="button"
                  class="w-full text-left p-4 hover:bg-gray-50 transition-colors"
                  on:click={() => viewDetail(log)}
                >
                  <div class="flex items-start justify-between gap-3">
                    <div class="flex items-start gap-3 flex-1 min-w-0">
                      {#if log.user_email}
                        <div
                          class="flex-shrink-0 w-10 h-10 bg-gradient-to-br from-indigo-400 to-indigo-600 rounded-full flex items-center justify-center shadow-sm"
                        >
                          <span class="text-sm font-semibold text-white">
                            {(log.user_name || '?').charAt(0).toUpperCase()}
                          </span>
                        </div>
                      {:else}
                        <div
                          class="flex-shrink-0 w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center"
                        >
                          <svg
                            class="w-5 h-5 text-gray-400"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <path
                              stroke-linecap="round"
                              stroke-linejoin="round"
                              stroke-width="2"
                              d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
                            /><path
                              stroke-linecap="round"
                              stroke-linejoin="round"
                              stroke-width="2"
                              d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                            />
                          </svg>
                        </div>
                      {/if}

                      <div class="flex-1 min-w-0">
                        <div class="flex items-center gap-2 mb-2">
                          <span class="text-xs font-medium text-gray-600"
                            >{formatDateShort(log.created_at)}</span
                          >
                          <span
                            class="px-2 py-0.5 text-xs font-semibold rounded-full {getActionColor(
                              log.action
                            )}"
                          >
                            {formatActionText(log.action)}
                          </span>
                        </div>
                        <div class="font-semibold text-gray-900 text-sm mb-1">
                          {log.user_name || 'Sistema'}
                        </div>
                        <div class="text-xs text-gray-500 mb-2">{getRoleText(log.user_role)}</div>
                        <div class="flex items-center gap-2 text-sm">
                          <span class="font-medium text-gray-700">{log.resource_type}</span>
                        </div>
                        {#if log.ip_address}
                          <div class="flex items-center gap-1 text-xs text-gray-500 mt-1">
                            <svg
                              class="w-3 h-3"
                              fill="none"
                              stroke="currentColor"
                              viewBox="0 0 24 24"
                            >
                              <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"
                              />
                            </svg>
                            {log.ip_address}
                          </div>
                        {/if}
                      </div>
                    </div>

                    <button
                      type="button"
                      class="flex-shrink-0 text-indigo-600 hover:text-indigo-900 transition-colors p-2 bg-indigo-50 rounded-lg"
                      title="Ver detalles"
                    >
                      <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          d="M9 5l7 7-7 7"
                        />
                      </svg>
                    </button>
                  </div>
                </button>
              {/each}
            </div>
          </div>

          {#if totalPages > 1}
            <div class="bg-white border-t border-gray-200 px-4 py-3 flex-shrink-0 sticky bottom-0">
              <div class="flex items-center justify-between sm:hidden">
                <button
                  on:click={() => goToPage(currentPage - 1)}
                  disabled={currentPage === 1}
                  class="relative inline-flex items-center gap-1 px-4 py-2 border border-gray-300 text-sm font-medium rounded-lg text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M15 19l-7-7 7-7"
                    />
                  </svg>
                  Anterior
                </button>
                <span class="text-sm font-medium text-gray-700">
                  Página <span class="text-indigo-600">{currentPage}</span> / {totalPages}
                </span>
                <button
                  on:click={() => goToPage(currentPage + 1)}
                  disabled={currentPage === totalPages}
                  class="relative inline-flex items-center gap-1 px-4 py-2 border border-gray-300 text-sm font-medium rounded-lg text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  Siguiente
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M9 5l7 7-7 7"
                    />
                  </svg>
                </button>
              </div>

              <div class="hidden sm:flex sm:items-center sm:justify-between">
                <div class="text-sm text-gray-700">
                  Mostrando <span class="font-semibold text-gray-900"
                    >{(currentPage - 1) * perPage + 1}</span
                  >
                  -
                  <span class="font-semibold text-gray-900"
                    >{Math.min(currentPage * perPage, totalLogs)}</span
                  >
                  de
                  <span class="font-semibold text-indigo-600">{totalLogs}</span> registros
                </div>
                <div>
                  <nav
                    class="relative z-0 inline-flex rounded-lg shadow-sm -space-x-px"
                    aria-label="Pagination"
                  >
                    {#if currentPage > 3}
                      <button
                        on:click={() => goToPage(1)}
                        class="relative inline-flex items-center px-2 py-2 rounded-l-lg border border-gray-300 bg-white text-xs font-medium text-gray-500 hover:bg-gray-50 transition-colors"
                      >
                        <svg class="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
                          <path
                            fill-rule="evenodd"
                            d="M15.707 15.707a1 1 0 01-1.414 0l-5-5a1 1 0 010-1.414l5-5a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 010 1.414zm-6 0a1 1 0 01-1.414 0l-5-5a1 1 0 010-1.414l5-5a1 1 0 011.414 1.414L5.414 10l4.293 4.293a1 1 0 010 1.414z"
                            clip-rule="evenodd"
                          />
                        </svg>
                      </button>
                    {/if}

                    <button
                      on:click={() => goToPage(currentPage - 1)}
                      disabled={currentPage === 1}
                      class="relative inline-flex items-center px-3 py-2 {currentPage <= 3
                        ? 'rounded-l-lg'
                        : ''} border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                      <svg class="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
                        <path
                          fill-rule="evenodd"
                          d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z"
                          clip-rule="evenodd"
                        />
                      </svg>
                    </button>

                    {#each Array.from({ length: Math.min(5, totalPages) }, (_, i) => i + Math.max(1, Math.min(currentPage - 2, totalPages - 4))) as page}
                      <button
                        on:click={() => goToPage(page)}
                        class="relative inline-flex items-center px-3 py-1.5 border text-xs font-medium transition-colors {page ===
                        currentPage
                          ? 'z-10 bg-indigo-600 border-indigo-600 text-white'
                          : 'bg-white border-gray-300 text-gray-700 hover:bg-gray-50'}"
                      >
                        {page}
                      </button>
                    {/each}

                    <button
                      on:click={() => goToPage(currentPage + 1)}
                      disabled={currentPage === totalPages}
                      class="relative inline-flex items-center px-2 py-1.5 {currentPage >=
                      totalPages - 2
                        ? 'rounded-r-md'
                        : ''} border border-gray-300 bg-white text-xs font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      <svg class="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
                        <path
                          fill-rule="evenodd"
                          d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"
                          clip-rule="evenodd"
                        />
                      </svg>
                    </button>

                    {#if currentPage < totalPages - 2}
                      <button
                        on:click={() => goToPage(totalPages)}
                        class="relative inline-flex items-center px-2 py-1.5 rounded-r-md border border-gray-300 bg-white text-xs font-medium text-gray-500 hover:bg-gray-50"
                      >
                        <svg class="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
                          <path
                            fill-rule="evenodd"
                            d="M10.293 15.707a1 1 0 010-1.414L14.586 10l-4.293-4.293a1 1 0 111.414-1.414l5 5a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0z"
                            clip-rule="evenodd"
                          />
                          <path
                            fill-rule="evenodd"
                            d="M4.293 15.707a1 1 0 010-1.414L8.586 10 4.293 5.707a1 1 0 011.414-1.414l5 5a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0z"
                            clip-rule="evenodd"
                          />
                        </svg>
                      </button>
                    {/if}
                  </nav>
                </div>
              </div>
            </div>
          {/if}
        {/if}
      </div>
    </div>
  </div>
</div>

<!-- Modal de Incidentes -->
{#if showIncidentModal && selectedIncident}
  <Modal
    open={showIncidentModal}
    size="2xl"
    title="Detalle del Incidente de Seguridad"
    on:close={() => (showIncidentModal = false)}
  >
    <div class="space-y-4">
      <div>
        <h4 class="text-sm font-medium text-gray-900 mb-2">Información General</h4>
        <dl class="grid grid-cols-2 gap-3 text-sm">
          <div>
            <dt class="font-medium text-gray-500">Título:</dt>
            <dd class="text-gray-900">{selectedIncident.title}</dd>
          </div>
          <div>
            <dt class="font-medium text-gray-500">Severidad:</dt>
            <dd>
              <span
                class="px-2 py-1 text-xs font-medium rounded-full {getSeverityColor(
                  selectedIncident.severity
                )}"
              >
                {selectedIncident.severity?.toUpperCase()}
              </span>
            </dd>
          </div>
          <div>
            <dt class="font-medium text-gray-500">Estado:</dt>
            <dd>
              <span
                class="px-2 py-1 text-xs font-medium rounded-full {getStatusColor(
                  selectedIncident.status
                )}"
              >
                {selectedIncident.status?.toUpperCase()}
              </span>
            </dd>
          </div>
          <div>
            <dt class="font-medium text-gray-500">Fecha:</dt>
            <dd class="text-gray-900">{formatDate(selectedIncident.created_at)}</dd>
          </div>
          {#if selectedIncident.affected_user}
            <div>
              <dt class="font-medium text-gray-500">Usuario Afectado:</dt>
              <dd class="text-gray-900">{selectedIncident.affected_user}</dd>
            </div>
          {/if}
          {#if selectedIncident.source_ip}
            <div>
              <dt class="font-medium text-gray-500">IP Origen:</dt>
              <dd class="text-gray-900 font-mono text-xs">{selectedIncident.source_ip}</dd>
            </div>
          {/if}
        </dl>
      </div>

      {#if selectedIncident.description}
        <div>
          <h4 class="text-sm font-medium text-gray-900 mb-2">Descripción</h4>
          <div class="bg-gray-50 rounded-lg p-3 text-sm text-gray-700">
            {selectedIncident.description}
          </div>
        </div>
      {/if}

      {#if selectedIncident.evidence && selectedIncident.evidence.length > 0}
        <div>
          <h4 class="text-sm font-medium text-gray-900 mb-2">Evidencia</h4>
          <div class="bg-gray-50 rounded-lg p-3">
            <ul class="list-disc list-inside text-sm text-gray-700 space-y-1">
              {#each selectedIncident.evidence as evidence}
                <li>{evidence}</li>
              {/each}
            </ul>
          </div>
        </div>
      {/if}

      {#if selectedIncident.metadata && Object.keys(selectedIncident.metadata).length > 0}
        <div>
          <h4 class="text-sm font-medium text-gray-900 mb-2">Información Adicional</h4>
          <pre
            class="bg-gray-50 rounded-lg p-3 text-xs font-mono text-gray-600 overflow-auto max-h-40">{JSON.stringify(
              selectedIncident.metadata,
              null,
              2
            )}</pre>
        </div>
      {/if}
    </div>

    <div slot="footer" class="flex justify-end">
      <button
        on:click={() => (showIncidentModal = false)}
        class="px-4 py-2 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50"
      >
        Cerrar
      </button>
    </div>
  </Modal>
{/if}

{#if showDetailModal && selectedLog}}
  <Modal
    open={showDetailModal}
    size="2xl"
    title="Detalle del Registro de Auditoría"
    on:close={() => (showDetailModal = false)}
  >
    <div class="space-y-4">
      <div>
        <h4 class="text-sm font-medium text-gray-900 mb-2">Información General</h4>
        <dl class="grid grid-cols-2 gap-3 text-sm">
          <div>
            <dt class="font-medium text-gray-500">Fecha y Hora:</dt>
            <dd class="text-gray-900">{formatDate(selectedLog.created_at)}</dd>
          </div>
          <div>
            <dt class="font-medium text-gray-500">Usuario:</dt>
            <dd class="text-gray-900">{selectedLog.user_name || 'Sistema'}</dd>
          </div>
          <div>
            <dt class="font-medium text-gray-500">Email:</dt>
            <dd class="text-gray-900">{selectedLog.user_email || 'N/A'}</dd>
          </div>
          {#if selectedLog.user_role}
            <div>
              <dt class="font-medium text-gray-500">Rol:</dt>
              <dd class="text-gray-900">{getRoleText(selectedLog.user_role)}</dd>
            </div>
          {/if}
          <div>
            <dt class="font-medium text-gray-500">IP:</dt>
            <dd class="text-gray-900 font-mono text-xs">{selectedLog.ip_address || 'N/A'}</dd>
          </div>
          <div>
            <dt class="font-medium text-gray-500">Correlation ID:</dt>
            <dd class="text-gray-900 font-mono text-xs truncate">
              {selectedLog.correlation_id || 'N/A'}
            </dd>
          </div>
        </dl>
      </div>

      <div>
        <h4 class="text-sm font-medium text-gray-900 mb-2">Acción</h4>
        <div class="bg-gray-50 rounded-lg p-3">
          <span
            class="px-2 py-1 text-xs font-semibold rounded-full {getActionColor(
              selectedLog.action
            )}"
          >
            {selectedLog.action}
          </span>
          <p class="mt-2 text-sm text-gray-700">{formatActionText(selectedLog.action)}</p>
        </div>
      </div>

      <div>
        <h4 class="text-sm font-medium text-gray-900 mb-2">Recurso Afectado</h4>
        <div class="bg-gray-50 rounded-lg p-3 text-sm">
          <div><span class="font-medium">Tipo:</span> {selectedLog.resource_type}</div>
          {#if selectedLog.resource_id}
            <div class="mt-1">
              <span class="font-medium">ID:</span>
              <code class="text-xs">{selectedLog.resource_id}</code>
            </div>
          {/if}
        </div>
      </div>

      {#if selectedLog.user_agent}
        <div>
          <h4 class="text-sm font-medium text-gray-900 mb-2">Navegador / Dispositivo</h4>
          <div class="bg-gray-50 rounded-lg p-3 text-xs font-mono text-gray-600 break-all">
            {selectedLog.user_agent}
          </div>
        </div>
      {/if}

      {#if selectedLog.old_values && Object.keys(selectedLog.old_values).length > 0}
        <div>
          <h4 class="text-sm font-medium text-gray-900 mb-2">Valores Anteriores</h4>
          <pre
            class="bg-gray-50 rounded-lg p-3 text-xs font-mono text-gray-600 overflow-auto max-h-40">{JSON.stringify(
              selectedLog.old_values,
              null,
              2
            )}</pre>
        </div>
      {/if}

      {#if selectedLog.new_values && Object.keys(selectedLog.new_values).length > 0}
        <div>
          <h4 class="text-sm font-medium text-gray-900 mb-2">Valores Nuevos</h4>
          <pre
            class="bg-gray-50 rounded-lg p-3 text-xs font-mono text-gray-600 overflow-auto max-h-40">{JSON.stringify(
              selectedLog.new_values,
              null,
              2
            )}</pre>
        </div>
      {/if}

      {#if selectedLog.metadata && Object.keys(selectedLog.metadata).length > 0}
        <div>
          <h4 class="text-sm font-medium text-gray-900 mb-2">Información Adicional</h4>
          <pre
            class="bg-gray-50 rounded-lg p-3 text-xs font-mono text-gray-600 overflow-auto max-h-40">{JSON.stringify(
              selectedLog.metadata,
              null,
              2
            )}</pre>
        </div>
      {/if}
    </div>

    <div slot="footer" class="flex justify-end">
      <button
        on:click={() => (showDetailModal = false)}
        class="px-4 py-2 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50"
      >
        Cerrar
      </button>
    </div>
  </Modal>
{/if}
