/**
 * Internal Links analysis workflow.
 * Handles full runs, test runs, troubleshooting actions, and progress polling.
 */

(function ($) {
    'use strict';

    var config = window.CPANALYZER_INTERNAL_LINKS_ANALYSIS || window.CPA_INTERNAL_LINKS_ANALYSIS;
    var analysisStartTime = null;
    var overtimeShown = false;

    if (!config) {
        return;
    }

    function setStatus(message, type) {
        var $status = $('#cpanalyzer-analysis-status');
        if (!$status.length) {
            return;
        }

        var color = '#5c6770';
        if (type === 'success') {
            color = '#008a20';
        } else if (type === 'error') {
            color = '#b42318';
        } else if (type === 'warning') {
            color = '#b45309';
        }

        $status.html('<span style="color:' + color + ';">' + message + '</span>');
    }

    function showDebugMessage(message) {
        var $output = $('#cpanalyzer-debug-output');
        if (!$output.length) {
            return;
        }

        $output.prop('hidden', false).text(message);
    }

    function setButtonState($button, busy, busyLabel, idleLabel) {
        if (!$button.length) {
            return;
        }

        $button.prop('disabled', !!busy);
        if (busy) {
            $button.html('<span class="spinner is-active" style="float:none;margin:0 6px 0 0;"></span>' + busyLabel);
        } else if (idleLabel) {
            $button.html(idleLabel);
        }
    }

    function updateProgress(status) {
        if (!status || typeof status.processed === 'undefined' || typeof status.total === 'undefined') {
            return;
        }

        var total = Math.max(parseInt(status.total, 10) || 0, 1);
        var processed = parseInt(status.processed, 10) || 0;
        var percent = Math.min(100, Math.max(0, Math.round((processed / total) * 100)));
        var remaining = Math.max(total - processed, 0);

        $('#cpanalyzer-progress-percent').text(percent + '%');
        $('#cpanalyzer-progress-text').text(config.strings.progress + ' ' + processed + ' ' + config.strings.of + ' ' + total + ' ' + config.strings.itemsProcessed);
        $('#cpanalyzer-progress-bar-fill').css('width', percent + '%');

        if (remaining > 0) {
            $('#cpanalyzer-time-remaining').text(config.strings.timeRemaining + ' ' + remaining + ' ' + config.strings.minutes);
        } else {
            $('#cpanalyzer-time-remaining').text(config.strings.almostFinished);
        }
    }

    function pollAnalysisStatus() {
        $.ajax({
            url: config.ajaxurl,
            type: 'POST',
            data: {
                action: 'cpanalyzer_get_link_analysis_status',
                nonce: config.nonce
            }
        }).done(function (response) {
            if (!response || !response.success) {
                setTimeout(pollAnalysisStatus, 5000);
                return;
            }

            var status = response.data.status || {};
            if (status.status === 'analyzing') {
                updateProgress(status);
                setTimeout(pollAnalysisStatus, 3000);
                return;
            }

            if (status.status === 'completed') {
                location.reload();
            }
        }).fail(function () {
            setTimeout(pollAnalysisStatus, 5000);
        });
    }

    function checkOvertime() {
        if (!analysisStartTime || overtimeShown) {
            return;
        }

        var elapsed = (Date.now() - analysisStartTime) / 1000;
        var expectedTime = (parseInt(config.estimatedDuration, 10) || 0) + 300;

        if (elapsed > expectedTime) {
            $('#cpanalyzer-overtime-message').prop('hidden', false);
            overtimeShown = true;
            return;
        }

        setTimeout(checkOvertime, 30000);
    }

    function runRequest(options) {
        $.ajax({
            url: config.ajaxurl,
            type: 'POST',
            data: options.data
        }).done(function (response) {
            options.onSuccess(response);
        }).fail(function (xhr) {
            if (options.onError) {
                options.onError(xhr);
            }
        }).always(function () {
            if (options.onComplete) {
                options.onComplete();
            }
        });
    }

    $(document).ready(function () {
        var analyzeLabel = '<span class="dashicons dashicons-analytics"></span>' + config.strings.analyzeButton;
        var testLabel = '<span class="dashicons dashicons-hammer"></span>' + config.strings.testButton;

        if (config.isAnalyzing) {
            analysisStartTime = Date.now() - ((parseInt(config.processedCount, 10) || 0) * 60000);
            $('#cpanalyzer-analysis-progress').prop('hidden', false);
            pollAnalysisStatus();
            checkOvertime();
        }

        $('#cpanalyzer-analyze-links').on('click', function () {
            var $button = $(this);
            var confirmMessage = config.strings.confirmStart;

            if (config.hasEstimate) {
                confirmMessage += '\n\n' + config.strings.foundItems;
                confirmMessage += '\n' + config.strings.estimatedTime;
                confirmMessage += '\n\n' + config.strings.runsInBackground;
            } else {
                confirmMessage += '\n\n' + config.strings.mayTakeTime;
            }

            if (!window.confirm(confirmMessage)) {
                return;
            }

            setButtonState($button, true, config.strings.startingAnalysis);
            $('#cpanalyzer-manual-trigger').prop('disabled', true);
            setStatus(config.strings.preparingContent, 'info');

            runRequest({
                data: {
                    action: 'cpanalyzer_analyze_internal_links',
                    nonce: config.nonce
                },
                onSuccess: function (response) {
                    if (response && response.success) {
                        setStatus(response.data.message, 'success');
                        analysisStartTime = Date.now();
                        overtimeShown = false;
                        $('#cpanalyzer-analysis-progress').prop('hidden', false).show();
                        setTimeout(function () {
                            pollAnalysisStatus();
                            checkOvertime();
                        }, 1500);
                    } else {
                        setStatus((response && response.data && response.data.message) || config.strings.errorStarting, 'error');
                        setButtonState($button, false, null, analyzeLabel);
                        $('#cpanalyzer-manual-trigger').prop('disabled', false);
                    }
                },
                onError: function () {
                    setStatus(config.strings.errorStarting, 'error');
                    setButtonState($button, false, null, analyzeLabel);
                    $('#cpanalyzer-manual-trigger').prop('disabled', false);
                }
            });
        });

        $('#cpanalyzer-manual-trigger').on('click', function () {
            var $button = $(this);

            if (!window.confirm(config.strings.confirmTest)) {
                return;
            }

            setButtonState($button, true, config.strings.startingTest);
            $('#cpanalyzer-analyze-links').prop('disabled', true);
            setStatus(config.strings.startingTest, 'info');

            runRequest({
                data: {
                    action: 'cpanalyzer_trigger_link_analysis',
                    nonce: config.nonce
                },
                onSuccess: function (response) {
                    if (response && response.success) {
                        setStatus(response.data.message, 'success');
                        setTimeout(function () {
                            location.reload();
                        }, 1400);
                    } else {
                        setStatus((response && response.data && response.data.message) || config.strings.errorStarting, 'error');
                    }
                },
                onError: function () {
                    setStatus(config.strings.errorStarting, 'error');
                },
                onComplete: function () {
                    setButtonState($button, false, null, testLabel);
                    $('#cpanalyzer-analyze-links').prop('disabled', false);
                }
            });
        });

        $('#cpanalyzer-check-cron').on('click', function () {
            var $button = $(this);
            var originalLabel = $button.html();
            setButtonState($button, true, config.strings.checkingCron);
            showDebugMessage(config.strings.checkingCron);

            runRequest({
                data: {
                    action: 'cpanalyzer_debug_cron',
                    nonce: config.nonce
                },
                onSuccess: function (response) {
                    if (response && response.success) {
                        showDebugMessage(config.strings.cronStatus + ': ' + response.data.message);
                    } else {
                        showDebugMessage((response && response.data && response.data.message) || config.strings.errorStarting);
                    }
                },
                onError: function () {
                    showDebugMessage(config.strings.errorStarting);
                },
                onComplete: function () {
                    setButtonState($button, false, null, originalLabel);
                }
            });
        });

        $('#cpanalyzer-reset-analysis').on('click', function () {
            var $button = $(this);
            var originalLabel = $button.html();

            if (!window.confirm(config.strings.confirmReset)) {
                return;
            }

            setButtonState($button, true, config.strings.resetting);
            setStatus(config.strings.resetting, 'warning');

            runRequest({
                data: {
                    action: 'cpanalyzer_reset_link_analysis',
                    nonce: config.nonce
                },
                onSuccess: function (response) {
                    if (response && response.success) {
                        setStatus(config.strings.resetSuccess, 'success');
                        setTimeout(function () {
                            location.reload();
                        }, 1000);
                    } else {
                        setStatus((response && response.data && response.data.message) || config.strings.errorStarting, 'error');
                        setButtonState($button, false, null, originalLabel);
                    }
                },
                onError: function () {
                    setStatus(config.strings.errorStarting, 'error');
                    setButtonState($button, false, null, originalLabel);
                }
            });
        });
    });
})(jQuery);
