const { __, sprintf } = wp.i18n;

document.addEventListener('DOMContentLoaded', function() {
    if (typeof FusionCharts === 'undefined') {
        console.error('FusionCharts Error');
        return;
    }
    new FusionCharts({
        id: "myDoughnutChart",
        type: 'doughnut2d',
        renderAt: 'chart-container',
        width: "100%",
        height: "100%",
        dataFormat: "xml",
        dataSource: `
            <chart 
                bgAlpha='0' bgColor='#FFFFFF' canvasBgColor='#FFFFFF'
                anchorBgColor='#FFFFFF' legendBgColor='#FFFFFF'
                borderColor='#D6E1F0' xAxisLineColor='#D6E1F0' yAxisLineColor='#D6E1F0'
                divLineColor='#D6E1F0' baseFontColor='#000000' legendBorderColor='#D6E1F0'
                toolTipBorderColor='#0278BE' toolTipBgColor='#0278BE' toolTipColor='#FFFFFF'
                toolTipBgAlpha='80' palettecolors='#02569C,#0168AD,#0278BE,#0288D1,#039AE3,#03A9F5,#28B6F6,#4DC2F7,#72CFFA,#97DCFB,#BBE8FB,#E1F5FE'
                drawAnchors='0' anchorRadius='2' showLabels='1' showToolTip='1'
                allowSelection='1' captionpadding='0' showLimits='0' displayValue='1'
                showValues='0' adjustDiv='1' showLegend='0' showCanvasBorder='0'
                showCanvasBg='0' canvasBaseDepth='0' canvasBgDepth='0' showBorder='0'
                animation='0' showZeroPlaneValue='0' legendShadow='0' legendPadding='0'
                interactiveLegend='1' placevaluesinside='0' showZeroPlane='1'
                plotBorderColor='#D6E1F0' usePlotGradientColor='0' axislinealpha='75'
                divlinealpha='50' crossLineAlpha='50' drawCrossLineOnTop='1' drawCrossLine='1'
                crosslinecolor='#0288D1' showShadow='0' showAlternateHGridColor='0'
                tooltipborderradius='5' tooltippadding='5' alignLegendWithCanvas='1'
                crossLineAnimation='0' plotColorinTooltip='0' toolTipBorderThickness='0'
                baseFont='Roboto' chartTopMargin='5' chartBottomMargin='5'
                chartRightMargin='5' chartLeftMargin='5' labelFontSize='10'
                skipOverlapLabels='1' enableSlicing='0' use3DLighting='0'
                showValue='0' radius3D='0' defaultcenterlabel='33%' 
                centerLabelToolText='67% ${__('Completed', 'swpanel-ai')}' centerLabelFontSize='34'
                showPlotBorder='1' enableSmartLabels='1' useEllipsesWhenOverflow='1'
                doughnutRadius='75%' startingAngle='270' manageLabelOverflow='1'
                centerLabelBold='1' animateClockwise='0'
            >
                <set value='67' label='${__('Pending', 'swpanel-ai')}' toolText='${__('Pending', 'swpanel-ai')}' color='#4DC2F7' borderColor='#4DC2F7'/>
                <set value='33' label='${__('Completed', 'swpanel-ai')}' toolText='${__('Completed', 'swpanel-ai')}' color='#0278BE' borderColor='#0278BE'/>
            </chart>
        `
    }).render();
});

function updateChartValues(done, pending) {
    const chart = FusionCharts.items["myDoughnutChart"];
    if (!chart) {
        console.error("Chart not initialized or invalid");
        return;
    }
    const total = done + pending;
    const percent = total === 0 ? 0 : Math.round((done / total) * 100);
    chart.setXMLData(`
        <chart 
            bgAlpha='0' bgColor='#FFFFFF' canvasBgColor='#FFFFFF'
            anchorBgColor='#FFFFFF' legendBgColor='#FFFFFF'
            borderColor='#D6E1F0' xAxisLineColor='#D6E1F0' yAxisLineColor='#D6E1F0'
            divLineColor='#D6E1F0' baseFontColor='#000000' legendBorderColor='#D6E1F0'
            toolTipBorderColor='#0278BE' toolTipBgColor='#0278BE' toolTipColor='#FFFFFF'
            toolTipBgAlpha='80' palettecolors='#02569C,#0168AD,#0278BE,#0288D1,#039AE3,#03A9F5,#28B6F6,#4DC2F7,#72CFFA,#97DCFB,#BBE8FB,#E1F5FE'
            drawAnchors='0' anchorRadius='2' showLabels='1' showToolTip='1'
            allowSelection='1' captionpadding='0' showLimits='0' displayValue='1'
            showValues='0' adjustDiv='1' showLegend='0' showCanvasBorder='0'
            showCanvasBg='0' canvasBaseDepth='0' canvasBgDepth='0' showBorder='0'
            animation='0' showZeroPlaneValue='0' legendShadow='0' legendPadding='0'
            interactiveLegend='1' placevaluesinside='0' showZeroPlane='1'
            plotBorderColor='#D6E1F0' usePlotGradientColor='0' axislinealpha='75'
            divlinealpha='50' crossLineAlpha='50' drawCrossLineOnTop='1' drawCrossLine='1'
            crosslinecolor='#0288D1' showShadow='0' showAlternateHGridColor='0'
            tooltipborderradius='5' tooltippadding='5' alignLegendWithCanvas='1'
            crossLineAnimation='0' plotColorinTooltip='0' toolTipBorderThickness='0'
            baseFont='Roboto' chartTopMargin='5' chartBottomMargin='5'
            chartRightMargin='5' chartLeftMargin='5' labelFontSize='10'
            skipOverlapLabels='1' enableSlicing='0' use3DLighting='0'
            showValue='0' radius3D='0' defaultcenterlabel='${percent}%' 
            centerLabelToolText='${percent}% completado' centerLabelFontSize='34'
            showPlotBorder='1' enableSmartLabels='1' useEllipsesWhenOverflow='1'
            doughnutRadius='75%' startingAngle='270' manageLabelOverflow='1'
            centerLabelBold='1' animateClockwise='0'
        >
            <set value='${pending}' label='${__('Pending', 'swpanel-ai')}' color='#4DC2F7'/>
            <set value='${done}' label='${__('Completed', 'swpanel-ai')}' color='#0278BE'/>
        </chart>
    `);
    const message = sprintf(
    __('%1$d steps remaining out of %2$d', 'swpanel-ai'),
    pending,
    total
    );
    document.getElementById('chart-text').textContent = message;
}

