"use strict";
document.addEventListener('DOMContentLoaded', function () {
    const btn = document.getElementById('aiomatic_result_toggle');
    const wrapper = document.querySelector('.aiomatic-result-wrapper');

    btn.addEventListener('click', function () {
        wrapper.classList.toggle('aiomatic-result-expanded');

        if (wrapper.classList.contains('aiomatic-result-expanded')) {
            btn.textContent = '⤡'; 
        } else {
            btn.textContent = '⤢';
        }
    });
});
jQuery(function($){
    function aiomaticRefreshAgentStatuses() {

        const ids = [];

        $('.aiomatic-agent-status').each(function(){
            ids.push($(this).data('agent-id'));
        });

        if (!ids.length) return;

        $.post(ajaxurl, {
            action: 'aiomatic_get_agents_status',
            nonce: aiomaticAgent.nonce,
            agent_ids: ids
        }, function(res){

            if (!res.success) return;

            const data = res.data;

            const colors = {
                running: '#46b450',
                paused: '#ffb900',
                interrupted: '#ff7700',
                failed: '#dc3232',
                completed: '#2271b1',
                cancelled: '#777',
                scheduled: '#8e44ad',
                idle: '#999'
            };

            Object.keys(data).forEach(function(id){

                const agent = data[id];

                const statusEl = $('.aiomatic-agent-status[data-agent-id="'+id+'"]');
                const lastEl   = $('.aiomatic-agent-last[data-agent-id="'+id+'"]');

                if (!statusEl.length) return;

                statusEl.text(agent.status);

                statusEl.css('background', colors[agent.status] || '#999');

                statusEl.removeClass('aiomatic-running');
                if (agent.status === 'running') {
                    statusEl.addClass('aiomatic-running');
                }

                if (lastEl.length) {
                    lastEl.text(agent.last);
                }

            });

        });
    }
    setInterval(aiomaticRefreshAgentStatuses, 5000);
    
    $(document).on('click', '#aiomatic_refine_goal', function(){
        const goal = $('#aiomatic_task_goal').val().trim();
        const agentId = $('#aiomatic_task_agent_id').val();

        if (!goal) {
            alert('Please write something first.');
            return;
        }

        const btn = $(this);
        btn.prop('disabled', true).text('Refining...');

        $.post(ajaxurl, {
            action: 'aiomatic_refine_goal',
            nonce: aiomaticAgent.nonce,
            agent_id: agentId,
            goal: goal
        }, function(res){

            btn.prop('disabled', false).text('✨ Refine with AI');

            if (!res.success) {
                alert(res.data?.message || 'Error');
                return;
            }

            const data = res.data;

            if (data.goal) {
                $('#aiomatic_task_goal').val(data.goal);
            }

            let hasAdvanced = false;

            if (data.constraints && data.constraints.length) {
                $('#aiomatic_task_constraints').val(data.constraints.join("\n"));
                hasAdvanced = true;
            }

            if (data.output_format) {
                $('#aiomatic_task_output').val(data.output_format);
                hasAdvanced = true;
            }

            if (hasAdvanced) {
                $('#aiomatic_advanced_fields').slideDown(150);
                $('#aiomatic_toggle_advanced .aiomatic-icon').text('▲');
            }
            if (data.goal) {
                $('#aiomatic_task_goal')
                    .val(data.goal)
                    .addClass('aiomatic-highlight');

                setTimeout(() => {
                    $('#aiomatic_task_goal').removeClass('aiomatic-highlight');
                }, 1200);
            }

        }).fail(function(){
            btn.prop('disabled', false).text('✨ Refine with AI');
            alert('Request failed');
        });

    });
    let aiomaticLogPoller = null;
    function escapeHtml(text) {
        return $('<div>').text(text).html();
    }
    function aiomaticSetTaskModalState(status, stopUrl) {
        status = status || 'idle';
        stopUrl = stopUrl || '';

        $('#aiomatic_task_agent_status').val(status);

        if (status === 'running') {
            $('#aiomatic-task-modal h2').text('Stop Agent Task');
            $('#aiomatic_start_task_btn').hide();
            $('#aiomatic_stop_task_btn').show();
            $('#aiomatic_stop_task_btn').removeAttr("disabled");
            $('#aiomatic_task_goal, #aiomatic_task_input, #aiomatic_task_constraints, #aiomatic_task_output')
                .prop('disabled', true);
        }
        else if (status === 'paused' || status === 'interrupted') {
            $('#aiomatic-task-modal h2').text('Resume Agent Task');
            $('#aiomatic_start_task_btn').text('Resume').show();
            $('#aiomatic_stop_task_btn').hide();
        } else {
            $('#aiomatic-task-modal h2').text('Start Agent Task');
            $('#aiomatic_stop_task_btn').hide();
            $('#aiomatic_start_task_btn').show();
            $('#aiomatic_start_task_btn').removeAttr("disabled");
            $('#aiomatic_task_goal, #aiomatic_task_input, #aiomatic_task_constraints, #aiomatic_task_output')
                .prop('disabled', false);
        }
    }
    $(document).on('click', '.aiomatic-open-task-modal', function(e){
        e.preventDefault();

        const agentId = $(this).data('agent-id') || '';
        const stopUrlRaw = $(this).data('stop-url') || '';
        const stopUrl = stopUrlRaw.replace(/&amp;/g, '&');

        $('#aiomatic_task_agent_id').val(agentId);
        $('#aiomatic_task_result').text('Loading...\n');

        $('#aiomatic-task-modal').fadeIn(150);

        $.post(aiomaticAgent.ajaxurl, {
            action: 'aiomatic_get_agent_task_info',
            agent_id: agentId,
            nonce: aiomaticAgent.nonce
        }, function(taskRes){

            let status = 'idle';

            if (taskRes && taskRes.success && taskRes.data && taskRes.data.status) {
                status = taskRes.data.status;
            }

            aiomaticSetTaskModalState(status, stopUrl);

            $.post(aiomaticAgent.ajaxurl, {
                action: 'aiomatic_get_agent_logs',
                agent_id: agentId,
                nonce: aiomaticAgent.nonce
            }, function(res){

                if (!res || res.success !== true || !Array.isArray(res.data)) {
                    $('#aiomatic_task_result').text('No logs.\n');
                    return;
                }

                let output = '';
                let lastId = 0;

                res.data.forEach(log => {
                    lastId = Math.max(lastId, log.id || 0);

                    switch (log.type) {
                        case 'model_prompt':
                            output += '[THINKING]\n';
                            break;
                        case 'model_error':
                            output += '[AI ERROR]\n' + (log.response || '') + '\n\n';
                            break;
                        case 'model_response':
                            output += '[RESPONSE]\n' + (log.response || '') + '\n\n';
                            break;
                        case 'tool_call':
                            output += '[TOOL] ' + (log.tool_name || '') + '\n' + (log.params || '') + '\n\n';
                            break;
                        case 'tool_error':
                            output += '[TOOL ERROR] ' + (log.result || '') + '\n\n';
                            break;
                        case 'tool_result':
                            output += '[RESULT]\n\n';// + (log.result || '') + '\n\n';
                            break;
                        case 'final':
                            output += '[FINAL]\n' + (log.result || '') + '\n\n';
                            break;
                        case 'abort':
                            output += '[STOPPED]\n' + (log.result || '') + '\n\n';
                            break;
                        default:
                            output += '[STATUS]\n' + (escapeHtml(log.type || '') + ' - ' + escapeHtml(log.result || ''));
                    }
                });

                $('#aiomatic_task_result').text(output);

                if (status === 'running') {
                    startLiveLogs(agentId, lastId);
                }
            });
        });
    });
    $('#aiomatic_toggle_advanced').on('click', function(e) {
        e.preventDefault();
        
        const $container = $('#aiomatic_advanced_fields');
        const $text = $(this).find('.toggle-text');
        const $icon = $(this).find('.dashicons');

        $container.slideToggle(300, function() {
            if ($container.is(':visible')) {
                $text.text('<?php echo esc_html__("Hide advanced configuration", "aiomatic-automatic-ai-content-writer"); ?>');
                $icon.removeClass('dashicons-plus-alt2').addClass('dashicons-minus');
            } else {
                $text.text('<?php echo esc_html__("Show advanced configuration", "aiomatic-automatic-ai-content-writer"); ?>');
                $icon.removeClass('dashicons-minus').addClass('dashicons-plus-alt2');
            }
        });
    });
    $(document).on('click', '#aiomatic_stop_task_btn', function(e){
        e.preventDefault();

        if (!confirm('Stop this agent task?')) {
            return;
        }

        const btn = $(this);
        const agentId = $('#aiomatic_task_agent_id').val();

        if (!agentId) {
            alert('Missing agent ID.');
            return;
        }

        btn.prop('disabled', true);

        $.post(aiomaticAgent.ajaxurl, {
            action: 'aiomatic_stop_task_ajax',
            agent_id: agentId,
            nonce: aiomaticAgent.nonce
        }, function(res){

            btn.prop('disabled', false);

            if (!res || res.success !== true) {
                alert(res?.data?.message || 'Failed to stop task.');
                return;
            }

            if (window.aiomaticSetTaskModalState) {
                window.aiomaticSetTaskModalState('idle');
            }
            $('#aiomatic_start_task_btn').removeAttr("disabled");
            $('#aiomatic_task_result').append("\n[STOPPED]\n");
        });
    });
    window.aiomaticSetTaskModalState = aiomaticSetTaskModalState;
    function startLiveLogs(agent_id, startFromId = 0) {

        if (aiomaticLogPoller) {
            clearTimeout(aiomaticLogPoller);
            aiomaticLogPoller = null;
        }
        let lastId = startFromId;
        let isRunning = true;

        function poll() {

            if (!isRunning) return;

            $.post(aiomaticAgent.ajaxurl, {
                action: 'aiomatic_get_agent_logs',
                agent_id: agent_id,
                nonce: aiomaticAgent.nonce,
                after_id: lastId
            }, function (res) {

                if (!res || res.success !== true) {
                    return;
                }

                const logs = res.data || [];

                if (!logs.length) {
                    setTimeout(poll, 1500);
                    return;
                }

                logs.forEach(log => {

                    if (log.id <= lastId) {
                        return;
                    }
                    lastId = Math.max(lastId, log.id || 0);

                    let line = '';
                    switch (log.type) {
                        case 'model_prompt':
                            line = '[THINKING]\n';
                            break;
                        case 'model_error':
                            line = '[AI ERROR]\n' + (log.response || '');
                            break;
                        case 'model_response':
                            line = '[RESPONSE]\n' + (log.response || '');
                            break;
                        case 'tool_result':
                            line = '[RESULT]\n\n';// + (log.result || '');
                            break;
                        case 'tool_error':
                            line = '[TOOL ERROR] ' + (log.result || '') + '\n\n';
                            break;
                        case 'tool_call':
                            line = '[TOOL] ' + (log.tool_name || '') + '\n' + (log.params || '') + '\n\n';
                            break;
                        case 'final':
                            line = '[FINAL]\n' + (log.result || '');
                            isRunning = false;
                            break;
                        case 'abort':
                            line = '[STOPPED]\n' + (log.result || '');
                            isRunning = false;
                            break;
                        default:
                            line = '[STATUS]\n' + (escapeHtml(log.type || '') + ' - ' + escapeHtml(log.result || ''));
                    }

                    if (line) {
                        appendLine(line);
                    }
                });

                if (isRunning) {
                    setTimeout(poll, 1500);
                }
                else
                {
                    $('#aiomatic_stop_task_btn').hide();
                    $('#aiomatic_start_task_btn').show();
                    $('#aiomatic_start_task_btn').removeAttr("disabled");
                    $('#aiomatic_task_goal, #aiomatic_task_input, #aiomatic_task_constraints, #aiomatic_task_output').prop('disabled', false);
                }
            });
        }

        function appendLine(text) {
            const $out = $('#aiomatic_task_result');
            $out.append(text + "\n\n");

            $out.scrollTop($out[0].scrollHeight);
        }

        poll();
    }
    const btn = $('<a>', {
        href: aiomaticAgent.backUrl,
        class: 'page-title-action aiomatic-back-inline',
        text: '← Back'
    });

    const $titleAction = $('.wrap .page-title-action');
    const $heading = $('.wrap .wp-heading-inline');

    if ($titleAction.length) {
        $titleAction.last().after(btn);
    } else if ($heading.length) {
        $heading.after(btn);
    }
    
    $(document).on('click', '.start-agent-task', function (e) {
        e.preventDefault();
        const id = $(this).data('id');
        $('#aiomatic_task_agent_id').val(id);
        $('#aiomatic_task_goal').val('');
        $('#aiomatic_task_input').val('');
        $('#aiomatic_task_constraints').val('');
        $('#aiomatic_task_output').val('');
        $('#aiomatic_task_result').text('');

        $('#aiomatic-task-modal').show();
    });

    $(document).on('click', '.aiomatic-modal-close', function () {
        if (aiomaticLogPoller) {
            clearTimeout(aiomaticLogPoller);
            aiomaticLogPoller = null;
        }
        $(this).closest('.aiomatic-modal').hide();
    });

    $(document).on('click', '.aiomatic-modal', function (e) {
        if ($(e.target).hasClass('aiomatic-modal')) {
            if (aiomaticLogPoller) {
                clearTimeout(aiomaticLogPoller);
                aiomaticLogPoller = null;
            }
            $(this).hide();
        }
    });
    function aiomaticStartMonitor(){
        const box = $('#aiomatic-agent-monitor');
        if (!box.length) return;

        const agentId = box.data('agent-id');

        function update(){
            $.post(ajaxurl, {
                action: 'aiomatic_get_agent_status',
                agent_id: agentId,
                nonce: aiomaticAgent.nonce
            }, function(res){

                if (!res || !res.success) return;

                const data = res.data;

                const colors = {
                    running: '#46b450',
                    paused: '#ffb900',
                    interrupted: '#ff7700',
                    failed: '#dc3232',
                    completed: '#2271b1',
                    cancelled: '#777',
                    scheduled: '#8e44ad',
                    idle: '#999'
                };

                $('#aiomatic-agent-status')
                    .text(data.status)
                    .css('background', colors[data.status] || '#999');

                $('#aiomatic-agent-task').text(data.task);
                $('#aiomatic-agent-last').text(data.last);

            });
        }

        update();
        setInterval(update, 5000);
    }

    if ($('#aiomatic-agent-monitor').length) {
        aiomaticStartMonitor();
    }
    $('#aiomatic_start_task_btn').on('click', function () {
        $('#aiomatic_start_task_btn').prop('disabled', true);
        const agent_id = $('#aiomatic_task_agent_id').val();

        const data = {
            goal: $('#aiomatic_task_goal').val(),
            input: $('#aiomatic_task_input').val(),
            constraints: $('#aiomatic_task_constraints').val()
    .split("\n")
    .map(s => s.trim())
    .filter(Boolean),
            output_format: $('#aiomatic_task_output').val()
        };

        if (!data.goal.trim()) {
            $('#aiomatic_start_task_btn').prop('disabled', false);
            alert('Goal is required.');
            return;
        }
        const scheduleType = $('input[name="aiomatic_schedule_type"]:checked').val();
        let scheduleTime = null;

        if (scheduleType === 'schedule') {
            scheduleTime = $('#aiomatic_schedule_datetime').val();

            if (!scheduleTime) {
                $('#aiomatic_start_task_btn').prop('disabled', false);
                alert('Please select a schedule date.');
                return;
            }
        }
        const $out = $('#aiomatic_task_result');
        if (scheduleType === 'schedule') {
            $out.text('Scheduling task...\n');
        } else {
            $out.text('Starting task...\n');
        }

        $.post(aiomaticAgent.ajaxurl, {
            action: 'aiomatic_get_agent_logs',
            agent_id: agent_id,
            nonce: aiomaticAgent.nonce
        }, function (resBefore) {
            
            let lastId = 0;

            if (resBefore && resBefore.success && Array.isArray(resBefore.data) && resBefore.data.length) {
                const last = resBefore.data[resBefore.data.length - 1];
                lastId = last.id || 0;
            }
            $.post(aiomaticAgent.ajaxurl, {
                action: 'aiomatic_start_task_ajax',
                agent_id: agent_id,
                task: JSON.stringify(data),
                schedule_time: scheduleTime,
                nonce: aiomaticAgent.nonce
            }, function (res) {
                if (scheduleType !== 'schedule') {
                    startLiveLogs(agent_id, lastId);
                }

                if (!res || res.success !== true) {
                    const msg = res.data?.message || 'The request failed.';
                    $('#aiomatic_task_result').append(msg + "\n");
                    return;
                }
                if (scheduleType !== 'schedule') {
                    if (window.aiomaticSetTaskModalState) {
                        const stopUrlRaw = res.data?.stop_url || '';
                        const stopUrl = stopUrlRaw.replace(/&amp;/g, '&');
                        window.aiomaticSetTaskModalState('running', stopUrl);
                    }
                }
                else
                {
                    $('#aiomatic_start_task_btn').prop('disabled', false);
                }
                const result = res?.data?.result;
                const output = typeof result === 'string'
                    ? result
                    : JSON.stringify(result ?? '', null, 2);
                $out.append(output + "\n");
            });
        });
    });
    $(document).on('change', 'input[name="aiomatic_schedule_type"]', function () {
        if ($(this).val() === 'schedule') {
            $('#aiomatic_schedule_picker').slideDown(120);
        } else {
            $('#aiomatic_schedule_picker').slideUp(120);
        }
    });
    let aiomaticLogsCache = [];
    let aiomaticFirstLogId = 0;
    let aiomaticLoadingOlder = false;
    let aiomaticHasMoreLogs = true;
    function renderLogs(logs) {

        const selectedType = $('#aiomatic-log-type-filter').val();

        let html = '<div class="aiomatic-logs-list">';
        let currentStep = null;

        logs.forEach(log => {

            if (selectedType && log.type !== selectedType) {
                return;
            }

            if (currentStep !== log.step) {
                currentStep = log.step;
                html += `<div class="aiomatic-step">Run ${log.step}</div>`;
            }

            let color = '#999';

            switch (log.type) {
                case 'model_prompt':   color = '#6c5ce7'; break;
                case 'model_error':    color = '#dc3232'; break;
                case 'model_response': color = '#00b894'; break;
                case 'tool_call':      color = '#0984e3'; break;
                case 'tool_error':     color = '#dc3232'; break;
                case 'tool_result':    color = '#00cec9'; break;
                case 'final':          color = '#2d3436'; break;
                case 'error':          color = '#dc3232'; break;
            }

            html += `
                <div class="aiomatic-log-item">
                    <div class="aiomatic-log-head">
                        <span class="aiomatic-log-type" style="background:${color}">
                            ${log.type}
                        </span>
                        <span class="aiomatic-log-time">${log.time}</span>
                    </div>
                    <div class="aiomatic-log-message">
            `;

            if (log.tool) {
                html += `<div><strong>Tool:</strong> ${escapeHtml(log.tool)}</div>`;
            }

            if (log.prompt) {
                html += `<pre>${escapeHtml((log.prompt || '').substring(0, 800))}</pre>`;
            }

            if (log.response) {
                html += `<pre>${escapeHtml((log.response || '').substring(0, 800))}</pre>`;
            }

            if (log.result) {
                html += `<pre>${escapeHtml((log.result || '').substring(0, 800))}</pre>`;
            }

            html += `</div></div>`;
        });

        html += '</div>';

        $('#aiomatic_logs_container').html(html);
    }
    $(document).on('click', '.clear-agent-long-memory', function (e) {
        e.preventDefault();

        const id = $(this).data('id');

        if (!confirm('Clear long-term memory for this agent? This cannot be undone.')) {
            return;
        }

        const $el = $(this);
        $el.text('Clearing...').css('pointer-events', 'none');

        $.post(aiomaticAgent.ajaxurl, {
            action: 'aiomatic_clear_agent_long_memory',
            agent_id: id,
            nonce: aiomaticAgent.nonce
        })
        .done(function (res) {

            if (!res.success) {
                alert(res.data?.message || 'Failed to clear memory');
                $el.text('Clear Long Term Memory').css('pointer-events', '');
                return;
            }

            const count = res.data?.deleted || 0;

            alert('Long-term memory cleared (' + count + ' entries).');

            $el.text('Cleared').css({ opacity: 0.6, 'pointer-events': '' });

        })
        .fail(function () {
            alert('Request failed!');
            $el.text('Clear Long Term Memory').css('pointer-events', '');
        });
    });
    $(document).on('click', '#aiomatic-delete-logs', function(){

        if (!confirm('Delete all logs for this agent?')) {
            return;
        }

        const id = $('#aiomatic_logs_agent_id').val();
        const $container = $('#aiomatic_logs_container');
        const $btn = $('#aiomatic-delete-logs');

        $container.html('<div class="aiomatic-logs-loading">Deleting...</div>');
        $btn.prop('disabled', true);

        $.post(aiomaticAgent.ajaxurl, {
            action: 'aiomatic_delete_agent_logs',
            agent_id: id,
            nonce: aiomaticAgent.nonce
        })
        .done(function(res){

            $btn.prop('disabled', false);

            if (!res.success) {

                let msg = 'Failed to delete logs.';

                if (res.data) {
                    if (typeof res.data === 'string') {
                        msg = res.data;
                    } else if (res.data.message) {
                        msg = res.data.message;
                    }
                }

                $container.html('<div class="aiomatic-empty" style="color:red;">' + msg + '</div>');
                return;
            }

            $container.html('<div class="aiomatic-empty">Logs deleted.</div>');
        })
        .fail(function(xhr){

            $btn.prop('disabled', false);

            let msg = 'Request failed.';

            if (xhr.responseText) {
                msg = xhr.responseText;
            }

            $container.html('<div class="aiomatic-empty" style="color:red;">' + msg + '</div>');
        });
    });
    function loadOlderLogs() {

        if (aiomaticLoadingOlder || !aiomaticHasMoreLogs || !aiomaticFirstLogId) {
            return;
        }

        aiomaticLoadingOlder = true;

        const agentId = $('#aiomatic_logs_agent_id').val();
        const $container = $('#aiomatic_logs_list');

        const prevScrollHeight = $container[0].scrollHeight;

        $.post(aiomaticAgent.ajaxurl, {
            action: 'aiomatic_get_agent_logs',
            agent_id: agentId,
            before_id: aiomaticFirstLogId,
            nonce: aiomaticAgent.nonce
        }, function (res) {

            aiomaticLoadingOlder = false;

            if (!res || res.success !== true || !res.data.length) {
                aiomaticHasMoreLogs = false;
                $('#aiomatic-load-older-logs')
                    .text('No more logs')
                    .prop('disabled', true);
                return;
            }

            const newLogs = res.data;

            aiomaticFirstLogId = newLogs[0].id;

            // prepend to cache
            aiomaticLogsCache = newLogs.concat(aiomaticLogsCache);

            // re-render
            renderLogs(aiomaticLogsCache);

            // maintain scroll position (important)
            const newScrollHeight = $container[0].scrollHeight;
            $container.scrollTop(newScrollHeight - prevScrollHeight);
        });
    }
    $(document).on('click', '#aiomatic_agents_import_btn', function(e){
        e.preventDefault();

        if(!confirm('Import agents from file?')) return;

        const fileInput = $('#aiomatic_agents_upload')[0];

        if (!fileInput.files.length) {
            alert('Please select a JSON file.');
            return;
        }

        const file = fileInput.files[0];
        const ext = file.name.split('.').pop().toLowerCase();

        if (ext !== 'json') {
            alert('Only JSON files allowed.');
            return;
        }

        const formData = new FormData();
        formData.append('action', 'aiomatic_agents_upload');
        formData.append('nonce', aiomaticAgent.nonce);
        formData.append('overwrite', $('#aiomatic_agents_overwrite').is(':checked') ? '1' : '0');
        formData.append('file', file);

        const $btn = $(this);

        $.ajax({
            url: aiomaticAgent.ajaxurl,
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            beforeSend: function(){
                $btn.text('Importing...').prop('disabled', true);
            },
            success: function(res){
                $btn.text('Import Agents').prop('disabled', false);

                if (!res.success) {
                    alert(res.data?.message || 'Import failed');
                    return;
                }

                alert('Agents imported successfully!');
                location.reload();
            },
            error: function(){
                $btn.text('Import Agents').prop('disabled', false);
                alert('Request failed');
            }
        });
    });

    $(document).on('click', '#aiomatic_agents_default_btn', function(e){
        e.preventDefault();

        if(!confirm('Import default agents?')) return;

        const $btn = $(this);

        $.post(aiomaticAgent.ajaxurl, {
            action: 'aiomatic_default_agents',
            nonce: aiomaticAgent.nonce
        }, function(res){

            $btn.prop('disabled', false);

            if (!res.success) {
                alert(res.data?.message || 'Failed');
                return;
            }

            alert('Default agents imported!');
            location.reload();

        });
    });
    $(document).on('click', '#aiomatic_backup_agents', function(){
        $('#aiomatic-backup-modal').fadeIn(150);
    });

    $(document).on('click', '#aiomatic_close_backup_agents', function(){
        $('#aiomatic-backup-modal').fadeOut(150);
    });
    $(document).on('change', '#aiomatic-log-type-filter', function () {
        renderLogs(aiomaticLogsCache);
    });
    $(document).on('click', '#aiomatic-load-older-logs', function () {
        loadOlderLogs();
    });
    $(document).on('click', '.view-agent-logs', function (e) {
        e.preventDefault();

        const id = $(this).data('id');
        $('#aiomatic_logs_agent_id').val(id);
        const $modal = $('#aiomatic-logs-modal');
        const $container = $('#aiomatic_logs_container');

        aiomaticLogsCache = [];
        aiomaticFirstLogId = 0;
        aiomaticHasMoreLogs = true;
        aiomaticLoadingOlder = false;

        $('#aiomatic-load-older-logs')
            .text('Load older logs')
            .prop('disabled', false);

        $('#aiomatic-load-older-wrapper').hide();
        
        $container.html('<div class="aiomatic-logs-loading">Loading...</div>');
        $modal.show();

        $.post(aiomaticAgent.ajaxurl, {
            action: 'aiomatic_get_agent_logs',
            agent_id: id,
            nonce: aiomaticAgent.nonce
        }, function (res) {

            if (!res || res.success !== true || !Array.isArray(res.data) || !res.data.length) {
                $container.html('<div class="aiomatic-empty">No logs found.</div>');
                return;
            }
            aiomaticLogsCache = res.data;
            if (aiomaticLogsCache.length) {
                aiomaticFirstLogId = aiomaticLogsCache[0].id;
                aiomaticHasMoreLogs = true;
                $('#aiomatic-load-older-wrapper').show();
            } else {
                $('#aiomatic-load-older-wrapper').hide();
            }
            renderLogs(aiomaticLogsCache);
        });
    });
});