/**
 * Activity Log Admin JavaScript
 */

(function($) {
    'use strict';

    const ActivityLog = {
        currentPage: 0,
        pageSize: 50,
        orderBy: 'created_at',
        order: 'DESC',
        total: 0,
        selectedIds: [],
        filters: {},
        deleteTarget: null,
        autoRefreshInterval: null,

        init: function() {
            this.bindEvents();
            this.restoreFromURL();
            this.loadStats();
            this.loadLogs();
        },

        bindEvents: function() {
            const self = this;

            // Date preset change
            $('#filter-date-preset').on('change', function() {
                const preset = $(this).val();
                if (preset === 'custom') {
                    $('#custom-date-range').show();
                } else {
                    $('#custom-date-range').hide();
                    self.applyDatePreset(preset);
                }
            });

            // Apply filters button
            $('#apply-filters').on('click', function() {
                self.currentPage = 0;
                self.loadLogs();
                self.updateActiveFiltersCount();
            });

            // Refresh button
            $('#refresh-logs').on('click', function() {
                const $btn = $(this);
                $btn.prop('disabled', true).find('svg').css('animation', 'spin 1s linear infinite');
                self.loadLogs();
                self.loadStats();
                setTimeout(function() {
                    $btn.prop('disabled', false).find('svg').css('animation', '');
                }, 500);
            });

            // Delete all logs button
            $('#delete-all-logs').on('click', function() {
                self.showDeleteModal('ALL activity logs');
                self.deleteTarget = { type: 'all' };
            });

            // Auto-refresh toggle
            $('#auto-refresh-toggle').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#auto-refresh-interval').show();
                    self.startAutoRefresh();
                } else {
                    $('#auto-refresh-interval').hide();
                    self.stopAutoRefresh();
                }
            });

            // Auto-refresh interval change
            $('#auto-refresh-interval').on('change', function() {
                if ($('#auto-refresh-toggle').is(':checked')) {
                    self.stopAutoRefresh();
                    self.startAutoRefresh();
                }
            });

            // Clear filters button
            $('#clear-filters').on('click', function() {
                self.clearFilters();
            });

            // When severity changes, clear action_type (they're mutually exclusive for filtering)
            $('#filter-severity').on('change', function() {
                if ($(this).val()) {
                    $('#filter-action').val('');
                }
            });

            // When action_type changes, clear severity (they're mutually exclusive for filtering)
            $('#filter-action').on('change', function() {
                if ($(this).val()) {
                    $('#filter-severity').val('');
                }
            });

            // Export CSV
            $('#export-csv').on('click', function() {
                self.exportCSV();
            });

            // Search input (with debounce)
            let searchTimeout;
            $('#filter-search').on('input', function() {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(function() {
                    self.currentPage = 0;
                    self.loadLogs();
                }, 500);
            });

            // Per page change
            $('#per-page').on('change', function() {
                self.pageSize = parseInt($(this).val());
                self.currentPage = 0;
                self.loadLogs();
            });

            // Sorting
            $(document).on('click', '#activity-log-table th.sortable', function() {
                const column = $(this).data('column');

                if (self.orderBy === column) {
                    self.order = self.order === 'DESC' ? 'ASC' : 'DESC';
                } else {
                    self.orderBy = column;
                    self.order = 'DESC';
                }

                self.currentPage = 0;
                self.loadLogs();
            });

            // Pagination
            $('#page-first').on('click', function() {
                if (self.currentPage > 0) {
                    self.currentPage = 0;
                    self.loadLogs();
                }
            });

            $('#page-prev').on('click', function() {
                if (self.currentPage > 0) {
                    self.currentPage--;
                    self.loadLogs();
                }
            });

            $('#page-next').on('click', function() {
                if ((self.currentPage + 1) * self.pageSize < self.total) {
                    self.currentPage++;
                    self.loadLogs();
                }
            });

            $('#page-last').on('click', function() {
                const lastPage = Math.ceil(self.total / self.pageSize) - 1;
                if (self.currentPage < lastPage) {
                    self.currentPage = lastPage;
                    self.loadLogs();
                }
            });

            // Select all checkbox
            $('#select-all').on('change', function() {
                const isChecked = $(this).prop('checked');
                $('.activity-log-row-checkbox').prop('checked', isChecked);
                self.updateSelectedIds();
            });

            // Individual row checkbox
            $(document).on('change', '.activity-log-row-checkbox', function() {
                self.updateSelectedIds();
            });

            // Delete selected button
            $('#delete-selected').on('click', function() {
                if (self.selectedIds.length > 0) {
                    self.showDeleteModal(self.selectedIds.length + ' entries');
                    self.deleteTarget = { type: 'bulk', ids: self.selectedIds };
                }
            });

            // Single delete button
            $(document).on('click', '.activity-log-delete-btn', function() {
                const id = $(this).data('id');
                self.showDeleteModal('this entry');
                self.deleteTarget = { type: 'single', id: id };
            });

            // Confirm delete
            $('#confirm-delete').on('click', function() {
                if (self.deleteTarget) {
                    if (self.deleteTarget.type === 'single') {
                        self.deleteSingle(self.deleteTarget.id);
                    } else if (self.deleteTarget.type === 'bulk') {
                        self.deleteBulk(self.deleteTarget.ids);
                    } else if (self.deleteTarget.type === 'all') {
                        self.deleteAll();
                    }
                }
                self.hideDeleteModal();
            });

            // Modal close handlers
            $('.activity-log-modal-close, .activity-log-modal-overlay, .activity-log-modal-cancel').on('click', function() {
                self.hideDeleteModal();
                self.hideUserAgentModal();
            });

            // Show user agent
            $(document).on('click', '.activity-log-expand-btn', function() {
                const userAgent = $(this).data('user-agent');
                self.showUserAgentModal(userAgent);
            });

            // Keyboard shortcut for closing modals
            $(document).on('keydown', function(e) {
                if (e.key === 'Escape') {
                    self.hideDeleteModal();
                    self.hideUserAgentModal();
                }
            });
        },

        restoreFromURL: function() {
            const params = new URLSearchParams(window.location.search);

            // Restore filters from URL
            if (params.has('date_from')) {
                $('#filter-date-from').val(params.get('date_from'));
            }
            if (params.has('date_to')) {
                $('#filter-date-to').val(params.get('date_to'));
            }
            if (params.has('user_id')) {
                $('#filter-user').val(params.get('user_id'));
            }
            // Severity and action_type are mutually exclusive - action_type takes precedence
            if (params.has('action_type')) {
                $('#filter-action').val(params.get('action_type'));
                // Don't set severity if action_type is present
            } else if (params.has('severity')) {
                $('#filter-severity').val(params.get('severity'));
            }
            if (params.has('role')) {
                $('#filter-role').val(params.get('role'));
            }
            if (params.has('ip_address')) {
                $('#filter-ip').val(params.get('ip_address'));
            }
            if (params.has('search')) {
                $('#filter-search').val(params.get('search'));
            }
            if (params.has('paged')) {
                this.currentPage = Math.max(0, parseInt(params.get('paged')) - 1);
            }
            if (params.has('orderby')) {
                this.orderBy = params.get('orderby');
            }
            if (params.has('order')) {
                this.order = params.get('order').toUpperCase();
            }

            // Check if custom date range should be shown
            const dateFrom = $('#filter-date-from').val();
            const dateTo = $('#filter-date-to').val();
            if (dateFrom || dateTo) {
                // Check if it matches a preset
                const preset = this.detectDatePreset(dateFrom, dateTo);
                if (preset) {
                    $('#filter-date-preset').val(preset);
                } else if (dateFrom || dateTo) {
                    $('#filter-date-preset').val('custom');
                    $('#custom-date-range').show();
                }
            } else {
                // Default to 7 days
                $('#filter-date-preset').val('7days');
                this.applyDatePreset('7days');
            }

            this.updateActiveFiltersCount();
        },

        detectDatePreset: function(fromDate, toDate) {
            const today = new Date();
            const todayStr = this.formatDateForInput(today);

            if (!fromDate && !toDate) return 'all';
            if (fromDate === todayStr && toDate === todayStr) return 'today';

            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            const yesterdayStr = this.formatDateForInput(yesterday);
            if (fromDate === yesterdayStr && toDate === yesterdayStr) return 'yesterday';

            const sevenDaysAgo = new Date(today);
            sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
            if (fromDate === this.formatDateForInput(sevenDaysAgo) && toDate === todayStr) return '7days';

            const thirtyDaysAgo = new Date(today);
            thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
            if (fromDate === this.formatDateForInput(thirtyDaysAgo) && toDate === todayStr) return '30days';

            return null;
        },

        applyDatePreset: function(preset) {
            const today = new Date();
            let fromDate = null;
            let toDate = new Date(today);

            switch (preset) {
                case 'today':
                    fromDate = new Date(today);
                    break;
                case 'yesterday':
                    fromDate = new Date(today);
                    fromDate.setDate(fromDate.getDate() - 1);
                    toDate = new Date(fromDate);
                    break;
                case '7days':
                    fromDate = new Date(today);
                    fromDate.setDate(fromDate.getDate() - 7);
                    break;
                case '30days':
                    fromDate = new Date(today);
                    fromDate.setDate(fromDate.getDate() - 30);
                    break;
                case 'all':
                    fromDate = null;
                    toDate = null;
                    break;
                default:
                    return;
            }

            if (fromDate) {
                $('#filter-date-from').val(this.formatDateForInput(fromDate));
            } else {
                $('#filter-date-from').val('');
            }

            if (toDate) {
                $('#filter-date-to').val(this.formatDateForInput(toDate));
            } else {
                $('#filter-date-to').val('');
            }
        },

        formatDateForInput: function(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },

        getFilters: function() {
            return {
                date_from: $('#filter-date-from').val(),
                date_to: $('#filter-date-to').val(),
                user_id: $('#filter-user').val(),
                severity: $('#filter-severity').val(),
                action_type: $('#filter-action').val(),
                role: $('#filter-role').val(),
                ip_address: $('#filter-ip').val().trim(),
                search: $('#filter-search').val().trim()
            };
        },

        clearFilters: function() {
            $('#filter-date-from').val('');
            $('#filter-date-to').val('');
            $('#filter-date-preset').val('7days');
            $('#custom-date-range').hide();
            $('#filter-user').val('');
            $('#filter-severity').val('');
            $('#filter-action').val('');
            $('#filter-role').val('');
            $('#filter-ip').val('');
            $('#filter-search').val('');
            this.applyDatePreset('7days');
            this.currentPage = 0;
            this.loadLogs();
            this.updateActiveFiltersCount();
        },

        loadStats: function() {
            const self = this;

            $.ajax({
                url: activityLogAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'activity_log_get_stats',
                    nonce: activityLogAdmin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        const data = response.data;
                        $('#stat-total-events').text(self.formatNumber(data.total_events));
                        $('#stat-today').text(self.formatNumber(data.today_events));
                        $('#stat-failed-logins').text(self.formatNumber(data.failed_logins));
                        $('#stat-unique-users').text(self.formatNumber(data.unique_users));
                    }
                }
            });
        },

        loadLogs: function() {
            const self = this;
            const filters = this.getFilters();

            $.ajax({
                url: activityLogAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'activity_log_get_logs',
                    nonce: activityLogAdmin.nonce,
                    orderby: self.orderBy,
                    order: self.order,
                    offset: self.currentPage * self.pageSize,
                    limit: self.pageSize,
                    ...filters
                },
                beforeSend: function() {
                    $('#activity-log-tbody').html(self.renderSkeletonRows(5));
                },
                success: function(response) {
                    if (response.success) {
                        self.total = response.data.total;
                        self.renderLogs(response.data.logs);
                        self.updatePagination();
                        self.updateSortIndicators();
                        self.updateResultsSummary();

                        // Update URL params for bookmarking
                        self.updateURLParams();
                    }
                },
                error: function() {
                    $('#activity-log-tbody').html(
                        '<tr><td colspan="8" class="sb-module-empty" style="padding: 60px 20px;">' +
                        '<div class="sb-module-empty-icon"></div>' +
                        '<p class="sb-module-empty-desc">Failed to load activity logs.</p></td></tr>'
                    );
                }
            });
        },

        renderLogs: function(logs) {
            const tbody = $('#activity-log-tbody');
            tbody.empty();

            if (!logs || logs.length === 0) {
                tbody.html(
                    '<tr><td colspan="8" class="sb-module-empty" style="padding: 60px 20px; text-align: center;">' +
                    '<div class="activity-log-empty-illustration">' +
                    '<svg width="120" height="100" viewBox="0 0 120 100" fill="none" xmlns="http://www.w3.org/2000/svg">' +
                    '<rect x="20" y="20" width="80" height="60" rx="4" fill="#f1f5f9" stroke="#e2e8f0" stroke-width="2"/>' +
                    '<rect x="30" y="35" width="40" height="6" rx="3" fill="#cbd5e1"/>' +
                    '<rect x="30" y="47" width="60" height="4" rx="2" fill="#e2e8f0"/>' +
                    '<rect x="30" y="57" width="50" height="4" rx="2" fill="#e2e8f0"/>' +
                    '<circle cx="90" cy="70" r="20" fill="#f1f5f9" stroke="#e2e8f0" stroke-width="2"/>' +
                    '<path d="M85 70L88 73L95 66" stroke="#94a3b8" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>' +
                    '</svg>' +
                    '</div>' +
                    '<p class="sb-module-empty-title" style="font-size: 16px; font-weight: 600; color: var(--gray-700); margin: 16px 0 8px;">No activity found</p>' +
                    '<p class="sb-module-empty-desc" style="color: var(--gray-500); font-size: 14px; max-width: 320px; margin: 0 auto;">No activity logs match your current filters. Try adjusting your search criteria or clearing the filters.</p></td></tr>'
                );
                return;
            }

            logs.forEach(function(log) {
                const severity = ActivityLog.getSeverityForAction(log.action);
                const rowClass = severity === 'critical' ? 'activity-log-row-critical' : (severity === 'warning' ? 'activity-log-row-warning' : '');
                const row = $('<tr>').addClass(rowClass);

                // Checkbox
                row.append(
                    $('<td>').html(
                        '<input type="checkbox" class="activity-log-row-checkbox activity-log-checkbox" data-id="' + log.id + '">'
                    )
                );

                // Date & Time
                row.append(
                    $('<td class="activity-log-col-date">').text(ActivityLog.formatDate(log.created_at))
                );

                // User with avatar
                const userCell = $('<td class="activity-log-col-user">');
                const userWrapper = $('<div class="activity-log-user-wrapper">');
                const avatar = $('<span class="activity-log-avatar">')
                    .text(log.user_name.charAt(0).toUpperCase());
                const userName = $('<span class="activity-log-user-name">').text(log.user_name);
                userWrapper.append(avatar, userName);
                userCell.append(userWrapper);
                row.append(userCell);

                // Role badge
                const roleClass = ActivityLog.getRoleBadgeClass(log.user_role);
                row.append(
                    $('<td>').html(
                        '<span class="activity-log-badge ' + roleClass + '">' + ActivityLog.formatRole(log.user_role) + '</span>'
                    )
                );

                // Action badge
                const actionClass = ActivityLog.getActionBadgeClass(log.action);
                row.append(
                    $('<td>').html(
                        '<span class="activity-log-badge ' + actionClass + '">' + ActivityLog.formatAction(log.action) + '</span>'
                    )
                );

                // Object
                let objectHtml = '<span class="activity-log-no-data">-</span>';
                if (log.object_name) {
                    objectHtml = '<span class="activity-log-object-wrapper">' +
                        '<span class="activity-log-object-name">' + ActivityLog.escapeHtml(log.object_name) + '</span>' +
                        (log.object_type ? '<span class="activity-log-object-type">(' + ActivityLog.escapeHtml(log.object_type) + ')</span>' : '') +
                        '</span>';
                }
                row.append($('<td>').html(objectHtml));

                // IP Address
                row.append(
                    $('<td class="activity-log-col-ip">').html(
                        '<code class="activity-log-ip">' + ActivityLog.escapeHtml(log.ip_address) + '</code>'
                    )
                );

                // Actions
                const actionsCell = $('<td class="activity-log-col-actions">');
                const actionsWrapper = $('<div class="activity-log-actions-wrapper">');

                // Expand button for user agent
                if (log.user_agent) {
                    const expandBtn = $('<button type="button" class="activity-log-expand-btn" title="View User Agent">')
                        .attr('data-user-agent', log.user_agent)
                        .html('<span class="dashicons dashicons-info-outline"></span>');
                    actionsWrapper.append(expandBtn);
                }

                // Delete button
                const deleteBtn = $('<button type="button" class="activity-log-delete-btn" title="Delete">')
                    .attr('data-id', log.id)
                    .html('<span class="dashicons dashicons-trash"></span>');
                actionsWrapper.append(deleteBtn);

                actionsCell.append(actionsWrapper);
                row.append(actionsCell);

                tbody.append(row);
            });

            // Reset select all checkbox
            $('#select-all').prop('checked', false);
            this.selectedIds = [];
            this.updateBulkActionsVisibility();
        },

        updateSelectedIds: function() {
            this.selectedIds = [];
            $('.activity-log-row-checkbox:checked').each(function() {
                ActivityLog.selectedIds.push($(this).data('id'));
            });
            $('#selected-count').text(this.selectedIds.length);
            this.updateBulkActionsVisibility();
        },

        updateBulkActionsVisibility: function() {
            if (this.selectedIds.length > 0) {
                $('#bulk-actions').show();
            } else {
                $('#bulk-actions').hide();
            }
        },

        updatePagination: function() {
            const start = this.total > 0 ? this.currentPage * this.pageSize + 1 : 0;
            const end = Math.min((this.currentPage + 1) * this.pageSize, this.total);
            const totalPages = Math.ceil(this.total / this.pageSize);

            $('#page-info').text('Page ' + (this.currentPage + 1) + ' of ' + Math.max(1, totalPages));

            // Update button states
            const isFirstPage = this.currentPage === 0;
            const isLastPage = end >= this.total;

            $('#page-first').prop('disabled', isFirstPage);
            $('#page-prev').prop('disabled', isFirstPage);
            $('#page-next').prop('disabled', isLastPage);
            $('#page-last').prop('disabled', isLastPage);
        },

        updateResultsSummary: function() {
            const start = this.total > 0 ? this.currentPage * this.pageSize + 1 : 0;
            const end = Math.min((this.currentPage + 1) * this.pageSize, this.total);
            $('#results-summary').text('Showing ' + start + ' - ' + end + ' of ' + this.formatNumber(this.total) + ' entries');
        },

        updateSortIndicators: function() {
            $('#activity-log-table th.sortable').removeClass('active asc desc');
            const th = $('#activity-log-table th[data-column="' + this.orderBy + '"]');
            th.addClass('active');
            th.addClass(this.order.toLowerCase());
        },

        updateURLParams: function() {
            const params = new URLSearchParams(window.location.search);
            params.set('page', 'switchboard-activity-log');

            const filters = this.getFilters();
            for (const [key, value] of Object.entries(filters)) {
                if (value) {
                    params.set(key, value);
                } else {
                    params.delete(key);
                }
            }

            params.set('paged', this.currentPage + 1);
            params.set('orderby', this.orderBy);
            params.set('order', this.order);

            const newUrl = window.location.pathname + '?' + params.toString();
            window.history.replaceState({}, '', newUrl);
        },

        formatDate: function(dateString) {
            if (!dateString) return '-';
            const date = new Date(dateString.replace(/-/g, '/'));
            const options = {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                hour: 'numeric',
                minute: '2-digit',
                hour12: true
            };
            return date.toLocaleDateString('en-US', options);
        },

        formatNumber: function(num) {
            if (num === null || num === undefined) return '0';
            return parseInt(num).toLocaleString();
        },

        formatAction: function(action) {
            if (!action) return '-';
            return action.split('_').map(word =>
                word.charAt(0).toUpperCase() + word.slice(1)
            ).join(' ');
        },

        formatRole: function(role) {
            if (!role || role === 'none') return 'Guest';
            return role.charAt(0).toUpperCase() + role.slice(1);
        },

        // Severity mapping - matches PHP SwitchboardActivityLog::$severity_map
        severityMap: {
            'critical': ['login_failed', 'user_deleted', 'post_deleted'],
            'warning':  ['post_trash', 'plugin_deactivated'],
            'success':  ['user_login', 'post_published', 'user_registered'],
            'info':     ['user_logout', 'post_created', 'post_draft', 'post_pending', 'plugin_activated', 'theme_switched', 'profile_updated', 'option_updated']
        },

        getSeverityForAction: function(action) {
            for (const [severity, actions] of Object.entries(this.severityMap)) {
                if (actions.includes(action)) {
                    return severity;
                }
            }
            return 'info';
        },

        getSeverityBadgeClass: function(severity) {
            const classes = {
                'critical': 'activity-log-badge-critical',
                'warning': 'activity-log-badge-warning',
                'success': 'activity-log-badge-success',
                'info': 'activity-log-badge-info'
            };
            return classes[severity] || 'activity-log-badge-default';
        },

        getSeverityLabel: function(severity) {
            const labels = {
                'critical': 'Critical',
                'warning': 'Warning',
                'success': 'Success',
                'info': 'Info'
            };
            return labels[severity] || 'Info';
        },

        getActionBadgeClass: function(action) {
            const severity = this.getSeverityForAction(action);
            return this.getSeverityBadgeClass(severity);
        },

        getRoleBadgeClass: function(role) {
            const roleClasses = {
                'administrator': 'activity-log-badge-admin',
                'editor': 'activity-log-badge-editor',
                'author': 'activity-log-badge-author',
                'contributor': 'activity-log-badge-contributor',
                'subscriber': 'activity-log-badge-subscriber',
                'none': 'activity-log-badge-guest'
            };
            return roleClasses[role] || 'activity-log-badge-default';
        },

        escapeHtml: function(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        },

        exportCSV: function() {
            const filters = this.getFilters();
            const params = new URLSearchParams({
                action: 'activity_log_export',
                nonce: activityLogAdmin.nonce,
                ...filters
            });
            window.location.href = activityLogAdmin.ajaxUrl + '?' + params.toString();
        },

        deleteSingle: function(id) {
            const self = this;

            $.ajax({
                url: activityLogAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'activity_log_delete',
                    nonce: activityLogAdmin.nonce,
                    id: id
                },
                success: function(response) {
                    if (response.success) {
                        self.loadLogs();
                        self.loadStats();
                    } else {
                        alert('Failed to delete: ' + (response.data || 'Unknown error'));
                    }
                }
            });
        },

        deleteBulk: function(ids) {
            const self = this;

            $.ajax({
                url: activityLogAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'activity_log_delete_bulk',
                    nonce: activityLogAdmin.nonce,
                    ids: ids
                },
                success: function(response) {
                    if (response.success) {
                        self.selectedIds = [];
                        self.loadLogs();
                        self.loadStats();
                    } else {
                        alert('Failed to delete: ' + (response.data || 'Unknown error'));
                    }
                }
            });
        },

        deleteAll: function() {
            const self = this;

            $.ajax({
                url: activityLogAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'activity_log_delete_all',
                    nonce: activityLogAdmin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        self.selectedIds = [];
                        self.currentPage = 0;
                        self.loadLogs();
                        self.loadStats();
                    } else {
                        alert('Failed to delete: ' + (response.data || 'Unknown error'));
                    }
                }
            });
        },

        showDeleteModal: function(targetText) {
            $('#delete-message').text('Are you sure you want to delete ' + targetText + '? This action cannot be undone.');
            $('#delete-modal').show();
        },

        hideDeleteModal: function() {
            $('#delete-modal').hide();
            this.deleteTarget = null;
        },

        showUserAgentModal: function(userAgent) {
            $('#user-agent-content').text(userAgent || 'No user agent recorded');
            $('#user-agent-modal').show();
        },

        hideUserAgentModal: function() {
            $('#user-agent-modal').hide();
        },

        updateActiveFiltersCount: function() {
            let count = 0;
            const filters = this.getFilters();

            // Count non-date filters (user_id uses !== '' to count "0" for Guests)
            if (filters.user_id !== '') count++;
            if (filters.severity !== '') count++;
            if (filters.action_type !== '') count++;
            if (filters.role !== '') count++;
            if (filters.ip_address !== '') count++;
            if (filters.search !== '') count++;

            // Update badge
            const badge = $('#active-filters-count');
            if (count > 0) {
                badge.text(count).show();
            } else {
                badge.hide();
            }
        },

        startAutoRefresh: function() {
            const self = this;
            const interval = parseInt($('#auto-refresh-interval').val()) * 1000;

            this.autoRefreshInterval = setInterval(function() {
                self.loadLogs();
                self.loadStats();
            }, interval);
        },

        stopAutoRefresh: function() {
            if (this.autoRefreshInterval) {
                clearInterval(this.autoRefreshInterval);
                this.autoRefreshInterval = null;
            }
        },

        renderSkeletonRows: function(count) {
            let html = '';
            for (let i = 0; i < count; i++) {
                html += '<tr class="activity-log-skeleton-row">' +
                    '<td><div class="activity-log-skeleton" style="width: 16px; height: 16px;"></div></td>' +
                    '<td><div class="activity-log-skeleton activity-log-skeleton-text-sm"></div></td>' +
                    '<td><div style="display: flex; align-items: center; gap: 10px;"><div class="activity-log-skeleton activity-log-skeleton-avatar"></div><div class="activity-log-skeleton activity-log-skeleton-text-md"></div></div></td>' +
                    '<td><div class="activity-log-skeleton activity-log-skeleton-badge"></div></td>' +
                    '<td><div class="activity-log-skeleton activity-log-skeleton-badge"></div></td>' +
                    '<td><div class="activity-log-skeleton activity-log-skeleton-text-lg"></div></td>' +
                    '<td><div class="activity-log-skeleton activity-log-skeleton-text-sm"></div></td>' +
                    '<td><div class="activity-log-skeleton" style="width: 24px; height: 24px;"></div></td>' +
                    '</tr>';
            }
            return html;
        }
    };

    // Initialize on document ready
    $(document).ready(function() {
        ActivityLog.init();
    });

})(jQuery);
