jQuery(document).ready(function($) {

    // Fetch and update debug mode status when the page loads
    $.ajax({
        url: easyerlo_ajax_object.ajax_url,
        type: 'post',
        data: {
            action: 'get_debug_mode_status'
        },
        success: function(response) {
            var statusElement = $('#debug-mode-status');
            if (response === 'ON') {
                statusElement.css('color', 'green');
            } else if (response === 'OFF') {
                statusElement.css('color', 'red');
            }
            statusElement.text(response);
        }
    });

    // AJAX call to toggle debug mode
    function updateToggleState(status) {
        $('#toggle-debug-mode').prop('checked', status === 'ON' || status === 'Log: ON');
    
        $('#debug-mode-status')
            .text(status)
            .css('color', status === 'ON' || status === 'Log: ON' ? 'green' : 'red');
    }

    // Initial state
    $.ajax({
        url: easyerlo_ajax_object.ajax_url,
        type: 'post',
        data: { action: 'get_debug_mode_status' },
        success: function(response) {
            updateToggleState(response);
        }
    });

    // Toggle handler
    $('#toggle-debug-mode').on('change', function() {
        $.ajax({
            url: easyerlo_ajax_object.ajax_url,
            type: 'post',
            data: { action: 'toggle_debug_mode' },
            success: function(response) {
                updateToggleState(response);
            }
        });
    });
    // END 

    
    // AJAX call to display error log
    $('#refresh-debug-log').on('click', function() {
        $.ajax({
            url: easyerlo_ajax_object.ajax_url,
            type: 'post',
            data: {
                action: 'display_error_log'
            },
            success: function(response) {
                $('#error-log-container').empty(); // reset and show the latest error on log 
                // console.log(response); 
                $('#error-log-container').append(response);
            }
        });
    });

     // Fetch error count via AJAX
    $.ajax({
        url: easyerlo_ajax_object.ajax_url,
        type: 'post',
        data: {
            action: 'get_error_count'
        },
        cache: false, // Prevent caching
        success: function(response) {
            var error_count = parseInt(response);
            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>";
            $('#wp-admin-bar-my-errors-page .ab-item').html("Errors-" + error_count_html);
        },
        error: function(xhr, status, error) {
            console.error("Error fetching error count:", error);
        }
    });

    // AJAX call to clean debug log
    $('#clean-debug-log').on('click', function() {
        $.ajax({
            url: easyerlo_ajax_object.ajax_url,
            type: 'post',
            data: {
                action: 'clean_debug_log'
            },
            success: function(response) {
                // alert(response);
                // Refresh error log after cleaning
                $('#refresh-debug-log').trigger('click');

                // Update error count after cleaning
                $.ajax({
                    url: easyerlo_ajax_object.ajax_url,
                    type: 'post',
                    data: {
                        action: 'get_error_count'
                    },
                    success: function(response) {
                        var error_count = parseInt(response);
                        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>";
                        $('#wp-admin-bar-my-errors-page .ab-item').html("Errors-" + error_count_html);
                    }
                });
                
            }
        });
    });

    

    // AJAX call to download debug log
    $('form#download-debug-log').on('submit', function(event) {
        event.preventDefault();
        $.ajax({
            url: easyerlo_ajax_object.ajax_url,
            type: 'post',
            data: $(this).serialize(), // Serialize form data
            success: function(response) {
                // JavaScript-based download
                var downloadLink = document.createElement('a');
                downloadLink.href = response; // Debug log URL
                downloadLink.download = 'debug.log';
                downloadLink.style.display = 'none';
                document.body.appendChild(downloadLink);
                downloadLink.click();
                document.body.removeChild(downloadLink);
            }
        });
    });

    //Reset 
    $('#reset-constant').on('click', function(e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: easyerlo_ajax_object.ajax_url,
            data: {
                action: 'reset_debug_constant', // Action name to trigger the AJAX callback
                // Add any additional data if needed
            },
            success: function(response) {
                alert(response); // Show success message
                window.location.reload();
            },
            error: function(error) {
                console.error('Error:', error); // Log any errors to the console
            }
        });
    });


    // Function to fetch and update error count
    function updateErrorCount() {
        $.ajax({
            url: easyerlo_ajax_object.ajax_url,
            type: 'post',
            data: {
                action: 'get_error_count'
            },
            cache: false, // Prevent caching
            success: function(response) {
                var error_count = parseInt(response);
                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>";
                $('#wp-admin-bar-my-errors-page .ab-item').html("Errors-" + error_count_html);
            },
            error: function(xhr, status, error) {
                console.error("Error fetching error count:", error);
            }
        });
    }

    // Function to fetch and update error log
    function updateErrorLog() {
        $.ajax({
            url: easyerlo_ajax_object.ajax_url,
            type: 'post',
            data: {
                action: 'display_error_log'
            },
            success: function(response) {
                $('#error-log-container').html(response);
            }
        });
    }


    function updateDebugStatus() {
        $.ajax({
            url: easyerlo_ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'check_debug_constants_status',
            },
            success: function(response) {
                if (response.success) {
                    const wpDebugStatus = response.data.WP_DEBUG;
                    const wpDebugLogStatus = response.data.WP_DEBUG_LOG;

                    const wpDebugElement = $('.constant-status.wp-debug');
                    const wpDebugLogElement = $('.constant-status.wp-debug-log');

                    wpDebugElement.text(wpDebugStatus === true || wpDebugStatus === 'true' ? 'Active' : 'Not Active');
                    wpDebugLogElement.text(wpDebugLogStatus === true || wpDebugLogStatus === 'true' ? 'Active' : 'Not Active');

                    wpDebugElement.css('color', wpDebugStatus === true || wpDebugStatus === 'true' ? 'green' : 'red');
                    wpDebugLogElement.css('color', wpDebugLogStatus === true || wpDebugLogStatus === 'true' ? 'green' : 'red');
                }
            }
        });
    }

    // Initial load of error count and error log
    updateErrorCount();
    updateErrorLog();
    updateDebugStatus();

    // Set intervals to update error count and error log periodically
    var errorCountInterval = setInterval(updateErrorCount, 5000); // Update every 5 seconds
    var updateDebugConstStatus = setInterval(updateDebugStatus, 5000); // Update every 5 seconds
    // var errorLogInterval = setInterval(updateErrorLog, 5000); // To Update every 10 seconds 10000

    // Clean up intervals when the page is unloaded
    $(window).on('unload', function() {
        clearInterval(errorCountInterval);
        clearInterval(updateDebugConstStatus);
        // clearInterval(errorLogInterval);
    });


    // Initial load of error log
    $('#refresh-debug-log').trigger('click');


    // Tabs 
    const tabs = document.querySelectorAll('.nav-tab');
    const tabPanes = document.querySelectorAll('.tab-pane');

    // Function to activate a tab
    function activateTab(tab) {
        // Remove active class from all tabs and hide all panes
        tabs.forEach(t => t.classList.remove('nav-tab-active'));
        tabPanes.forEach(p => p.style.display = 'none');

        // Add active class to clicked tab and show corresponding pane
        tab.classList.add('nav-tab-active');
        document.querySelector(tab.getAttribute('href')).style.display = 'block';

        // Save active tab to localStorage
        localStorage.setItem('activeTab', tab.getAttribute('href'));
    }

    // Add click handlers to tabs
    tabs.forEach(tab => {
        tab.addEventListener('click', function(e) {
            e.preventDefault();
            activateTab(this);
        });
    });

    // Restore active tab on page load
    const savedTab = localStorage.getItem('activeTab');
    if (savedTab) {
        const tabToActivate = document.querySelector(`.nav-tab[href="${savedTab}"]`);
        if (tabToActivate) {
            activateTab(tabToActivate);
        }
    }

    // Copy button 
    document.querySelectorAll('.copy-btn').forEach(button => {
        button.addEventListener('click', function() {
            const targetId = this.getAttribute('data-target');
            const targetCode = document.querySelector(targetId);

            // Create a temporary textarea to copy the content
            const tempInput = document.createElement('textarea');
            tempInput.value = targetCode.textContent;
            document.body.appendChild(tempInput);
            tempInput.select();
            document.execCommand('copy');
            document.body.removeChild(tempInput);

            // Change button text to "Copied"
            const originalText = this.textContent;
            this.textContent = 'copied';

            // Revert text back after 1 second
            setTimeout(() => {
                this.textContent = originalText;
            }, 1000);
        });
    });



    // AJAX call to toggle fe debug mode widgets
    $('#toggle-fe-mode').on('click', function() {
        $.ajax({
            url: easyerlo_ajax_object.ajax_url,
            type: 'post',
            data: {
                action: 'toggle_widgets_mode'
            },
            success: function(response) {
                var widgets_mode = response.data.widgets_mode;
                $('#debug-fe-status').text(widgets_mode === 'true' ? 'ON' : 'OFF');
                $('#debug-fe-status').css('color', widgets_mode === 'true' ? 'red' : '#ffee00');
            }
        });
    });

    // Set the initial status based on the stored option value
    $.ajax({
        url: easyerlo_ajax_object.ajax_url,
        type: 'post',
        data: {
            action: 'get_widgets_mode_status'
        },
        success: function(response) {
            var widgets_mode = response.data.widgets_mode;
            $('#debug-fe-status').text(widgets_mode === 'true' ? 'ON' : 'OFF');
            $('#debug-fe-status').css('color', widgets_mode === 'true' ? 'red' : '#ffee00');
        }
    });

    $('#toggle-admin-widget').on('click', function() {
        $.ajax({
            url: easyerlo_ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'toggle_admin_widget',
                nonce: easyerlo_ajax_object.nonce
            },
            success: function(response) {
                if (response.success) {
                    const status = response.data.status;
                    const $statusSpan = $('#admin-widget-status');
                    
                    if (status === 'active') {
                        $statusSpan.text('ON').css('color', '#ffee00');
                    } else {
                        $statusSpan.text('OFF').css('color', 'red');
                    }
                    
                }
            }
        });
    });

    $('#toggle-fatal-error-safer').on('click', function() {
        $.ajax({
            url: easyerlo_ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'toggle_fatal_error_safer',
                nonce: easyerlo_ajax_object.nonce
            },
            success: function(response) {
                if (response.success) {
                    const status = response.data.status;
                    const $statusSpan = $('#fatal-error-safer');
                    
                    if (status === 'active') {
                        $statusSpan.text('ON').css('color', '#00ff86');
                    } else {
                        $statusSpan.text('OFF').css('color', 'red');
                    }
                    
                }
            }
        });
    });

    // Add modal HTML to the page
    $('body').append(`
        <div class="editor-modal">
            <div class="editor-modal-content">
                <div class="editor-modal-header">
                    <div class="editor-modal-title">
                        <span class="file-name">Edit File</span>
                        <span class="file-path"></span>
                    </div>
                    <div class="editor-modal-actions">
                        <button class="editor-modal-button editor-modal-open-local" title="Open in Local Editor">
                            <span class="dashicons dashicons-editor-code"></span>
                        </button>
                        <span class="editor-modal-close">&times;</span>
                    </div>
                </div>
                <div class="editor-modal-body">
                    <div class="editor-container">
                        <div class="line-numbers"></div>
                        <textarea class="code-editor" spellcheck="false"></textarea>
                    </div>
                </div>
                <div class="editor-modal-footer">
                    <button class="editor-modal-button editor-modal-cancel">Cancel</button>
                    <button class="editor-modal-button editor-modal-save">Save Changes</button>
                </div>
            </div>
        </div>
    `);

    let editor;
    let currentFilePath = '';
    let currentLineNumber = 0;

    // Function to show search dialog
    function showSearchDialog() {
        // Get selected text from editor
        const selectedText = editor.getSelection();
        
        // Use CodeMirror's built-in search dialog
        editor.execCommand('findPersistent');
        
        // If there's selected text, set it as the search query
        if (selectedText) {
            const searchInput = document.querySelector('.CodeMirror-search');
            if (searchInput) {
                searchInput.value = selectedText;
                // Trigger the search
                const event = new Event('input', { bubbles: true });
                searchInput.dispatchEvent(event);
            }
        }
    }

    // Initialize CodeMirror editor
    function initEditor() {
        const editorElement = document.querySelector('.code-editor');
        editor = CodeMirror.fromTextArea(editorElement, {
            mode: 'php',
            theme: 'monokai',
            lineNumbers: true,
            matchBrackets: true,
            autoCloseBrackets: true,
            indentUnit: 4,
            tabSize: 4,
            lineWrapping: true,
            extraKeys: {
                'Ctrl-Space': 'autocomplete',
                'Ctrl-/': 'toggleComment',
                'Ctrl-F': function(cm) {
                    showSearchDialog();
                },
                'Ctrl-S': function(cm) {
                    saveChanges();
                },
                'Alt-Up': 'moveLineUp',
                'Alt-Down': 'moveLineDown',
                'Shift-Alt-Down': 'duplicateLine',
                'Tab': function(cm) {
                    if (cm.somethingSelected()) {
                        cm.indentSelection('add');
                    } else {
                        cm.replaceSelection('    ', 'end');
                    }
                }
            }
        });

        // Add search functionality
        editor.setOption('search', {
            bottom: true
        });

        // Add custom commands
        CodeMirror.commands.duplicateLine = function(cm) {
            const line = cm.getCursor().line;
            const lineContent = cm.getLine(line);
            cm.replaceRange(lineContent + '\n', {line: line + 1, ch: 0});
            cm.setCursor({line: line + 1, ch: cm.getCursor().ch});
        };

        CodeMirror.commands.moveLineUp = function(cm) {
            const line = cm.getCursor().line;
            if (line > 0) {
                const lineContent = cm.getLine(line);
                cm.replaceRange('', {line: line, ch: 0}, {line: line + 1, ch: 0});
                cm.replaceRange(lineContent + '\n', {line: line - 1, ch: 0});
                cm.setCursor({line: line - 1, ch: cm.getCursor().ch});
            }
        };

        CodeMirror.commands.moveLineDown = function(cm) {
            const line = cm.getCursor().line;
            if (line < cm.lastLine()) {
                const lineContent = cm.getLine(line);
                cm.replaceRange('', {line: line, ch: 0}, {line: line + 1, ch: 0});
                cm.replaceRange(lineContent + '\n', {line: line + 1, ch: 0});
                cm.setCursor({line: line + 1, ch: cm.getCursor().ch});
            }
        };

        // Handle multi-cursor
        editor.on('mousedown', function(cm, e) {
            if (e.altKey) {
                const pos = cm.coordsChar({left: e.clientX, top: e.clientY});
                cm.addSelection(pos);
                e.preventDefault();
            }
        });
    }

    // Update the open editor modal function
    $(document).on('click', '.open-in-editor', function(e) {
        e.preventDefault();
        const filePath = $(this).data('path');
        const line = $(this).data('line');
        
        currentFilePath = filePath;
        currentLineNumber = parseInt(line);

        // Update modal title with file path
        const fileName = filePath.split('/').pop();
        $('.editor-modal-title .file-name').text(fileName);
        // $('.editor-modal-title .file-path').text(filePath);

        // Get file content
        $.ajax({
            url: easyerlo_ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'get_file_content',
                file_path: filePath,
                line_number: line,
                nonce: easyerlo_ajax_object.nonce
            },
            success: function(response) {
                if (response.success) {
                    const content = response.data.content;
                    
                    // Initialize editor if not already done
                    if (!editor) {
                        initEditor();
                    }
                    
                    // Set content in editor
                    editor.setValue(content);
                    
                    // Show modal
                    $('.editor-modal').fadeIn();
                    
                    // Scroll to current line after a short delay
                    setTimeout(function() {
                        editor.scrollIntoView({line: currentLineNumber - 1, ch: 0}, 50);
                        editor.addLineClass(currentLineNumber - 1, 'background', 'error-line');
                    }, 100);
                } else {
                    alert('Error: ' + response.data);
                }
            },
            error: function() {
                alert('Error loading file content');
            }
        });
    });

    // Update save changes function
    function saveChanges() {
        const content = editor.getValue();
        
        $.ajax({
            url: easyerlo_ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'save_file_content',
                file_path: currentFilePath,
                content: content,
                nonce: easyerlo_ajax_object.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Create and show success notice
                    const notice = $('<div class="editor-save-notice">File saved successfully!</div>');
                    $('.editor-modal-content').append(notice);
                    
                    // Add styles for the notice
                    $('<style>')
                        .text(`
                            .editor-save-notice {
                                position: fixed;
                                top: 20px;
                                right: 20px;
                                background: #46b450;
                                color: white;
                                padding: 10px 20px;
                                border-radius: 4px;
                                box-shadow: 0 2px 5px rgba(0,0,0,0.2);
                                z-index: 9999;
                                animation: slideIn 0.3s ease-out;
                            }
                            @keyframes slideIn {
                                from { transform: translateX(100%); opacity: 0; }
                                to { transform: translateX(0); opacity: 1; }
                            }
                        `)
                        .appendTo('head');
                    
                    // Remove notice after 2 seconds with fade out
                    setTimeout(function() {
                        notice.fadeOut(300, function() {
                            $(this).remove();
                        });
                    }, 2000);

                    // Refresh the error log to show updated content
                    $('#refresh-debug-log').trigger('click');
                } else {
                    // Show error notice
                    const notice = $('<div class="editor-save-notice error">Error: ' + (response.data || 'Unknown error occurred') + '</div>');
                    $('.editor-modal-content').append(notice);
                    
                    // Add error styles
                    $('<style>')
                        .text(`
                            .editor-save-notice.error {
                                background: #dc3232;
                            }
                        `)
                        .appendTo('head');
                    
                    // Remove error notice after 3 seconds
                    setTimeout(function() {
                        notice.fadeOut(300, function() {
                            $(this).remove();
                        });
                    }, 3000);
                }
            },
            error: function(xhr, status, error) {
                console.error('Save error:', error);
                // Show error notice
                const notice = $('<div class="editor-save-notice error">Error saving file: ' + error + '</div>');
                $('.editor-modal-content').append(notice);
                
                // Remove error notice after 3 seconds
                setTimeout(function() {
                    notice.fadeOut(300, function() {
                        $(this).remove();
                    });
                }, 3000);
            }
        });
    }

    // Close modal
    $('.editor-modal-close, .editor-modal-cancel').on('click', function() {
        $('.editor-modal').fadeOut();
    });

    // Add click handler for Save Changes button
    $('.editor-modal-save').on('click', function() {
        saveChanges();
    });

    $('#toggle-controller').on('click', function() {
        $('.wpel-buttons').slideToggle(300); // Toggle visibility with animation
        let icon = $('#toggle-icon');
        icon.text(icon.text() === '▼' ? '▲' : '▼'); // Change icon
    });

    if (easyerlo_ajax_object.admin_widget_status !== 'active') {
        $('#admin-error-widget').remove();
        return;
    }

    // Function to try opening file in local editor
    function tryOpenEditor(filePath, lineNumber) {
        // Validate inputs
        if (!filePath) {
            console.error('No file path provided');
            alert('No file path provided');
            return;
        }

        if (!lineNumber) {
            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)}:${lineNumber}`;
                    } else {
                        // For Unix-like systems
                        url = `${editor.protocol}${cleanPath}:${lineNumber}`;
                    }
                    
                    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}:${lineNumber}"`;
                        console.log('Trying command:', command);
                    } else {
                        // For Unix-like systems
                        const command = `${editor.check()} "${cleanPath}:${lineNumber}"`;
                        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.');
        }
    }

    // Add click handler for the open in editor button
    $(document).on('click', '.editor-modal-open-local', function() {
        console.log('Open in editor clicked');
        console.log('Current file path:', currentFilePath);
        console.log('Current line number:', currentLineNumber);
        
        if (currentFilePath && currentLineNumber) {
            tryOpenEditor(currentFilePath, currentLineNumber);
        } else {
            console.error('Missing file path or line number');
            alert('Cannot open file: Missing file path or line number');
        }
    });

});

