/**
 * Guard Dog Activity Log Page JavaScript
 * 
 * Handles tab switching, filtering, and activity log interactions.
 *
 * @package GuardDog
 * @since 1.8.0
 */

(function($) {
    'use strict';

    const ACTIVITY_LOG_TAB_KEY = 'guard_dog_activity_log_active_tab';
    const ACTIVITY_LOG_TAB_QUERY_PARAM = 'activity_log_tab';
    const BLACKLIST_EXPIRATION_MIN_DAYS = 0;
    const BLACKLIST_EXPIRATION_MAX_DAYS = 3650;
    const BLACKLIST_EXPIRATION_DEFAULT_DAYS = 30;

    function clampBlacklistExpirationDays(expirationDays) {
        return Math.min(
            Math.max(expirationDays, BLACKLIST_EXPIRATION_MIN_DAYS),
            BLACKLIST_EXPIRATION_MAX_DAYS
        );
    }

    function normalizeBlacklistExpirationDays(value, defaultValue) {
        const parsedDefault = parseInt(defaultValue, 10);
        const fallback = Number.isNaN(parsedDefault)
            ? BLACKLIST_EXPIRATION_DEFAULT_DAYS
            : clampBlacklistExpirationDays(parsedDefault);
        const parsedValue = parseInt(value, 10);

        if (Number.isNaN(parsedValue)) {
            return fallback;
        }

        return clampBlacklistExpirationDays(parsedValue);
    }

    window.GuardDogActivityLog = window.GuardDogActivityLog || {};
    window.GuardDogActivityLog.blacklistExpirationMinDays = BLACKLIST_EXPIRATION_MIN_DAYS;
    window.GuardDogActivityLog.blacklistExpirationMaxDays = BLACKLIST_EXPIRATION_MAX_DAYS;
    window.GuardDogActivityLog.normalizeBlacklistExpirationDays = normalizeBlacklistExpirationDays;

    $(document).ready(function() {
        initTabNavigation();

        // Search functionality
        $('.guard-dog-search-input').on('input', function() {
            const searchTerm = $(this).val().toLowerCase();
            const $rows = $('.guard-dog-activity-table tbody tr');
            
            $rows.each(function() {
                const $row = $(this);
                const text = $row.text().toLowerCase();
                
                if (text.includes(searchTerm)) {
                    $row.show();
                } else {
                    $row.hide();
                }
            });
        });

        // Cleanup form handling
        const cleanupForm = document.querySelector('.guard-dog-cleanup-form');
        const cleanupSelect = document.getElementById('cleanup_event_types');
        const cleanupFallback = document.getElementById('cleanup_fallback');
        
        if (cleanupForm && cleanupSelect && cleanupFallback) {
            // Handle form submission
            cleanupForm.addEventListener('submit', function() {
                // If user has made specific selections, disable the fallback
                if (cleanupSelect.selectedOptions.length > 0) {
                    // Check if user selected something other than just "all"
                    let hasNonAllSelection = false;
                    for (let option of cleanupSelect.selectedOptions) {
                        if (option.value !== 'all') {
                            hasNonAllSelection = true;
                            break;
                        }
                    }
                    
                    // If user made specific selections, disable fallback
                    if (hasNonAllSelection || cleanupSelect.selectedOptions.length > 1) {
                        cleanupFallback.disabled = true;
                    }
                } else {
                    // No selection made, ensure fallback is active and select default
                    cleanupFallback.disabled = false;
                    cleanupSelect.options[0].selected = true;
                }
            });
        }

        // IP Reputation Check functionality
        initIpReputationCheck();
    });

    function initTabNavigation() {
        if (!window.GuardDogAdmin || typeof window.GuardDogAdmin.initScopedTabs !== 'function') {
            return;
        }

        window.GuardDogAdmin.initScopedTabs({
            storageKey: ACTIVITY_LOG_TAB_KEY,
            queryParam: ACTIVITY_LOG_TAB_QUERY_PARAM
        });
    }

    /**
     * Initialize IP Reputation Check functionality
     */
    function initIpReputationCheck() {
        // Prevent multiple initializations
        if (window.guardDogIpReputationInitialized) {
            return;
        }
        window.guardDogIpReputationInitialized = true;

        // Remove any existing handlers first to prevent duplicates
        $(document).off('click', '.guard-dog-check-ip-reputation');
        $(document).off('click', '.guard-dog-ip-reputation-modal-overlay, .guard-dog-ip-reputation-modal-close');
        $(document).off('click', '.guard-dog-add-ip-to-blacklist-btn');
        $(document).off('keydown.guardDogIpReputation');

        // Handle click on reputation check button
        $(document).on('click', '.guard-dog-check-ip-reputation', function(e) {
            e.preventDefault();
            e.stopPropagation();
            const $button = $(this);
            const ipAddress = $button.data('ip');
            
            if (!ipAddress) {
                console.error('No IP address found');
                return;
            }

            // Show loading state
            $button.prop('disabled', true).addClass('loading');
            
            // Check IP reputation
            checkIpReputation(ipAddress, $button);
        });

        // Handle modal close
        $(document).on('click', '.guard-dog-ip-reputation-modal-overlay', function(e) {
            // Only close if clicking directly on the overlay (backdrop), not on modal content
            if (e.target === e.currentTarget) {
                e.preventDefault();
                e.stopPropagation();
                closeIpReputationModal();
            }
        });
        
        // Handle close button click
        $(document).on('click', '.guard-dog-ip-reputation-modal-close', function(e) {
            e.preventDefault();
            e.stopPropagation();
            closeIpReputationModal();
        });

        // Handle add to blacklist button
        $(document).on('click', '.guard-dog-add-ip-to-blacklist-btn', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const $button = $(this);
            const ipAddress = $button.data('ip');
            const abuseConfidence = parseInt($button.data('abuse-confidence')) || 0;
            const $expirationInput = $('#guard-dog-blacklist-expiration');
            const defaultExpiration = typeof guard_dog_activity_log !== 'undefined' && guard_dog_activity_log.strings
                ? guard_dog_activity_log.strings.defaultExpiration
                : BLACKLIST_EXPIRATION_DEFAULT_DAYS;
            const expirationDays = normalizeBlacklistExpirationDays($expirationInput.val(), defaultExpiration);
            
            if (!ipAddress) {
                alert('Error: IP address not found. Please try again.');
                return;
            }
            
            if (typeof guard_dog_activity_log === 'undefined') {
                alert('Error: JavaScript configuration not loaded. Please refresh the page.');
                return;
            }
            
            addIpToBlacklist(ipAddress, expirationDays, $button, abuseConfidence);
        });

        // Close modal on Escape key (namespaced event)
        $(document).on('keydown.guardDogIpReputation', function(e) {
            if (e.key === 'Escape' && $('.guard-dog-ip-reputation-modal-overlay').is(':visible')) {
                closeIpReputationModal();
            }
        });
    }

    /**
     * Check IP reputation via AJAX
     */
    function checkIpReputation(ipAddress, $button) {
        $.ajax({
            url: guard_dog_activity_log.ajaxurl,
            type: 'POST',
            data: {
                action: 'guard_dog_check_ip_reputation',
                ip_address: ipAddress,
                nonce: guard_dog_activity_log.adminNonce
            },
            success: function(response) {
                $button.prop('disabled', false).removeClass('loading');
                
                if (response.success && response.data) {
                    showIpReputationModal(ipAddress, response.data);
                } else {
                    // Handle specific error cases
                    const errorData = response.data || {};
                    let errorMessage = errorData.message || errorData.error || guard_dog_activity_log.strings.error;
                    
                    // Add help link for API key errors
                    if (errorData.error_code === 'api_key_required' || errorData.error_code === 'authentication_failed') {
                        if (errorData.help_url) {
                            errorMessage += '\n\n' + guard_dog_activity_log.strings.getApiKeyHelp || 'Get a free API key at: ' + errorData.help_url;
                        }
                    }
                    
                    alert(errorMessage);
                }
            },
            error: function(xhr, status, error) {
                $button.prop('disabled', false).removeClass('loading');
                console.error('IP reputation check error:', error);
                alert(guard_dog_activity_log.strings.error);
            }
        });
    }

    /**
     * Show IP reputation modal
     */
    function showIpReputationModal(ipAddress, data) {
        // Prevent duplicate modals - if one is already showing, don't create another
        if ($('.guard-dog-ip-reputation-modal-overlay').length > 0) {
            console.log('Modal already visible, skipping duplicate');
            return;
        }
        
        // Remove any existing modal if any
        $('.guard-dog-ip-reputation-modal-overlay').remove();

        // Build threat indicators HTML
        let threatIndicatorsHtml = '';
        if (data.threat_indicators && data.threat_indicators.length > 0) {
            threatIndicatorsHtml = '<ul class="guard-dog-threat-indicators">';
            data.threat_indicators.forEach(function(indicator) {
                threatIndicatorsHtml += '<li>' + indicator + '</li>';
            });
            threatIndicatorsHtml += '</ul>';
        } else {
            threatIndicatorsHtml = '<p class="guard-dog-no-threats">' + guard_dog_activity_log.strings.noThreats + '</p>';
        }

        // Build modal HTML
        const modalHtml = `
            <div class="guard-dog-ip-reputation-modal-overlay">
                <div class="guard-dog-ip-reputation-modal">
                    <div class="guard-dog-ip-reputation-modal-header">
                        <h2>${guard_dog_activity_log.strings.ipReputationCheck || 'IP Reputation Check'}</h2>
                        <button type="button" class="guard-dog-ip-reputation-modal-close" aria-label="${guard_dog_activity_log.strings.close}">
                            <span class="dashicons dashicons-no-alt"></span>
                        </button>
                    </div>
                    <div class="guard-dog-ip-reputation-modal-body">
                        <div class="guard-dog-ip-info">
                            <strong>${guard_dog_activity_log.strings.ipAddress || 'IP Address'}:</strong> ${ipAddress}
                            ${data.reverse_dns ? `<br><small style="color: #666;">${guard_dog_activity_log.strings.reverseDns || 'Reverse DNS'}: ${data.reverse_dns}</small>` : ''}
                        </div>
                        <div class="guard-dog-reputation-details">
                            <h3 class="guard-dog-details-section-title">${guard_dog_activity_log.strings.reputationInfo || 'Reputation Information'}</h3>
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.abuseConfidence || 'Abuse Confidence'}:</span>
                                <span class="detail-value">${data.abuse_confidence || 0}%</span>
                            </div>
                            ${data.total_reports ? `
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.totalReports || 'Total Reports'}:</span>
                                <span class="detail-value">${data.total_reports}</span>
                            </div>
                            ` : ''}
                            ${data.num_distinct_users ? `
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.reportedBy || 'Reported By'}:</span>
                                <span class="detail-value">${data.num_distinct_users} ${guard_dog_activity_log.strings.users || 'users'}</span>
                            </div>
                            ` : ''}
                            ${data.last_reported_at ? `
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.lastReported || 'Last Reported'}:</span>
                                <span class="detail-value">${new Date(data.last_reported_at).toLocaleString()}</span>
                            </div>
                            ` : ''}
                        </div>
                        <div class="guard-dog-location-details">
                            <h3 class="guard-dog-details-section-title">${guard_dog_activity_log.strings.locationInfo || 'Location Information'}</h3>
                            ${data.country || data.country_code ? `
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.country || 'Country'}:</span>
                                <span class="detail-value">${data.country || data.country_code || ''} ${data.country_code && data.country ? `(${data.country_code})` : ''}</span>
                            </div>
                            ` : ''}
                            ${data.continent ? `
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.continent || 'Continent'}:</span>
                                <span class="detail-value">${data.continent}</span>
                            </div>
                            ` : ''}
                            ${data.region ? `
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.region || 'Region'}:</span>
                                <span class="detail-value">${data.region}</span>
                            </div>
                            ` : ''}
                            ${data.city ? `
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.city || 'City'}:</span>
                                <span class="detail-value">${data.city}</span>
                            </div>
                            ` : ''}
                            ${data.timezone ? `
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.timezone || 'Timezone'}:</span>
                                <span class="detail-value">${data.timezone}</span>
                            </div>
                            ` : ''}
                        </div>
                        <div class="guard-dog-network-details">
                            <h3 class="guard-dog-details-section-title">${guard_dog_activity_log.strings.networkInfo || 'Network Information'}</h3>
                            ${data.isp ? `
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.isp || 'ISP'}:</span>
                                <span class="detail-value">${data.isp}</span>
                            </div>
                            ` : ''}
                            ${data.org ? `
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.organization || 'Organization'}:</span>
                                <span class="detail-value">${data.org}</span>
                            </div>
                            ` : ''}
                            ${data.as || data.asname ? `
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.asNumber || 'AS Number'}:</span>
                                <span class="detail-value">${data.as || ''} ${data.asname ? `(${data.asname})` : ''}</span>
                            </div>
                            ` : ''}
                            ${data.domain ? `
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.domain || 'Domain'}:</span>
                                <span class="detail-value">${data.domain}</span>
                            </div>
                            ` : ''}
                            ${data.usage_type ? `
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.usageType || 'Usage Type'}:</span>
                                <span class="detail-value">${data.usage_type}</span>
                            </div>
                            ` : ''}
                            ${data.is_proxy || data.is_hosting || data.is_mobile ? `
                            <div class="detail-row">
                                <span class="detail-label">${guard_dog_activity_log.strings.networkType || 'Network Type'}:</span>
                                <span class="detail-value">
                                    ${data.is_proxy ? guard_dog_activity_log.strings.proxy || 'Proxy/VPN' : ''}
                                    ${data.is_proxy && data.is_hosting ? ', ' : ''}
                                    ${data.is_hosting ? guard_dog_activity_log.strings.hosting || 'Hosting' : ''}
                                    ${(data.is_proxy || data.is_hosting) && data.is_mobile ? ', ' : ''}
                                    ${data.is_mobile ? guard_dog_activity_log.strings.mobile || 'Mobile' : ''}
                                </span>
                            </div>
                            ` : ''}
                        </div>
                        ${data.threat_indicators && data.threat_indicators.length > 0 ? `
                        <div class="guard-dog-threat-section">
                            <h3>${guard_dog_activity_log.strings.threatIndicators || 'Threat Indicators'}:</h3>
                            ${threatIndicatorsHtml}
                        </div>
                        ` : ''}
                        <div class="guard-dog-blacklist-section">
                            <label for="guard-dog-blacklist-expiration">
                                ${guard_dog_activity_log.strings.expirationDays}:
                            </label>
                            <input type="number" 
                                   id="guard-dog-blacklist-expiration" 
                                   class="guard-dog-blacklist-expiration-input" 
                                   value="${guard_dog_activity_log.strings.defaultExpiration}" 
                                   min="${BLACKLIST_EXPIRATION_MIN_DAYS}"
                                   max="${BLACKLIST_EXPIRATION_MAX_DAYS}">
                            <button type="button" 
                                    class="button button-primary guard-dog-add-ip-to-blacklist-btn" 
                                    data-ip="${ipAddress}"
                                    data-abuse-confidence="${data.abuse_confidence || 0}">
                                ${guard_dog_activity_log.strings.addToBlacklist}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // Append modal to body
        $('body').append(modalHtml);
        
        // Show modal with animation
        setTimeout(function() {
            $('.guard-dog-ip-reputation-modal-overlay').addClass('active');
        }, 10);
    }

    /**
     * Close IP reputation modal
     */
    function closeIpReputationModal() {
        $('.guard-dog-ip-reputation-modal-overlay').removeClass('active');
        setTimeout(function() {
            $('.guard-dog-ip-reputation-modal-overlay').remove();
        }, 300);
    }

    /**
     * Add IP to blacklist via AJAX
     */
    function addIpToBlacklist(ipAddress, expirationDays, $button, abuseConfidence) {
        abuseConfidence = abuseConfidence || 0;
        
        // Validate required data
        if (!guard_dog_activity_log || !guard_dog_activity_log.ajaxurl) {
            alert('Error: AJAX URL not configured. Please refresh the page.');
            return;
        }
        
        if (!guard_dog_activity_log.adminNonce) {
            alert('Error: Security nonce not configured. Please refresh the page.');
            return;
        }
        
        const originalText = $button.text();
        $button.prop('disabled', true).text(guard_dog_activity_log.strings.adding || 'Adding...');
        
        const ajaxData = {
            action: 'guard_dog_add_ip_to_blacklist',
            ip_address: ipAddress,
            expiration_days: expirationDays,
            abuse_confidence: abuseConfidence,
            source: 'ip_reputation_check',
            nonce: guard_dog_activity_log.adminNonce
        };
        
        $.ajax({
            url: guard_dog_activity_log.ajaxurl,
            type: 'POST',
            data: ajaxData,
            success: function(response) {
                if (response.success) {
                    $button.text(guard_dog_activity_log.strings.addedToBlacklist).addClass('success');
                    setTimeout(function() {
                        closeIpReputationModal();
                        // Optionally reload the page to show updated blacklist
                        // window.location.reload();
                    }, 1500);
                } else {
                    $button.prop('disabled', false).text(originalText);
                    alert(response.data?.message || guard_dog_activity_log.strings.error);
                }
            },
            error: function(xhr, status, error) {
                $button.prop('disabled', false).text(originalText);
                
                // Try to parse error response
                let errorMessage = guard_dog_activity_log.strings.error;
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.data && response.data.message) {
                        errorMessage = response.data.message;
                    }
                } catch (e) {
                    // Use default error message
                }
                
                alert(errorMessage);
            }
        });
    }

})(jQuery); 
