jQuery(document).ready(function($) {
    // Check if we're in admin area
    var isAdmin = $('body').hasClass('wp-admin');
    
    // Check if frontend widget mode is enabled
    var widgetsMode = 'false';
    $.ajax({
        url: easyerlo_ajax_fe_object.ajax_url,
        type: 'post',
        data: {
            action: 'get_widgets_mode_status'
        },
        async: false,
        success: function(response) {
            if (response.success) {
                widgetsMode = response.data.widgets_mode;
            }
        }
    });

    // Function to fetch and update error count
    function updateErrorCount() {
        $.ajax({
            url: easyerlo_ajax_fe_object.ajax_url,
            type: 'post',
            data: {
                action: 'get_error_count'
            },
            cache: false, // Prevent caching
            success: function(response) {
                var error_count = parseInt(response);
                if (!isNaN(error_count)) {
                    var error_count_html = "<span style='color:red;font-weight:bold;' class='update-plugins count-" + error_count + "'><span class='update-count'>" + error_count + "</span></span>";
                    
                    // Update admin bar item
                    if (isAdmin) {
                        // In admin area, always show the count
                        $('#wp-admin-bar-my-errors-page .ab-item').html("Errors-" + error_count_html);
                    } else if (widgetsMode === 'true') {
                        // In frontend, only show if widget mode is enabled
                        $('#wp-admin-bar-my-errors-page .ab-item').html("Errors-" + error_count_html);
                        $('#wp-admin-bar-my-errors-page').show();
                    } else {
                        // In frontend with widget mode off, hide the item
                        $('#wp-admin-bar-my-errors-page').hide();
                    }

                    // Update error log container if it exists
                    if ($('#error-log-container .error-log-header span').length) {
                        $('#error-log-container .error-log-header span').html("Error Log (" + error_count_html + ")");
                    }
                } else {
                    // Handle invalid response
                    if (isAdmin) {
                        // In admin area, show zero count
                        var zero_count_html = "<span style='color:red;font-weight:bold;' class='update-plugins count-0'><span class='update-count'>0</span></span>";
                        $('#wp-admin-bar-my-errors-page .ab-item').html("Errors-" + zero_count_html);
                    } else {
                        // In frontend, hide the item
                        $('#wp-admin-bar-my-errors-page').hide();
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error("Error fetching error count:", error);
                if (isAdmin) {
                    // In admin area, show zero count on error
                    var zero_count_html = "<span style='color:red;font-weight:bold;' class='update-plugins count-0'><span class='update-count'>0</span></span>";
                    $('#wp-admin-bar-my-errors-page .ab-item').html("Errors-" + zero_count_html);
                } else {
                    // In frontend, hide the item on error
                    $('#wp-admin-bar-my-errors-page').hide();
                }
            }
        });
    }

    // Function to fetch and update error log
    function updateErrorLog() {
        $.ajax({
            url: easyerlo_ajax_fe_object.ajax_url,
            type: 'post',
            data: {
                action: 'display_error_log'
            },
            success: function(response) {
                if ($('#error-log-content').length) {
                    $('#error-log-content').html(response);
                }
            },
            error: function(xhr, status, error) {
                console.error("Error fetching error log:", error);
                if ($('#error-log-content').length) {
                    $('#error-log-content').html('<div class="error">Error loading log content.</div>');
                }
            }
        });
    }

    // Always update error count and log in admin, conditionally in frontend
    if (isAdmin) {
        // Initial load of error count and log
        updateErrorCount();
        updateErrorLog();
        
        // Set intervals to update periodically
        var errorCountInterval = setInterval(updateErrorCount, 5000);
        var errorLogInterval = setInterval(updateErrorLog, 5000);
        
        // Clean up intervals when the page is unloaded
        $(window).on('unload', function() {
            clearInterval(errorCountInterval);
            clearInterval(errorLogInterval);
        });
    } else if (widgetsMode === 'true') {
        // Frontend widget mode enabled
        updateErrorCount();
        updateErrorLog();
        
        var errorCountInterval = setInterval(updateErrorCount, 5000);
        var errorLogInterval = setInterval(updateErrorLog, 5000);
        
        $(window).on('unload', function() {
            clearInterval(errorCountInterval);
            clearInterval(errorLogInterval);
        });
    }

    // Initialize the state
    var isOpen = false;

    // Function to toggle the error log visibility
    function toggleErrorLog() {
        if (isOpen) {
            $('#error-log-container').removeClass('open').addClass('closed');
            $('#error-log-toggle').text('🔺');
        } else {
            $('#error-log-container').removeClass('closed').addClass('open');
            $('#error-log-toggle').text('🔻');
        }
        isOpen = !isOpen;
    }

    // Bind the click event to the toggle button
    $('.error-log-header').on('click', function() {
        toggleErrorLog();
    });

    // Open editor 
    $(document).on('click', '.open-in-editor', function() {
        const filePath = $(this).data('path');
        const line = $(this).data('line');
        
        // Validate inputs
        if (!filePath) {
            console.error('No file path provided');
            alert('No file path provided');
            return;
        }

        if (!line) {
            console.error('No line number provided');
            alert('No line number provided');
            return;
        }

        // List of editors to try in order of preference
        const editors = [
            {
                name: 'vscode',
                protocol: 'vscode://file/',
                check: () => navigator.platform.includes('Win') ? 'code' : 'code'
            },
            {
                name: 'sublime',
                protocol: 'subl://open?url=file://',
                check: () => navigator.platform.includes('Win') ? 'subl' : 'subl'
            },
            {
                name: 'phpstorm',
                protocol: 'phpstorm://open?file=',
                check: () => navigator.platform.includes('Win') ? 'phpstorm' : 'phpstorm'
            },
            {
                name: 'atom',
                protocol: 'atom://core/open/file?filename=',
                check: () => navigator.platform.includes('Win') ? 'atom' : 'atom'
            }
        ];

        try {
            // Clean and format the file path for Windows
            let cleanPath = String(filePath);
            
            // Remove any double backslashes
            cleanPath = cleanPath.replace(/\\+/g, '\\');
            
            // Remove any leading/trailing slashes
            cleanPath = cleanPath.replace(/^[\/\\]+|[\/\\]+$/g, '');
            
            // Convert forward slashes to backslashes for Windows
            if (navigator.platform.includes('Win')) {
                cleanPath = cleanPath.replace(/\//g, '\\');
            }

            console.log('Original path:', filePath);
            console.log('Cleaned path:', cleanPath);

            // Try each editor
            for (const editor of editors) {
                try {
                    let url;
                    if (navigator.platform.includes('Win')) {
                        // For Windows, use file:/// protocol with proper encoding
                        url = `${editor.protocol}${encodeURI(cleanPath)}:${line}`;
                    } else {
                        // For Unix-like systems
                        url = `${editor.protocol}${cleanPath}:${line}`;
                    }
                    
                    console.log(`Attempting to open with ${editor.name}:`, url);
                    window.location.href = url;
                    
                    // If we get here, the protocol handler didn't work
                    // Try using the command line approach
                    if (navigator.platform.includes('Win')) {
                        // For Windows, try using the start command
                        const command = `start ${editor.name} "${cleanPath}:${line}"`;
                        console.log('Trying command:', command);
                    } else {
                        // For Unix-like systems
                        const command = `${editor.check()} "${cleanPath}:${line}"`;
                        console.log('Trying command:', command);
                    }
                } catch (e) {
                    console.error(`Failed to open with ${editor.name}:`, e);
                }
            }

            // If no editor worked, try opening in default text editor
            try {
                const url = `file:///${encodeURI(cleanPath)}`;
                console.log('Attempting to open with default editor:', url);
                window.open(url);
            } catch (e) {
                console.error('Failed to open file:', e);
                alert('Could not open file in any editor. Please open it manually.');
            }
        } catch (error) {
            console.error('Error in tryOpenEditor:', error);
            alert('An error occurred while trying to open the file. Please check the console for details.');
        }
    });
});