/**
 * JCOGS Image Pro - Error Details AJAX Handler
 * =============================================
 * Handles AJAX loading of error notification details in the Control Panel
 * 
 * @category   ExpressionEngine Add-on
 * @package    JCOGS Image Pro
 * @author     JCOGS Design <contact@jcogs.net>
 * @copyright  Copyright (c) 2021 - 2025 JCOGS Design
 * @license    https://jcogs.net/add-ons/license/jcogs_img_pro
 * @version    2.0.2
 * @link       https://JCOGS.net/
 * @since      Enhanced Error Notifications Feature
 */

(function($) {
    'use strict';

    // Track load state across handlers and retries.
    let detailsLoaded = false;
    let allDetailsLoaded = false;

    /**
     * Normalize endpoint URLs and avoid mixed-content requests.
     */
    function normalizeEndpointUrl(rawUrl) {
        if (!rawUrl) {
            return rawUrl;
        }

        try {
            var resolved = new URL(rawUrl, window.location.href);

            if (window.location.protocol === 'https:' && resolved.protocol === 'http:') {
                resolved.protocol = 'https:';
            }

            return resolved.toString();
        } catch (e) {
            return rawUrl;
        }
    }

    /**
     * Detect plain-text EE throttling responses (including localized text).
     */
    function isThrottlingResponseText(text) {
        if (!text) {
            return false;
        }

        var value = String(text).toLowerCase();
        return value.indexOf('throttl') !== -1 ||
            value.indexOf('too many request') !== -1 ||
            value.indexOf('too many page') !== -1 ||
            value.indexOf('rate limit') !== -1 ||
            value.indexOf('te veel pagina') !== -1 ||
            value.indexOf('probeer het later nog eens') !== -1;
    }

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

    /**
     * Build a user-facing message from AJAX error context.
     */
    function buildErrorMessage(xhr, status, error) {
        if (status === 'timeout') {
            return 'Request timed out. Please try again.';
        }

        if (status === 'abort') {
            return 'Request was cancelled.';
        }

        var responseText = xhr && xhr.responseText ? xhr.responseText : '';
        if (isThrottlingResponseText(responseText) || isThrottlingResponseText(error)) {
            return 'Request throttled by ExpressionEngine. Please wait a moment and try again.';
        }

        if (status === 'error') {
            if (xhr.status === 404) {
                return 'Error details endpoint not found.';
            }
            if (xhr.status === 500) {
                return 'Server error occurred. Please check the server logs.';
            }
            if (xhr.status === 0) {
                return 'Network error. Please check your connection.';
            }
            return 'HTTP ' + xhr.status + ': ' + xhr.statusText;
        }

        return 'Failed to load error details.';
    }
    
    $(document).ready(function() {
        // Check if error URLs are available
        if (typeof window.jcogsImageProErrorUrls === 'undefined') {
            console.warn('[JCOGS Image Pro] Error URLs not found - error details functionality disabled');
            return;
        }
        
        const errorUrls = window.jcogsImageProErrorUrls;
        
        // Handle "view details" click
        $('.jcogs-expand-errors').on('click', function(e) {
            e.preventDefault();
            
            const $target = $($(this).data('target'));
            if (!$target.length) {
                console.error('[JCOGS Image Pro] Error details target not found');
                return;
            }
            
            // If already expanded and loaded, just toggle
            if ($target.hasClass('show') || $target.hasClass('in')) {
                return; // Let Bootstrap handle the toggle
            }
            
            // Load initial error details if not loaded
            if (!detailsLoaded) {
                loadErrorDetails($target, errorUrls.errorDetails, function() {
                    detailsLoaded = true;
                });
            }
        });
        
        // Handle "Show All" click (will be added dynamically by the AJAX response)
        $(document).on('click', '.jcogs-show-all-errors', function(e) {
            e.preventDefault();
            
            if (!allDetailsLoaded) {
                const $container = $('#jcogs-error-details');
                loadErrorDetails($container, errorUrls.errorDetailsAll, function() {
                    allDetailsLoaded = true;
                    $(this).remove(); // Remove the "Show All" button
                }.bind(this));
            }
        });
    });
    
    /**
     * Load error details via AJAX
     * 
     * @param {jQuery} $container Target container element
     * @param {string} url AJAX URL to load from
     * @param {function} callback Success callback function
     */
    function loadErrorDetails($container, url, callback) {
        url = normalizeEndpointUrl(url);

        // Show loading state
        $container.html('<div class="jcogs-error-loading" style="text-align: center; padding: 1rem; color: #666;"><i class="fas fa-spinner fa-spin"></i> Loading error details...</div>');
        
        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'text',
            timeout: 10000, // 10 second timeout
            success: function(rawData) {
                try {
                    if (isThrottlingResponseText(rawData)) {
                        throw new Error('Request throttled by ExpressionEngine. Please wait a moment and try again.');
                    }

                    var data = String(rawData || '');
                    if (data.trim() === '') {
                        throw new Error('Received an empty response from the server.');
                    }

                    $container.html(data);
                    
                    // Call callback if provided
                    if (typeof callback === 'function') {
                        callback();
                    }
                    
                    // Trigger custom event for extensibility
                    $container.trigger('jcogs:errorDetailsLoaded', [data]);
                    
                } catch (error) {
                    console.error('[JCOGS Image Pro] Error processing response:', error);
                    showErrorMessage($container, error.message || 'Failed to process error details response.');
                }
            },
            error: function(xhr, status, error) {
                console.error('[JCOGS Image Pro] AJAX Error:', {
                    status: status,
                    error: error,
                    responseText: xhr.responseText,
                    url: url
                });

                showErrorMessage($container, buildErrorMessage(xhr, status, error));
            }
        });
    }
    
    /**
     * Show error message in container
     * 
     * @param {jQuery} $container Target container
     * @param {string} message Error message to display
     */
    function showErrorMessage($container, message) {
        const errorHtml = `
            <div class="alert alert-warning" style="margin: 1rem 0;">
                <p><strong>Temporarily unavailable:</strong> ${escapeHtml(message)}</p>
                <p style="margin-bottom: 0; font-size: 0.875rem; margin-top: 0.5rem;">
                    <a href="#" class="jcogs-retry-load">Retry now</a> or 
                    <a href="${window.location.href}">refresh the page</a>.
                </p>
            </div>
        `;
        
        $container.html(errorHtml);
        
        // Handle retry click
        $container.find('.jcogs-retry-load').on('click', function(e) {
            e.preventDefault();
            // Reset loaded state and trigger click on expand button
            detailsLoaded = false;
            allDetailsLoaded = false;
            $('.jcogs-expand-errors').trigger('click');
        });
    }
    
})(jQuery);