
<?php $nonce = wp_create_nonce( 'quttera' ); ?>

<script type="text/javascript">

(function() {
    'use strict';

    const REFRESH_INTERVAL = 30000; // 30 seconds
    let autoRefreshTimer = null;

    /**
     * Initialize page on load
     */
    jQuery(document).ready(function($) {
        console.log('Brute-Force Frontend: Initializing...');
        
        // Fetch initial data
        renderBruteForceBlockedList();
        
        // Set up auto-refresh
        autoRefreshTimer = setInterval(renderBruteForceBlockedList, REFRESH_INTERVAL);
        
        // Bind clear all button
        document.getElementById('clear_all_blocked_btn').addEventListener('click', clearAllBruteForceBlockedIPs);
    });

    /**
     * Render blocked IPs list via AJAX
     */
    function renderBruteForceBlockedList() {
        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {
                action: 'scanner-get-bruteforce-blocked-ips',
                _wpnonce: '<?php echo $nonce; ?>',
            },
            timeout: 30000,
            error: function(jqXHR, textStatus) {
                console.error('Failed to fetch blocked IPs:', textStatus);
                updateRefreshTime('error');
            },
            success: function(response) {
                console.log('Fetched brute-force blocked IPs:', response);
                
                if (!response.success) {
                    console.error('Server error:', response.message);
                    updateRefreshTime('error');
                    return;
                }
                
                const blockedIPs = response.data?.blocked_ips || [];
                updateBruteForceBlockedDisplay(blockedIPs);
                updateRefreshTime('success');
            }
        });
    }

    /**
     * Update the display of blocked IPs
     * @param {Array} blockedIPs - Array of blocked IP objects
     */
    function updateBruteForceBlockedDisplay(blockedIPs) {
        const container = document.getElementById('bruteforce_blocked_ips_list');
        const emptyMsg = document.getElementById('bruteforce_blocked_empty');
        const clearBtn = document.getElementById('clear_all_blocked_btn');

        container.innerHTML = '';

        if (blockedIPs.length === 0) {
            emptyMsg.style.display = 'block';
            clearBtn.style.display = 'none';
            return;
        }

        emptyMsg.style.display = 'none';
        clearBtn.style.display = 'inline-block';

        // Render each blocked IP
        blockedIPs.forEach(function(ipData) {
            const item = document.createElement('div');
            item.className = 'bruteforce-block-item';
            
            item.innerHTML = `
                <div style="display: flex; justify-content: space-between; align-items: flex-start;">
                    <div style="flex: 1;">
                        <div class="bruteforce-block-ip">${escapeHtml(ipData.ip)}</div>
                        <div class="bruteforce-block-details">
                            Locked: <span title="${escapeHtml(ipData.locked_at)}">${escapeHtml(ipData.locked_full)}</span>
                            <br/>
                            Expires: <span title="${escapeHtml(ipData.expires_at)}">${escapeHtml(ipData.expiry_full)}</span> (${escapeHtml(ipData.expiry_relative)})
                        </div>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-warning" onclick="removeBlockedIP('${escapeHtml(ipData.ip)}')" style="margin-left: 12px;">
                        <i class="bi bi-unlock"></i> Unlock
                    </button>
                </div>
            `;
            container.appendChild(item);
        });
    }

    /**
     * Remove a single blocked IP (manual unlock)
     * @param {string} ip - IP address to unlock
     */
    function removeBlockedIP(ip) {
        if (!confirm('Unlock IP: ' + ip + '?\n\nThis will remove the temporary block and allow the IP to attempt login again.')) {
            return;
        }

        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {
                action: 'scanner-remove-bruteforce-blocked-ip',
                ip: ip,
                _wpnonce: '<?php echo $nonce; ?>',
            },
            timeout: 30000,
            error: function(jqXHR, textStatus) {
                console.error('Failed to unlock IP:', textStatus);
                alert('Error unlocking IP. Please try again.');
            },
            success: function(response) {
                if (!response.success) {
                    console.error('Server error:', response.message);
                    alert(response.message || 'Failed to unlock IP');
                    return;
                }
                
                renderBruteForceBlockedList();
            }
        });
    }

    /**
     * Clear all blocked IPs
     */
    function clearAllBruteForceBlockedIPs() {
        if (!confirm('Clear ALL blocked IPs?\n\nThis will unlock all currently blocked IP addresses immediately. This action cannot be undone.')) {
            return;
        }

        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {
                action: 'scanner-clear-all-bruteforce-blocked-ips',
                _wpnonce: '<?php echo $nonce; ?>',                
            },
            timeout: 30000,
            error: function(jqXHR, textStatus) {
                console.error('Failed to clear blocked IPs:', textStatus);
                alert('Error clearing blocked IPs. Please try again.');
            },
            success: function(response) {
                if (!response.success) {
                    console.error('Server error:', response.message);
                    alert(response.message || 'Failed to clear blocked IPs');
                    return;
                }
                
                renderBruteForceBlockedList();
            }
        });
    }

    /**
     * Format a Date object as "X ago" format
     * @param {Date} date 
     * @returns {string}
     */
    function formatTimeAgo(date) {
        const now = new Date();
        const seconds = Math.floor((now - date) / 1000);
        
        if (seconds < 60) return seconds + 's';
        const minutes = Math.floor(seconds / 60);
        if (minutes < 60) return minutes + 'm';
        const hours = Math.floor(minutes / 60);
        if (hours < 24) return hours + 'h';
        const days = Math.floor(hours / 24);
        return days + 'd';
    }

    /**
     * Format a Date object as "X ago" format
     * @param {Date} date 
     * @returns {string}
     */
    function formatTimeAgo(date) {
        const now = new Date();
        const seconds = Math.floor((now - date) / 1000);
        
        if (seconds < 60) return seconds + 's';
        const minutes = Math.floor(seconds / 60);
        if (minutes < 60) return minutes + 'm';
        const hours = Math.floor(minutes / 60);
        if (hours < 24) return hours + 'h';
        const days = Math.floor(hours / 24);
        return days + 'd';
    }

    /**
     * Update the last refresh time display
     * @param {string} status - 'success' or 'error'
     */
    function updateRefreshTime(status = 'success') {
        const timeEl = document.getElementById('refresh_time');
        const now = new Date();
        const timeStr = now.toLocaleTimeString();
        
        if (status === 'error') {
            timeEl.innerHTML = 'Last update failed. <a href="#" onclick="renderBruteForceBlockedList(); return false;">Retry</a>';
            timeEl.style.color = '#dc2626';
        } else {
            timeEl.innerHTML = `Last updated: ${timeStr} (refreshes every 30 seconds)`;
            timeEl.style.color = '#9ca3af';
        }
    }

    /**
     * Escape HTML special characters for safe display
     * @param {*} text - Text to escape (handles strings, numbers, etc)
     * @returns {string}
     */
    function escapeHtml(text) {
        // Handle non-string types (numbers, null, undefined, etc)
        text = String(text || '');
        
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }

    // Export functions to global scope for onclick handlers
    window.removeBlockedIP = removeBlockedIP;
    window.clearAllBruteForceBlockedIPs = clearAllBruteForceBlockedIPs;
    window.renderBruteForceBlockedList = renderBruteForceBlockedList;
})();
</script>
