jQuery(document).ready(function($) {
    var currentTab = 'ip';
    var searchTimeout;
    
    // Създаваме модалния прозорец
    var $modal = $('<div class="thia-modal-overlay">\
        <div class="thia-modal">\
            <div class="thia-modal-header">\
                <h3>Confirm Unblock</h3>\
                <button class="thia-modal-close">&times;</button>\
            </div>\
            <div class="thia-modal-body">\
                <p id="thia-modal-message"></p>\
            </div>\
            <div class="thia-modal-footer">\
                <button class="thia-modal-cancel button">Cancel</button>\
                <button class="thia-modal-confirm button button-primary">Confirm</button>\
            </div>\
        </div>\
    </div>');
    
    $('body').append($modal);
    $modal.hide();
    
    // Tab switching
    $('.thia-tab-btn').on('click', function() {
        $('.thia-tab-btn').removeClass('active');
        $(this).addClass('active');
        currentTab = $(this).data('tab');
        $('#thia-search-input').attr('placeholder', currentTab === 'ip' ? 'Search by IP address...' : 'Search by email address...');
        $('#thia-search-input').val('');
        $('#thia-search-results').html('<div class="thia-search-message">Enter search term to find blocked ' + (currentTab === 'ip' ? 'IPs' : 'emails') + '</div>');
    });
    
    // Search function
    function performSearch() {
        var searchTerm = $('#thia-search-input').val().trim();
        
        if (searchTerm === '') {
            $('#thia-search-results').html('<div class="thia-search-message">Enter search term to find blocked ' + (currentTab === 'ip' ? 'IPs' : 'emails') + '</div>');
            return;
        }
        
        $('#thia-search-results').html('<div class="thia-search-message">Searching... <span class="thia-loading-small"></span></div>');
        
        $.ajax({
            url: thia_admin.ajax_url,
            type: 'POST',
            data: {
                action: 'thia_search_blocked',
                nonce: thia_admin.nonce,
                search: searchTerm,
                type: currentTab
            },
            success: function(response) {
                console.log('Search response:', response);
                if (response.success && response.data.length > 0) {
                    var html = '<table class="thia-result-table">';
                    html += '<thead>';
                    html += '<th>' + (currentTab === 'ip' ? 'IP Address' : 'Email') + '</th>';
                    html += '<th>Date Blocked</th>';
                    html += '<th>Action</th>';
                    html += '</thead><tbody>';
                    
                    $.each(response.data, function(i, item) {
                        var rowId = (currentTab === 'ip' ? item.value.replace(/\./g, '-') : item.value.replace(/[@.]/g, '-'));
                        html += '<tr id="row-' + rowId + '">';
                        html += '<td>' + escapeHtml(item.value) + '</td>';
                        html += '<td>' + item.date + '</td>';
                        html += '<td><button class="thia-unblock-btn" data-type="' + currentTab + '" data-value="' + escapeHtml(item.value) + '">Unblock</button></td>';
                        html += '</tr>';
                    });
                    
                    html += '</tbody></table>';
                    $('#thia-search-results').html(html);
                } else {
                    $('#thia-search-results').html('<div class="thia-search-message">No results found for "' + escapeHtml(searchTerm) + '"</div>');
                }
            },
            error: function(xhr, status, error) {
                console.log('AJAX Error:', error);
                console.log('Response:', xhr.responseText);
                $('#thia-search-results').html('<div class="thia-search-message">Error occurred. Please try again.</div>');
            }
        });
    }
    
    // Search on button click
    $('#thia-search-btn').on('click', function() {
        performSearch();
    });
    
    // Search on enter key
    $('#thia-search-input').on('keypress', function(e) {
        if (e.which === 13) {
            e.preventDefault();
            performSearch();
        }
    });
    
    // Debounced search while typing
    $('#thia-search-input').on('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(function() {
            performSearch();
        }, 500);
    });
    
    // Unblock function with modal
    var pendingUnblock = null;
    
    $(document).on('click', '.thia-unblock-btn', function() {
        var $btn = $(this);
        var type = $btn.data('type');
        var value = $btn.data('value');
        
        var confirmMsg = type === 'ip' 
            ? 'Are you sure you want to unblock IP: <strong>' + escapeHtml(value) + '</strong>?' 
            : 'Are you sure you want to unblock user: <strong>' + escapeHtml(value) + '</strong>?';
        
        $('#thia-modal-message').html(confirmMsg);
        
        pendingUnblock = {
            $btn: $btn,
            type: type,
            value: value
        };
        
        $modal.fadeIn(200);
    });
    
    // Modal close/cancel
    $('.thia-modal-close, .thia-modal-cancel').on('click', function() {
        $modal.fadeOut(200);
        pendingUnblock = null;
    });
    
    // Modal confirm
    $('.thia-modal-confirm').on('click', function() {
        if (!pendingUnblock) return;
        
        var $btn = pendingUnblock.$btn;
        var type = pendingUnblock.type;
        var value = pendingUnblock.value;
        var action = type === 'ip' ? 'thia_unblock_ip' : 'thia_unblock_user';
        var data = type === 'ip' ? { ip: value } : { email: value };
        
        $modal.fadeOut(200);
        
        $btn.prop('disabled', true).text('Removing...');
        
        $.ajax({
            url: thia_admin.ajax_url,
            type: 'POST',
            data: {
                action: action,
                nonce: thia_admin.nonce,
                ...data
            },
            success: function(response) {
                if (response.success) {
                    var rowId = '#row-' + (type === 'ip' ? value.replace(/\./g, '-') : value.replace(/[@.]/g, '-'));
                    $(rowId).fadeOut(300, function() {
                        $(this).remove();
                        if ($('.thia-result-table tbody tr').length === 0) {
                            $('#thia-search-results').html('<div class="thia-search-message">No results found</div>');
                        }
                    });
                    
                    var $msg = $('<div class="notice notice-success is-dismissible"><p>' + response.data.message + '</p></div>');
                    $('.thia-search-form').before($msg);
                    setTimeout(function() { $msg.fadeOut(300, function() { $(this).remove(); }); }, 3000);
                } else {
                    showModalMessage('Error', 'Failed to unblock: ' + (response.data || 'Unknown error'), 'error');
                    $btn.prop('disabled', false).text('Unblock');
                }
                pendingUnblock = null;
            },
            error: function() {
                showModalMessage('Error', 'Error occurred. Please try again.', 'error');
                $btn.prop('disabled', false).text('Unblock');
                pendingUnblock = null;
            }
        });
    });
    
    function showModalMessage(title, message, type) {
        $('#thia-modal-message').html(message);
        $('.thia-modal-header h3').text(title);
        $modal.fadeIn(200);
        
        // Auto close after 2 seconds for errors
        if (type === 'error') {
            setTimeout(function() {
                $modal.fadeOut(200);
            }, 2000);
        }
    }
    
    function escapeHtml(str) {
        if (!str) return '';
        return str.replace(/[&<>]/g, function(m) {
            if (m === '&') return '&amp;';
            if (m === '<') return '&lt;';
            if (m === '>') return '&gt;';
            return m;
        });
    }
    
    // Close modal on overlay click
    $('.thia-modal-overlay').on('click', function(e) {
        if (e.target === this) {
            $modal.fadeOut(200);
            pendingUnblock = null;
        }
    });
});