/**
 * SiteStaffr Banned Visitors Management
 *
 * Handles loading, banning, and unbanning visitors on the Calls page banned tab.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/js
 * @since      1.2.3
 */

(function($) {
    'use strict';

    var data = window.sitestaffrBannedData;
    if (!data) {
        return;
    }

    $(document).ready(function() {
        // Auto-load banned numbers on banned view
        loadBannedNumbers();

        // Function to load banned numbers from AJAX
        function loadBannedNumbers() {
            // Show loading state
            $('#sitestaffr-banned-loading').show();
            $('#sitestaffr-banned-table').hide();
            $('#sitestaffr-banned-empty').hide();

            // AJAX request
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'sitestaffr_get_banned_visitors',
                    nonce: data.nonce
                },
                success: function(response) {
                    // Hide loading
                    $('#sitestaffr-banned-loading').hide();

                    if (response.success && response.data.banned_numbers) {
                        var bannedNumbers = response.data.banned_numbers;

                        if (bannedNumbers.length === 0) {
                            // Show empty state
                            $('#sitestaffr-banned-empty').show();
                        } else {
                            // Populate table
                            populateBannedTable(bannedNumbers);
                            $('#sitestaffr-banned-table').show();
                        }
                    } else {
                        // Error or no data - show empty state
                        $('#sitestaffr-banned-empty').show();
                    }
                },
                error: function(xhr, status, error) {
                    $('#sitestaffr-banned-loading').hide();
                    console.error('SiteStaffr: Failed to load banned numbers:', error);
                    alert(data.i18n.loadFailed);
                }
            });
        }

        // Function to populate table with banned numbers
        function populateBannedTable(bannedNumbers) {
            var tbody = $('#sitestaffr-banned-table-body');
            tbody.empty();

            $.each(bannedNumbers, function(index, item) {
                var identifierDisplay = String(item.display || '').trim();
                if (!identifierDisplay && item.metadata && item.metadata.ip_address) {
                    identifierDisplay = String(item.metadata.ip_address).trim();
                }
                if (!identifierDisplay) {
                    identifierDisplay = String(item.identifier || '').trim();
                }
                if (!identifierDisplay) {
                    identifierDisplay = data.i18n.unknown;
                }

                var row = '<tr>' +
                    '<td class="column-phone"><strong>' + escapeHtml(identifierDisplay) + '</strong></td>' +
                    '<td class="column-date">' + escapeHtml(item.date) + '</td>' +
                    '<td class="column-reason">' + escapeHtml(item.reason) + '</td>' +
                    '<td class="column-actions">' +
                        '<button type="button" class="button sitestaffr-unban-btn" data-key="' + escapeHtml(item.key || '') + '" data-identifier="' + escapeHtml(item.identifier || '') + '" data-type="' + escapeHtml(item.type || '') + '">' +
                            data.i18n.unban +
                        '</button>' +
                    '</td>' +
                '</tr>';

                tbody.append(row);
            });
        }

        // Helper function to escape HTML
        function escapeHtml(text) {
            var map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
        }

        // Helper function to show success/error messages in banned numbers tab
        function showBannedNotice(type, message) {
            // Remove any existing notices
            $('#tab-content-banned-numbers .sitestaffr-banned-notice').remove();

            // Create notice element
            var noticeClass = type === 'success' ? 'notice-success' : 'notice-error';
            var notice = $('<div class="notice ' + noticeClass + ' is-dismissible sitestaffr-banned-notice" style="margin: 20px 0;"><p>' + escapeHtml(message) + '</p></div>');

            // Insert at top of banned numbers tab
            $('#tab-content-banned-numbers').prepend(notice);

            // Auto-dismiss after 3 seconds
            setTimeout(function() {
                notice.fadeOut(300, function() {
                    $(this).remove();
                });
            }, 3000);

            // Allow manual dismiss
            notice.on('click', '.notice-dismiss', function() {
                notice.fadeOut(300, function() {
                    $(this).remove();
                });
            });
        }

        // Unban button click handler
        $(document).on('click', '.sitestaffr-unban-btn', function() {
            var banKey = String($(this).data('key') || '');
            var identifier = String($(this).data('identifier') || '');
            var banType = String($(this).data('type') || 'phone');
            var $button = $(this);

            // Show confirmation dialog
            if (!confirm(data.i18n.confirmUnban + '\n\n' + identifier)) {
                return;
            }

            // Disable button and show loading state
            $button.prop('disabled', true).text(data.i18n.unbanning);

            // AJAX request to unban number
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'sitestaffr_unban_visitor',
                    ban_key: banKey,
                    identifier: identifier,
                    ban_type: banType,
                    nonce: data.nonce
                },
                success: function(response) {
                    if (response.success) {
                        showBannedNotice('success', data.i18n.unbanSuccess);
                        loadBannedNumbers();
                    } else {
                        var errorMsg = response.data && response.data.message ? response.data.message : data.i18n.unbanFailed;
                        showBannedNotice('error', errorMsg);
                        $button.prop('disabled', false).text(data.i18n.unban);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('SiteStaffr: Unban failed:', error);
                    showBannedNotice('error', data.i18n.unbanFailed);
                    $button.prop('disabled', false).text(data.i18n.unban);
                }
            });
        });

        // Ban User button click handler
        $('#sitestaffr-open-ban-modal, #sitestaffr-tab-ban-btn').on('click', function() {
            // Clear form
            $('#sitestaffr-ban-phone').val('').removeClass('error');
            $('#sitestaffr-ban-reason').val('');
            $('#sitestaffr-ban-phone-error').hide();

            // Show modal
            $('#sitestaffr-ban-modal').fadeIn(200);
        });

        // Close modal on X button click
        $('#sitestaffr-close-ban-modal, #sitestaffr-cancel-ban').on('click', function() {
            $('#sitestaffr-ban-modal').fadeOut(200);
        });

        // Close modal on overlay click
        $('.sitestaffr-modal-overlay').on('click', function() {
            $('#sitestaffr-ban-modal').fadeOut(200);
        });

        // Close modal on Escape key
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && $('#sitestaffr-ban-modal').is(':visible')) {
                $('#sitestaffr-ban-modal').fadeOut(200);
            }
        });

        // Validate identifier input (WebRTC-first: not phone-only).
        function validateIdentifier(identifier) {
            return !!String(identifier || '').trim();
        }

        // Ban User form submission
        $('#sitestaffr-submit-ban').on('click', function() {
            var phone = $('#sitestaffr-ban-phone').val().trim();
            var reason = $('#sitestaffr-ban-reason').val().trim();

            // Clear previous errors
            $('#sitestaffr-ban-phone').removeClass('error');
            $('#sitestaffr-ban-phone-error').hide();

            // Validate identifier
            if (!phone) {
                $('#sitestaffr-ban-phone').addClass('error');
                $('#sitestaffr-ban-phone-error')
                    .text(data.i18n.identifierRequired)
                    .show();
                return;
            }

            if (!validateIdentifier(phone)) {
                $('#sitestaffr-ban-phone').addClass('error');
                $('#sitestaffr-ban-phone-error')
                    .text(data.i18n.invalidIdentifier)
                    .show();
                return;
            }

            // Disable submit button and show loading state
            var $submitBtn = $('#sitestaffr-submit-ban');
            $submitBtn.prop('disabled', true).html('<span class="spinner is-active" style="float: none; margin: 0 8px 0 0;"></span>' + data.i18n.banning);

            // AJAX request to ban number
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'sitestaffr_ban_visitor',
                    identifier: phone,
                    reason: reason,
                    nonce: data.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Close modal
                        $('#sitestaffr-ban-modal').fadeOut(200);
                        showBannedNotice('success', data.i18n.banSuccess);
                        loadBannedNumbers();
                    } else {
                        var errorMsg = response.data && response.data.message ? response.data.message : data.i18n.banFailed;
                        $('#sitestaffr-ban-phone').addClass('error');
                        $('#sitestaffr-ban-phone-error').text(errorMsg).show();
                    }

                    // Re-enable submit button
                    $submitBtn.prop('disabled', false).html('<span class="dashicons dashicons-shield" style="vertical-align: middle; margin-right: 4px;"></span>' + data.i18n.banUser);
                },
                error: function(xhr, status, error) {
                    console.error('SiteStaffr: Ban failed:', error);
                    $('#sitestaffr-ban-phone').addClass('error');
                    $('#sitestaffr-ban-phone-error').text(data.i18n.banFailed).show();

                    // Re-enable submit button
                    $submitBtn.prop('disabled', false).html('<span class="dashicons dashicons-shield" style="vertical-align: middle; margin-right: 4px;"></span>' + data.i18n.banUser);
                }
            });
        });
    });

})(jQuery);
