jQuery(document).ready(function($) {
    const debugEnabled = !!window.aysaDebug;
    const debugLog = (...args) => { if (debugEnabled) { console.log(...args); } };
    const debugError = (...args) => { if (debugEnabled) { console.error(...args); } };
    const AYSA_API_BASE = (() => {
        const configured = (window.aysa_ajax && window.aysa_ajax.api_base_url)
            ? String(window.aysa_ajax.api_base_url).trim()
            : '';
        if (configured !== '') {
            return configured.replace(/\/+$/, '');
        }
        return 'https://api.aysa.ai';
    })();

    function scheduleDomainAuthorityTasks() {
        debugLog('[AYSA DOMAIN AUTHORITY] Starting task scheduling process');
        const automationConfig = window.aysaAutomationConfig || {};
        const ajaxurl = automationConfig.ajaxurl || '/wp-admin/admin-ajax.php';

        if (!automationConfig.domain_authority_automation) {
            debugLog('[AYSA DOMAIN AUTHORITY] Domain Authority automation is disabled');
            return;
        }

        const projectId = getProjectId();
        if (!projectId) {
            debugLog('[AYSA DOMAIN AUTHORITY] No project ID available for scheduling');
            return;
        }

        debugLog('[AYSA DOMAIN AUTHORITY] Fetching competitor data for project: ' + projectId);
        fetch(`${AYSA_API_BASE}/api/aysa-plugin/datasks/domain-authority-avg/${projectId}`)
            .then(response => {
                debugLog('[AYSA DOMAIN AUTHORITY] API response status: ' + response.status);
                return response.json();
            })
            .then(data => {
                const filtered = (Array.isArray(data) ? data : []).filter(x => x.backlinksCount > 0 && x.averageDomainAuthority > 0);
                if (!filtered.length) {
                    debugLog('[AYSA DOMAIN AUTHORITY] No valid competitor data found');
                    return;
                }

                const meanBacklinks = Math.round(filtered.reduce((sum, x) => sum + x.backlinksCount, 0) / filtered.length);
                const meanAuthority = Math.round(filtered.reduce((sum, x) => sum + x.averageDomainAuthority, 0) / filtered.length);

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'aysa_schedule_domain_authority_task',
                        project_id: projectId,
                        mean_backlinks: meanBacklinks,
                        mean_authority: meanAuthority,
                        competitor_data: JSON.stringify(filtered),
                        nonce: automationConfig.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            if (typeof loadQueueStatistics === 'function') {
                                loadQueueStatistics();
                            }
                        } else {
                            debugError('[AYSA DOMAIN AUTHORITY] Task scheduling failed: ' + (response.data || 'Unknown error'));
                        }
                    },
                    error: function(xhr, status, error) {
                        debugError('[AYSA DOMAIN AUTHORITY] AJAX error during task scheduling: ' + error + ', Status: ' + status);
                    }
                });
            })
            .catch(err => {
                debugError('[AYSA DOMAIN AUTHORITY] Error fetching competitor data: ' + err.message);
            });
    }

    function scheduleAssociationTasks() {
        debugLog('[AYSA DOMAIN AUTHORITY] Starting association task scheduling process');
        const automationConfig = window.aysaAutomationConfig || {};
        const ajaxurl = automationConfig.ajaxurl || '/wp-admin/admin-ajax.php';

        if (!automationConfig.domain_authority_automation) {
            debugLog('[AYSA DOMAIN AUTHORITY] Domain Authority automation is disabled');
            return;
        }

        const projectId = getProjectId();
        if (!projectId) {
            debugLog('[AYSA DOMAIN AUTHORITY] No project ID available for association scheduling');
            return;
        }

        fetch(`${AYSA_API_BASE}/api/AssociationsTask/ToAssociateCount/${projectId}`)
            .then(response => response.json())
            .then(data => {
                const associationCount = data.toAssociateCount || 0;
                if (associationCount <= 0) {
                    return;
                }

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'aysa_schedule_association_task',
                        project_id: projectId,
                        association_count: associationCount,
                        nonce: automationConfig.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            if (typeof loadQueueStatistics === 'function') {
                                loadQueueStatistics();
                            }
                        } else {
                            debugError('[AYSA DOMAIN AUTHORITY] Association task scheduling failed: ' + (response.data || 'Unknown error'));
                        }
                    },
                    error: function(xhr, status, error) {
                        debugError('[AYSA DOMAIN AUTHORITY] AJAX error during association task scheduling: ' + error + ', Status: ' + status);
                    }
                });
            })
            .catch(err => {
                debugError('[AYSA DOMAIN AUTHORITY] Error fetching association data: ' + err.message);
            });
    }

    function getProjectId() {
        let projectId = localStorage.getItem('aysa_project_id');
        if (projectId && parseInt(projectId, 10) > 0) {
            return parseInt(projectId, 10);
        }

        let apiProjectId = null;
        const domain = window.location.hostname;
        const xhr = new XMLHttpRequest();
        xhr.open('GET', AYSA_API_BASE + '/api/Project/getbydomain/' + domain, false);
        xhr.onload = function() {
            if (xhr.status === 200) {
                try {
                    const resp = JSON.parse(xhr.responseText);
                    if (resp && resp.projectId) {
                        apiProjectId = resp.projectId;
                        localStorage.setItem('aysa_project_id', apiProjectId);
                    }
                } catch (e) {
                    debugError('[AYSA DOMAIN AUTHORITY] Error parsing API response: ' + e.message);
                }
            } else {
                debugError('[AYSA DOMAIN AUTHORITY] API request failed with status: ' + xhr.status);
            }
        };
        xhr.send();
        return apiProjectId ? parseInt(apiProjectId, 10) : 0;
    }

    $(document).on('click', '.schedule-domain-authority', function() {
        scheduleDomainAuthorityTasks();
    });

    $(document).on('click', '.schedule-association-tasks', function() {
        scheduleAssociationTasks();
    });

    if (window.aysaAutomationConfig && window.aysaAutomationConfig.domain_authority_automation) {
        setTimeout(function() {
            scheduleDomainAuthorityTasks();
            scheduleAssociationTasks();
        }, 2000);
    }
});
