/**
 * Hide My Login - Admin Page JavaScript
 * Handles access log viewing, filtering, and management
 */

(function($) {
    'use strict';

    // State
    var state = {
        currentPage: 1,
        perPage: 50,
        totalPages: 1,
        totalItems: 0,
        selectedIds: [],
        deleteMode: null, // 'selected' or 'all'
        filters: {
            search: '',
            type: '',
            ip: '',
            date_from: '',
            date_to: ''
        }
    };

    // Initialize
    $(document).ready(function() {
        initFilters();
        initPagination();
        initSelection();
        initActions();
        initModals();

        // Load initial data
        loadStats();
        loadLogs();
    });

    /**
     * Initialize filter controls
     */
    function initFilters() {
        // Date preset change
        $('#filter-date-preset').on('change', function() {
            var preset = $(this).val();
            if (preset === 'custom') {
                $('#custom-date-range').slideDown(200);
            } else {
                $('#custom-date-range').slideUp(200);
                setDatePreset(preset);
            }
        });

        // Apply filters button
        $('#apply-filters').on('click', function() {
            gatherFilters();
            state.currentPage = 1;
            loadLogs();
        });

        // Clear filters button
        $('#clear-filters').on('click', function() {
            clearFilters();
            state.currentPage = 1;
            loadLogs();
        });

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

        // Enter key in search
        $('#filter-search, #filter-ip').on('keypress', function(e) {
            if (e.which === 13) {
                e.preventDefault();
                $('#apply-filters').click();
            }
        });

        // Set default date preset
        setDatePreset('7days');
    }

    /**
     * Set date range based on preset
     */
    function setDatePreset(preset) {
        var today = new Date();
        var from = new Date();
        var to = new Date();

        switch (preset) {
            case 'today':
                from = today;
                break;
            case 'yesterday':
                from.setDate(from.getDate() - 1);
                to.setDate(to.getDate() - 1);
                break;
            case '7days':
                from.setDate(from.getDate() - 7);
                break;
            case '30days':
                from.setDate(from.getDate() - 30);
                break;
            case 'all':
                from = null;
                to = null;
                break;
        }

        if (from) {
            state.filters.date_from = formatDate(from);
        } else {
            state.filters.date_from = '';
        }

        if (to && preset !== 'all') {
            state.filters.date_to = formatDate(to);
        } else {
            state.filters.date_to = '';
        }
    }

    /**
     * Format date as YYYY-MM-DD
     */
    function formatDate(date) {
        var year = date.getFullYear();
        var month = ('0' + (date.getMonth() + 1)).slice(-2);
        var day = ('0' + date.getDate()).slice(-2);
        return year + '-' + month + '-' + day;
    }

    /**
     * Gather current filter values
     */
    function gatherFilters() {
        state.filters.search = $('#filter-search').val().trim();
        state.filters.type = $('#filter-type').val();
        state.filters.ip = $('#filter-ip').val().trim();

        if ($('#filter-date-preset').val() === 'custom') {
            state.filters.date_from = $('#filter-date-from').val();
            state.filters.date_to = $('#filter-date-to').val();
        }

        updateFilterBadge();
    }

    /**
     * Clear all filters
     */
    function clearFilters() {
        $('#filter-search').val('');
        $('#filter-type').val('');
        $('#filter-ip').val('');
        $('#filter-date-preset').val('7days').trigger('change');

        state.filters = {
            search: '',
            type: '',
            ip: '',
            date_from: '',
            date_to: ''
        };

        setDatePreset('7days');
        updateFilterBadge();
    }

    /**
     * Update filter count badge
     */
    function updateFilterBadge() {
        var count = 0;
        if (state.filters.search) count++;
        if (state.filters.type) count++;
        if (state.filters.ip) count++;
        if ($('#filter-date-preset').val() !== '7days') count++;

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

    /**
     * Initialize pagination controls
     */
    function initPagination() {
        $('#page-first').on('click', function() {
            if (!$(this).prop('disabled')) {
                state.currentPage = 1;
                loadLogs();
            }
        });

        $('#page-prev').on('click', function() {
            if (!$(this).prop('disabled') && state.currentPage > 1) {
                state.currentPage--;
                loadLogs();
            }
        });

        $('#page-next').on('click', function() {
            if (!$(this).prop('disabled') && state.currentPage < state.totalPages) {
                state.currentPage++;
                loadLogs();
            }
        });

        $('#page-last').on('click', function() {
            if (!$(this).prop('disabled')) {
                state.currentPage = state.totalPages;
                loadLogs();
            }
        });
    }

    /**
     * Initialize row selection
     */
    function initSelection() {
        // Select all checkbox
        $('#select-all').on('change', function() {
            var checked = $(this).prop('checked');
            $('#hml-log-tbody .hml-row-checkbox').prop('checked', checked);

            if (checked) {
                state.selectedIds = [];
                $('#hml-log-tbody .hml-row-checkbox').each(function() {
                    state.selectedIds.push(parseInt($(this).data('id')));
                });
            } else {
                state.selectedIds = [];
            }

            updateBulkActions();
        });

        // Individual row checkbox (delegated)
        $('#hml-log-tbody').on('change', '.hml-row-checkbox', function() {
            var id = parseInt($(this).data('id'));
            var checked = $(this).prop('checked');

            if (checked) {
                if (state.selectedIds.indexOf(id) === -1) {
                    state.selectedIds.push(id);
                }
            } else {
                state.selectedIds = state.selectedIds.filter(function(item) {
                    return item !== id;
                });
            }

            // Update select all checkbox
            var totalCheckboxes = $('#hml-log-tbody .hml-row-checkbox').length;
            var checkedCheckboxes = $('#hml-log-tbody .hml-row-checkbox:checked').length;
            $('#select-all').prop('checked', totalCheckboxes === checkedCheckboxes && totalCheckboxes > 0);

            updateBulkActions();
        });
    }

    /**
     * Update bulk actions visibility
     */
    function updateBulkActions() {
        var $bulkActions = $('#bulk-actions');
        var $selectedCount = $('#selected-count');

        if (state.selectedIds.length > 0) {
            $bulkActions.show();
            $selectedCount.text(state.selectedIds.length);
        } else {
            $bulkActions.hide();
        }
    }

    /**
     * Initialize action buttons
     */
    function initActions() {
        // Refresh logs
        $('#refresh-logs').on('click', function() {
            loadStats();
            loadLogs();
        });

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

        // Delete selected
        $('#delete-selected').on('click', function() {
            if (state.selectedIds.length > 0) {
                state.deleteMode = 'selected';
                $('#delete-message').text(switchboardHideLogin.strings.confirmDelete);
                showModal('delete-modal');
            }
        });

        // Delete all logs
        $('#delete-all-logs').on('click', function() {
            state.deleteMode = 'all';
            $('#delete-message').text(switchboardHideLogin.strings.confirmDeleteAll);
            showModal('delete-modal');
        });

        // Confirm delete
        $('#confirm-delete').on('click', function() {
            hideModal('delete-modal');
            if (state.deleteMode === 'selected') {
                deleteLogs(state.selectedIds);
            } else if (state.deleteMode === 'all') {
                deleteLogs([]);
            }
        });

        // View details (delegated)
        $('#hml-log-tbody').on('click', '.hml-view-details-btn', function() {
            var $row = $(this).closest('tr');
            showDetailsModal($row);
        });
    }

    /**
     * Initialize modals
     */
    function initModals() {
        // Close modal on overlay click
        $('.hml-modal-overlay, .hml-modal-close, .hml-modal-cancel').on('click', function() {
            hideModal($(this).closest('.hml-modal').attr('id'));
        });

        // Close on escape key
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape') {
                $('.hml-modal:visible').each(function() {
                    hideModal($(this).attr('id'));
                });
            }
        });
    }

    /**
     * Show modal
     */
    function showModal(modalId) {
        $('#' + modalId).fadeIn(200);
    }

    /**
     * Hide modal
     */
    function hideModal(modalId) {
        $('#' + modalId).fadeOut(200);
    }

    /**
     * Show details modal
     */
    function showDetailsModal($row) {
        var uri = $row.data('uri');
        var userAgent = $row.data('user-agent');
        var reason = $row.data('reason');

        $('#modal-request-uri').text(uri || '-');
        $('#modal-user-agent').text(userAgent || '-');

        if (reason) {
            $('#modal-block-reason').text(formatReason(reason));
            $('#modal-reason-row').show();
        } else {
            $('#modal-reason-row').hide();
        }

        showModal('user-agent-modal');
    }

    /**
     * Format block reason for display
     */
    function formatReason(reason) {
        var reasons = {
            'blocked_path': 'Blocked Path',
            'blocked_user_agent': 'Blocked User Agent',
            'rate_limited': 'Rate Limited',
            'honeypot_triggered': 'Honeypot Triggered'
        };
        return reasons[reason] || reason;
    }

    /**
     * Load stats
     */
    function loadStats() {
        $.post(switchboardHideLogin.ajaxUrl, {
            action: 'switchboard_hide_login_get_stats',
            nonce: switchboardHideLogin.nonce
        }, function(response) {
            if (response.success) {
                $('#stat-total').text(response.data.total || 0);
                $('#stat-blocked').text(response.data.total_blocked || 0);
                $('#stat-allowed').text(response.data.total_allowed || 0);
                $('#stat-today').text(response.data.today || 0);

                // Update top IPs
                updateTopIps(response.data.top_ips);
            }
        });
    }

    /**
     * Update top blocked IPs list
     */
    function updateTopIps(ips) {
        var $container = $('#top-ips-container');

        if (!ips || ips.length === 0) {
            $container.html('<p class="hml-no-data">No blocked IPs yet</p>');
            return;
        }

        var html = '<div class="hml-top-ips-list">';
        ips.forEach(function(ip) {
            html += '<div class="hml-top-ip-item">';
            html += '<span class="hml-top-ip-address">' + escapeHtml(ip.ip_address) + '</span>';
            html += '<span class="hml-top-ip-count">' + ip.count + '</span>';
            html += '</div>';
        });
        html += '</div>';

        $container.html(html);
    }

    /**
     * Load access logs
     */
    function loadLogs() {
        var $tbody = $('#hml-log-tbody');

        // Show loading state
        $tbody.html(
            '<tr><td colspan="7" class="sb-module-empty" style="padding: 60px 20px;">' +
            '<div class="sb-module-empty-icon dashicons dashicons-update" style="font-size: 48px; width: 48px; height: 48px; animation: spin 1s linear infinite;"></div>' +
            '<p class="sb-module-empty-desc">' + switchboardHideLogin.strings.loading + '</p>' +
            '</td></tr>'
        );

        $.post(switchboardHideLogin.ajaxUrl, {
            action: 'switchboard_hide_login_get_logs',
            nonce: switchboardHideLogin.nonce,
            page: state.currentPage,
            per_page: state.perPage,
            search: state.filters.search,
            type: state.filters.type,
            ip: state.filters.ip,
            date_from: state.filters.date_from,
            date_to: state.filters.date_to
        }, function(response) {
            if (response.success) {
                state.totalItems = response.data.total;
                state.totalPages = response.data.total_pages;

                renderLogs(response.data.logs);
                updatePagination();

                // Clear selection
                state.selectedIds = [];
                $('#select-all').prop('checked', false);
                updateBulkActions();
            } else {
                $tbody.html(
                    '<tr><td colspan="7" class="sb-module-empty" style="padding: 60px 20px;">' +
                    '<p class="sb-module-empty-desc">' + switchboardHideLogin.strings.error + '</p>' +
                    '</td></tr>'
                );
            }
        }).fail(function() {
            $tbody.html(
                '<tr><td colspan="7" class="sb-module-empty" style="padding: 60px 20px;">' +
                '<p class="sb-module-empty-desc">' + switchboardHideLogin.strings.error + '</p>' +
                '</td></tr>'
            );
        });
    }

    /**
     * Render logs table
     */
    function renderLogs(logs) {
        var $tbody = $('#hml-log-tbody');

        if (!logs || logs.length === 0) {
            $tbody.html(
                '<tr><td colspan="7" class="hml-empty-state">' +
                '<div class="hml-empty-icon dashicons dashicons-shield-alt"></div>' +
                '<p class="hml-empty-title">No access attempts found</p>' +
                '<p class="hml-empty-desc">Try adjusting your filters or check back later.</p>' +
                '</td></tr>'
            );
            $('#results-summary').text(switchboardHideLogin.strings.noResults);
            return;
        }

        var html = '';
        logs.forEach(function(log) {
            var datetime = formatDateTime(log.created_at);
            var statusClass = log.blocked == 1 ? 'hml-badge-danger' : 'hml-badge-success';
            var statusText = log.blocked == 1 ? 'Blocked' : 'Allowed';

            html += '<tr data-id="' + log.id + '" data-uri="' + escapeHtml(log.request_uri) + '" data-user-agent="' + escapeHtml(log.user_agent || '') + '" data-reason="' + escapeHtml(log.block_reason || '') + '">';
            html += '<td><input type="checkbox" class="hml-checkbox hml-row-checkbox" data-id="' + log.id + '"></td>';
            html += '<td><div class="hml-datetime"><span class="hml-date">' + datetime.date + '</span><span class="hml-time">' + datetime.time + '</span></div></td>';
            html += '<td><span class="hml-ip-address">' + escapeHtml(log.ip_address) + '</span></td>';
            html += '<td><span class="hml-type-badge">' + escapeHtml(log.request_type) + '</span></td>';
            html += '<td><span class="hml-badge ' + statusClass + '">' + statusText + '</span></td>';
            html += '<td class="hml-details-cell">';
            html += '<code class="hml-request-uri">' + escapeHtml(truncate(log.request_uri, 40)) + '</code>';
            if (log.block_reason) {
                html += '<br><small style="color: var(--hml-gray-500);">' + formatReason(log.block_reason) + '</small>';
            }
            html += '</td>';
            html += '<td><button type="button" class="hml-view-details-btn" title="View Details"><span class="dashicons dashicons-visibility"></span></button></td>';
            html += '</tr>';
        });

        $tbody.html(html);

        // Update results summary
        var start = (state.currentPage - 1) * state.perPage + 1;
        var end = Math.min(state.currentPage * state.perPage, state.totalItems);
        $('#results-summary').text('Showing ' + start + '-' + end + ' of ' + state.totalItems + ' entries');
    }

    /**
     * Update pagination controls
     */
    function updatePagination() {
        $('#page-first').prop('disabled', state.currentPage <= 1);
        $('#page-prev').prop('disabled', state.currentPage <= 1);
        $('#page-next').prop('disabled', state.currentPage >= state.totalPages);
        $('#page-last').prop('disabled', state.currentPage >= state.totalPages);

        $('#page-info').text('Page ' + state.currentPage + ' of ' + state.totalPages);
    }

    /**
     * Delete logs
     */
    function deleteLogs(ids) {
        $.post(switchboardHideLogin.ajaxUrl, {
            action: 'switchboard_hide_login_clear_logs',
            nonce: switchboardHideLogin.nonce,
            ids: ids
        }, function(response) {
            if (response.success) {
                state.selectedIds = [];
                loadStats();
                loadLogs();
            } else {
                alert(response.data.message || switchboardHideLogin.strings.error);
            }
        }).fail(function() {
            alert(switchboardHideLogin.strings.error);
        });
    }

    /**
     * Export logs as CSV
     */
    function exportCsv() {
        // Build URL with current filters so export matches the displayed view
        var params = {
            action: 'switchboard_hide_login_export_logs',
            nonce: switchboardHideLogin.nonce
        };

        // Add active filters
        if (state.filters.search) params.search = state.filters.search;
        if (state.filters.status) params.type = state.filters.status;
        if (state.filters.dateFrom) params.date_from = state.filters.dateFrom;
        if (state.filters.dateTo) params.date_to = state.filters.dateTo;

        var queryString = $.param(params);
        window.open(switchboardHideLogin.ajaxUrl + '?' + queryString, '_blank');
    }

    /**
     * Format datetime for display
     */
    function formatDateTime(datetime) {
        var date = new Date(datetime + ' UTC');

        // Format date
        var dateStr = date.toLocaleDateString(undefined, {
            year: 'numeric',
            month: 'short',
            day: 'numeric'
        });

        // Format time
        var timeStr = date.toLocaleTimeString(undefined, {
            hour: '2-digit',
            minute: '2-digit'
        });

        return {
            date: dateStr,
            time: timeStr
        };
    }

    /**
     * Truncate string
     */
    function truncate(str, length) {
        if (!str) return '';
        if (str.length <= length) return str;
        return str.substring(0, length) + '...';
    }

    /**
     * Escape HTML
     */
    function escapeHtml(text) {
        if (!text) return '';
        var div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

})(jQuery);