jQuery(document).ready(function($) {
    function createTask() {
        $.ajax({
            url: swpanel_ai_data.ajax_url,
            type: 'POST',
            data: {
                action: 'swpanel_ai_create_task',
            },
            success: function(response) {
                checkStatus();
            },
            error: function() {
                $('#loading-div').hide();
                $('#load-error').show();
		        $('#load-error').css('display', 'flex');
                $('#message-error').text(__('Error creating page', 'swpanel-ai'));
            }
        });
    }

    function renderSteps(steps) {
        const container = $('#progress-bar');
        container.empty();
        
        let done = 0;
        let pending = 0;
        steps.forEach(step => {
            const status = (step.status || "").toLowerCase();
            if (status === "done") {
                done++;
                container.append(`
                    <div class="progress-step">
                        <div class="circle completed">
                            <i class="fa fa-check"></i>
                        </div>
                        <div class="label">${step.text}</div>
                    </div>
                `);
            } else if (step.status === 'started') {
                pending++;
                container.append(`
                    <div class="progress-step">
                        <div class="circle">
                            <i class="fa fa-spinner fa-pulse"></i>
                        </div>
                        <div class="label">${step.text}</div>
                    </div>
                `);
            } else {
                pending++;
                container.append(`
                    <div class="progress-step">
                        <div class="circle">
                            <i class="fa fa-times"></i>
                        </div>
                        <div class="label">${step.text}</div>
                    </div>
                `);
            }
        });

        updateChartValues(done, pending);
    }

    function checkStatus() {
        $.ajax({
            url: swpanel_ai_data.ajax_url,
            method: 'POST',
            data: {
                action: 'swpanel_ai_check_task',
            },
            success: function(res) {
                if (res.success && res.data.steps) {
                    renderSteps(res.data.steps);
                }

                if (res.success && res.data.status === 'done') {
                    window.location.href = swpanel_ai_data.admin_redirect_url;
                } else if (res.success && res.data.status === 'started') {
                    setTimeout(function() {
                        checkStatus();
                    }, 1000);
                } else if (res.success && res.data.status === 'error') {
                    $('#loading-div').hide();
                    $('#load-error').show();
		            $('#load-error').css('display', 'flex');
                    $('#message-error').text(res.data.message || __('ERROR', 'swpanel-ai'));
                } else if (res.success) {
                    setTimeout(function() {
                        checkStatus();
                    }, 1000);
                } else {
                    $('#loading-div').hide();
                    $('#load-error').show();
		            $('#load-error').css('display', 'flex');
                    $('#message-error').text(res.data);
                    $('#retry-load').text(swpanel_ai_data.retry_text);
                }
            },
            error: function(res) {
                $('#retry-load').text(swpanel_ai_data.retry_text);
                $('#loading-div').hide();
                $('#load-error').show();
		        $('#load-error').css('display', 'flex');
                $('#message-error').text(response.statusText);
            }
        });
    }

    $('#retry-load').on('click', function() {
        createTask();
        $('#loading-div').show();
        $('#load-error').hide();
    });    
    
    if (swpanel_ai_data.run_creating_task == 1) {
        createTask();
    } else {
        if (!swpanel_ai_data.background_task || swpanel_ai_data.background_task.status==='done') {
            $('#loading-div').hide();
            $('#load-error').show();
		    $('#load-error').css('display', 'flex');
            $('#retry-load').hide();
            $('#message-error').text(__('Waiting for process to start or it failed.', 'swpanel-ai'));
        } else {
            checkStatus();
        }
    }
});