/**
 * Admin JavaScript for HD SofT AI Summary
 *
 * @package HDSofT\AISummary
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        // Test connection button handler
        $('#test-connection').on('click', function(e) {
            e.preventDefault();
            
            var $button = $(this);
            var $result = $('#connection-result');
            
            // Get API key value
            var apiKey = $('#openrouter_api_key').val().trim();
            
            if (!apiKey) {
                $result.html('<span class="error">' + hdsoft_ai_summary_admin.strings.error + ' API key is required.</span>');
                $result.removeClass('success').addClass('error');
                return;
            }
            
            // Disable button and show loading
            $button.prop('disabled', true);
            $button.text(hdsoft_ai_summary_admin.strings.testing);
            $result.html('').removeClass('success error');
            
            // Make AJAX request
            $.ajax({
                url: hdsoft_ai_summary_admin.ajax_url,
                type: 'POST',
                data: {
                    action: 'hdsoft_ai_summary_test_connection',
                    nonce: hdsoft_ai_summary_admin.nonce,
                    api_key: apiKey
                },
                timeout: 30000, // 30 seconds timeout
                success: function(response) {
                    if (response.success) {
                        var message = hdsoft_ai_summary_admin.strings.success;
                        
                        if (response.data.model_info) {
                            message += '<br><strong>Current Model:</strong> ' + response.data.model_info.name;
                        }
                        
                        if (response.data.total_models) {
                            message += '<br><strong>Available Models:</strong> ' + response.data.total_models;
                        }
                        
                        $result.html('<span class="success">' + message + '</span>');
                        $result.removeClass('error').addClass('success');
                        
                        // Enable model loading if connection successful
                        $('#load-models').prop('disabled', false);
                    } else {
                        var errorMessage = response.data && response.data.message 
                            ? response.data.message 
                            : 'Unknown error occurred.';
                        
                        // Add specific error handling for common issues
                        if (errorMessage.includes('Invalid API key format')) {
                            errorMessage += '<br><small>OpenRouter API keys should start with "sk-or-" and be at least 20 characters long.</small>';
                        } else if (errorMessage.includes('Authentication failed')) {
                            errorMessage += '<br><small>Please check that your API key is correct and has sufficient permissions.</small>';
                        } else if (errorMessage.includes('No models available')) {
                            errorMessage += '<br><small>This usually indicates an authentication issue with your API key.</small>';
                        }
                        
                        $result.html('<span class="error">' + hdsoft_ai_summary_admin.strings.error + ' ' + errorMessage + '</span>');
                        $result.removeClass('success').addClass('error');
                        
                        // Disable model loading if connection failed
                        $('#load-models').prop('disabled', true);
                    }
                },
                error: function(xhr, status, error) {
                    var errorMessage = 'Connection failed.';
                    
                    if (status === 'timeout') {
                        errorMessage = 'Request timed out. Please check your internet connection and API key, then try again.';
                    } else if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                        errorMessage = xhr.responseJSON.data.message;
                    } else if (xhr.status === 0) {
                        errorMessage = 'Network error. Please check your internet connection.';
                    } else if (xhr.status >= 500) {
                        errorMessage = 'Server error (' + xhr.status + '). Please try again later.';
                    } else if (xhr.status >= 400) {
                        errorMessage = 'Client error (' + xhr.status + '). Please check your API key.';
                    }
                    
                    $result.html('<span class="error">' + hdsoft_ai_summary_admin.strings.error + ' ' + errorMessage + '</span>');
                    $result.removeClass('success').addClass('error');
                    
                    // Disable model loading on error
                    $('#load-models').prop('disabled', true);
                },
                complete: function() {
                    // Re-enable button
                    $button.prop('disabled', false);
                    $button.text('Test Connection');
                }
            });
        });

        // Load models button handler
        $('#load-models').on('click', function(e) {
            e.preventDefault();
            loadModels();
        });

        // Auto-save API key when changed (with debounce)
        var apiKeyTimeout;
        $('#openrouter_api_key').on('input', function() {
            clearTimeout(apiKeyTimeout);
            
            apiKeyTimeout = setTimeout(function() {
                // Clear previous test results when API key changes
                $('#connection-result').html('').removeClass('success error');
            }, 500);
        });
        
        // Form validation
        $('form').on('submit', function(e) {
            var apiKey = $('#openrouter_api_key').val().trim();
            var autoGenerate = $('#auto_generate').is(':checked');
            
            if (autoGenerate && !apiKey) {
                e.preventDefault();
                alert('Please enter an OpenRouter API key or disable auto-generation.');
                $('#openrouter_api_key').focus();
                return false;
            }
        });
        
        // Max tokens validation and word estimate
        $('#max_tokens').on('input', function() {
            var value = parseInt($(this).val());
            var min = parseInt($(this).attr('min'));
            var max = parseInt($(this).attr('max'));
            
            if (value < min) {
                $(this).val(min);
            } else if (value > max) {
                $(this).val(max);
            }
            
            // Update word estimate
            var tokens = parseInt($(this).val()) || 0;
            var words = Math.min(80, Math.max(30, Math.floor(tokens * 0.3)));
            $('#word-estimate').text(words);
        });

        // Load models function - populates native WordPress select dropdown
        function loadModels() {
            var $button = $('#load-models');
            var $select = $('#model_name');
            
            // Check if API key exists
            var apiKey = $('#openrouter_api_key').val().trim();
            if (!apiKey) {
                alert('Please enter an OpenRouter API key first.');
                return;
            }
            
            // Show loading state
            $button.prop('disabled', true).text('Loading...');
            
            // Make AJAX request
            $.ajax({
                url: hdsoft_ai_summary_admin.ajax_url,
                type: 'POST',
                data: {
                    action: 'hdsoft_ai_summary_get_models',
                    nonce: hdsoft_ai_summary_admin.nonce,
                    api_key: apiKey
                },
                timeout: 30000,
                success: function(response) {
                    if (response.success) {
                        // Save current selection
                        var currentValue = $select.val();
                        $select.empty();
                        
                        // Add models to dropdown - recommended first
                        response.data.models.forEach(function(model) {
                            var optionText = model.name + ' (' + model.id + ')';
                            if (model.recommended) {
                                optionText = '⭐ ' + optionText;
                            }
                            
                            var $option = $('<option></option>')
                                .attr('value', model.id)
                                .text(optionText);
                            
                            if (model.id === currentValue) {
                                $option.prop('selected', true);
                            }
                            
                            $select.append($option);
                        });
                        
                    } else {
                        var errorMessage = response.data && response.data.message 
                            ? response.data.message 
                            : 'Failed to load models.';
                        alert('Error loading models: ' + errorMessage);
                    }
                },
                error: function(xhr, status, error) {
                    var errorMessage = 'Failed to load models.';
                    
                    if (status === 'timeout') {
                        errorMessage = 'Request timed out. Please check your internet connection and try again.';
                    } else if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                        errorMessage = xhr.responseJSON.data.message;
                    }
                    
                    alert('Error: ' + errorMessage);
                },
                complete: function() {
                    $button.prop('disabled', false).text('Load Available Models');
                }
            });
        }
    });

})(jQuery);
