/**
 * List2Play Servers Admin JavaScript
 */

(function($) {
    'use strict';
    
    $(document).ready(function() {
        // Escape HTML function
        function escapeHtml(text) {
            if (!text) return '';
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
        }
        
        let allServers = [];
        let selectedServerIds = (typeof list2playAdmin !== 'undefined' && list2playAdmin.selectedServerIds) ? list2playAdmin.selectedServerIds : [];
        let serverOrder = (typeof list2playAdmin !== 'undefined' && list2playAdmin.serverOrder) ? list2playAdmin.serverOrder : [];
        
        // Auto-load servers on page load (always)
        loadServers();
        
        // Load servers from API
        function loadServers() {
            const $list = $('#list2play-servers-list');
            
            // Check if list2playAdmin is defined
            if (typeof list2playAdmin === 'undefined') {
                $list.html('<div class="list2play-error-message">Error: list2playAdmin is not defined. Please refresh the page.</div>');
                return;
            }
            
            $list.html('<div class="list2play-loading">Loading servers...</div>');
            
            $.ajax({
                url: list2playAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'list2play_get_user_servers',
                    nonce: list2playAdmin.nonce,
                },
                success: function(response) {
                    if (response.success && response.data && response.data.servers) {
                        allServers = response.data.servers;
                        
                        // If no servers are selected yet, auto-select all user servers
                        if (selectedServerIds.length === 0) {
                            selectedServerIds = allServers.map(function(server) {
                                return server.id;
                            });
                        }
                        
                        renderServerList(allServers);
                        
                        // Restore previously selected servers from saved option
                        if (selectedServerIds.length > 0) {
                            selectedServerIds.forEach(function(serverId) {
                                $('#server-' + serverId).prop('checked', true);
                            });
                        }
                        
                        // Update selectedServerIds from checkboxes
                        loadSelectedFromCheckboxes();
                    } else {
                        const errorMsg = (response.data && response.data.message) ? response.data.message : 'Failed to load servers. Please check your API token in settings.';
                        $list.html('<div class="list2play-error-message">' + escapeHtml(errorMsg) + '</div>');
                    }
                },
                error: function(xhr, status, error) {
                    let errorMsg = 'Failed to load servers. ';
                    if (xhr.status === 0) {
                        errorMsg += 'Network error. Please check your connection.';
                    } else if (xhr.status === 403) {
                        errorMsg += 'Access denied. Please check your API token.';
                    } else {
                        errorMsg += 'Error: ' + error + ' (Status: ' + xhr.status + ')';
                    }
                    $list.html('<div class="list2play-error-message">' + escapeHtml(errorMsg) + '</div>');
                }
            });
        }
        
        // Refresh servers button (manual trigger)
        $('#list2play-load-servers').on('click', function() {
            const $button = $(this);
            $button.prop('disabled', true).text('Refreshing...');
            loadServers();
            setTimeout(function() {
                $button.prop('disabled', false).text('Refresh Servers');
            }, 1000);
        });
        
        // Render server list with checkboxes and drag & drop
        function renderServerList(servers) {
            const $list = $('#list2play-servers-list');
            
            if (servers.length === 0) {
                $list.html('<p class="description">No servers found.</p>');
                return;
            }
            
            // Sort servers by saved order
            let sortedServers = sortServersByOrder(servers);
            
            let html = '<ul class="list2play-server-checkbox-list sortable-list">';
            
            sortedServers.forEach(function(server) {
                const isChecked = selectedServerIds.includes(server.id) ? 'checked' : '';
                const statusClass = server.status === 'online' ? 'online' : 'offline';
                const statusText = server.status === 'online' ? 'Online' : 'Offline';
                
                html += '<li class="list2play-server-checkbox-item" data-server-id="' + server.id + '">';
                html += '<span class="drag-handle" title="Drag to reorder">☰</span>';
                html += '<input type="checkbox" id="server-' + server.id + '" value="' + server.id + '" ' + isChecked + '>';
                html += '<label for="server-' + server.id + '">' + escapeHtml(server.hostname) + '</label>';
                html += '<span class="server-id">ID: ' + server.id + '</span>';
                html += '<span class="server-status ' + statusClass + '">' + statusText + '</span>';
                html += '</li>';
            });
            
            html += '</ul>';
            $list.html(html);
            
            // Initialize sortable
            initSortable();
        }
        
        // Sort servers by saved order
        function sortServersByOrder(servers) {
            if (serverOrder.length === 0) {
                return servers;
            }
            
            // Create a map of server order
            let orderMap = {};
            serverOrder.forEach(function(serverId, index) {
                orderMap[serverId] = index;
            });
            
            // Sort servers
            return servers.sort(function(a, b) {
                let orderA = orderMap[a.id] !== undefined ? orderMap[a.id] : 999999;
                let orderB = orderMap[b.id] !== undefined ? orderMap[b.id] : 999999;
                return orderA - orderB;
            });
        }
        
        // Initialize jQuery UI Sortable
        function initSortable() {
            $('.list2play-server-checkbox-list').sortable({
                handle: '.drag-handle',
                axis: 'y',
                cursor: 'move',
                opacity: 0.6,
                tolerance: 'pointer',
                update: function(event, ui) {
                    saveServerOrder();
                }
            });
        }
        
        // Save server order
        function saveServerOrder() {
            let newOrder = [];
            $('.list2play-server-checkbox-item').each(function() {
                newOrder.push(parseInt($(this).data('server-id')));
            });
            
            serverOrder = newOrder;
            
            $.ajax({
                url: list2playAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'list2play_save_server_order',
                    nonce: list2playAdmin.nonce,
                    server_order: newOrder,
                },
                success: function(response) {
                    if (response.success) {
                        showMessage('Server order saved.', 'success');
                    } else {
                        showMessage(response.data?.message || 'Failed to save order.', 'error');
                    }
                },
                error: function() {
                    showMessage('Failed to save server order.', 'error');
                }
            });
        }
        
        // Load selected servers from checkboxes
        function loadSelectedFromCheckboxes() {
            selectedServerIds = [];
            $('input[type="checkbox"][id^="server-"]:checked').each(function() {
                selectedServerIds.push(parseInt($(this).val()));
            });
        }
        
        // Update selected servers when checkbox changes
        $(document).on('change', 'input[type="checkbox"][id^="server-"]', function() {
            loadSelectedFromCheckboxes();
        });
        
        // Select all
        $('#list2play-select-all').on('click', function() {
            $('input[type="checkbox"][id^="server-"]').prop('checked', true);
            loadSelectedFromCheckboxes();
        });
        
        // Deselect all
        $('#list2play-deselect-all').on('click', function() {
            $('input[type="checkbox"][id^="server-"]').prop('checked', false);
            selectedServerIds = [];
        });
        
        // Save selection
        $('#list2play-save-selection').on('click', function() {
            const $button = $(this);
            loadSelectedFromCheckboxes();
            
            $button.prop('disabled', true).text('Saving...');
            
            $.ajax({
                url: list2playAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'list2play_save_selected_servers',
                    nonce: list2playAdmin.nonce,
                    server_ids: selectedServerIds,
                },
                success: function(response) {
                    if (response.success) {
                        showMessage('Selected servers saved successfully.', 'success');
                    } else {
                        showMessage(response.data?.message || 'Failed to save selection.', 'error');
                    }
                },
                error: function() {
                    showMessage('Failed to save selection.', 'error');
                },
                complete: function() {
                    $button.prop('disabled', false).text('Save Selection');
                }
            });
        });
        
        // Show message
        function showMessage(message, type) {
            const $message = $('<div class="list2play-' + type + '-message notice notice-' + type + ' is-dismissible" style="margin: 10px 0;"><p>' + escapeHtml(message) + '</p></div>');
            $('#list2play-server-selection').prepend($message);
            
            setTimeout(function() {
                $message.fadeOut(function() {
                    $(this).remove();
                });
            }, 3000);
        }
        
        // Add server by ID
        $('#list2play-add-server-btn').on('click', function() {
            const serverId = parseInt($('#list2play-add-server-id').val());
            const $button = $(this);
            const $input = $('#list2play-add-server-id');
            
            if (!serverId || serverId < 1) {
                showMessage('Please enter a valid server ID.', 'error');
                return;
            }
            
            // Check if server already exists
            if (allServers.some(function(s) { return s.id === serverId; })) {
                showMessage('Server is already in the list.', 'error');
                return;
            }
            
            $button.prop('disabled', true).text('Loading...');
            
            $.ajax({
                url: list2playAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'list2play_get_server_by_id',
                    nonce: list2playAdmin.nonce,
                    server_id: serverId,
                },
                success: function(response) {
                    if (response.success && response.data.server) {
                        const server = response.data.server;
                        
                        // Add server to allServers array if not already there
                        if (!allServers.some(function(s) { return s.id === serverId; })) {
                            allServers.push(server);
                        }
                        
                        // Add to selectedServerIds if not already there
                        if (!selectedServerIds.includes(serverId)) {
                            selectedServerIds.push(serverId);
                        }
                        
                        renderServerList(allServers);
                        
                        // Check the newly added server
                        $('#server-' + serverId).prop('checked', true);
                        
                        // Ensure the new server is in selectedServerIds before saving
                        if (!selectedServerIds.includes(serverId)) {
                            selectedServerIds.push(serverId);
                        }
                        
                        // Automatically save selection when server is added
                        // Make sure we have the latest selectedServerIds before saving
                        loadSelectedFromCheckboxes();
                        
                        // Double-check that the new server is included
                        if (!selectedServerIds.includes(serverId)) {
                            selectedServerIds.push(serverId);
                        }
                        
                        
                        $.ajax({
                            url: list2playAdmin.ajaxUrl,
                            type: 'POST',
                            data: {
                                action: 'list2play_save_selected_servers',
                                nonce: list2playAdmin.nonce,
                                server_ids: selectedServerIds,
                            },
                            success: function(saveResponse) {
                                if (saveResponse.success) {
                                    // Update list2playAdmin.selectedServerIds to reflect the saved state
                                    if (typeof list2playAdmin !== 'undefined') {
                                        list2playAdmin.selectedServerIds = selectedServerIds;
                                    }
                                    showMessage('Server added and saved successfully. Server IDs: ' + selectedServerIds.join(', '), 'success');
                                } else {
                                    // Save failed - error message already shown to user
                                    showMessage('Server added, but failed to save selection: ' + (saveResponse.data?.message || 'Unknown error'), 'error');
                                }
                            },
                            error: function(xhr, status, error) {
                                // AJAX error - error message already shown to user
                                showMessage('Server added, but failed to save selection. Error: ' + error + ' (Status: ' + xhr.status + ')', 'error');
                            }
                        });
                        
                        $input.val('');
                    } else {
                        showMessage(response.data?.message || 'Failed to load server. Make sure the server ID is correct and you have access to it.', 'error');
                    }
                },
                error: function() {
                    showMessage('Failed to load server. Please check your API settings and server ID.', 'error');
                },
                complete: function() {
                    $button.prop('disabled', false).text('Add Server');
                }
            });
        });
        
        // Allow Enter key to add server
        $('#list2play-add-server-id').on('keypress', function(e) {
            if (e.which === 13) {
                e.preventDefault();
                $('#list2play-add-server-btn').click();
            }
        });
    });
})(jQuery);
