document.addEventListener('DOMContentLoaded', function () {
    const greenButtons = document.querySelectorAll(".green-button");
    greenButtons.forEach(button => {
        button.addEventListener("click", function(e) {
            this.innerHTML = `<img src="${swpanel_ai_data.pluginUrl}../admin/assets/img/loader_points_white.svg" alt="Loading...">`;
        });
    });
    const blueButtons = document.querySelectorAll(".blue-button");
    blueButtons.forEach(button => {
        button.addEventListener("click", function(e) {
            this.innerHTML = `<img src="${swpanel_ai_data.pluginUrl}../admin/assets/img/loader_points_white.svg" alt="Loading...">`;
        });
    });
    const whiteButtons = document.querySelectorAll(".white-button");
    whiteButtons.forEach(button => {
        button.addEventListener("click", function(e) {
            this.innerHTML = `<img src="${swpanel_ai_data.pluginUrl}../admin/assets/img/loader_points_blue.svg" alt="Loading...">`;
        });
    });
    
    const { __ } = wp.i18n;
    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='11%' 
                centerLabelToolText='11% ${__('Completed', 'swpanel-ai')}' centerLabelFontSize='34'
                showPlotBorder='1' enableSmartLabels='1' useEllipsesWhenOverflow='1'
                doughnutRadius='75%' startingAngle='270' manageLabelOverflow='1'
                centerLabelBold='1' animateClockwise='0'
            >
                <set value='89' label='${__('Pending', 'swpanel-ai')}' toolText='${__('Pending', 'swpanel-ai')}' color='#4DC2F7' borderColor='#4DC2F7'/>
                <set value='11' label='${__('Completed', 'swpanel-ai')}' toolText='${__('Completed', 'swpanel-ai')}' color='#0278BE' borderColor='#0278BE'/>
            </chart>
        `
    }).render();
    FusionCharts.items["myDoughnutChart"].addEventListener("renderComplete", function (event) {
        event.sender.setChartAttribute("defaultcenterlabel", "11%");
    });
});
    
jQuery(document).ready(function($) {
    function loadHeadersData() {
        $('#loading').show();
		$('#loading').css('display', 'flex');
        $('#load-error').hide();

        $.ajax({
            url: swpanel_ai_data.ajax_url,
            type: 'POST',
            data: {
                action: 'swpanel_ai_get_headers',
            },
            success: function(response) {
                if (response.success) {
                    $('#loading').hide();
                    $('#style-form').show();
                    $('#load-error').hide();
                } else {
                    $('#loading').hide();
                    $('#load-error').show();
		            $('#load-error').css('display', 'flex');
                    $('#message-error').text(response.data.message);
                    $('#retry-load').text(swpanel_ai_data.retry_text);
                }
            },
            error: function(response) {
                $('#retry-load').text(swpanel_ai_data.retry_text);
                $('#loading').hide();
                $('#load-error').show();
		        $('#load-error').css('display', 'flex');
                $('#message-error').text(response.statusText);
            }
        });
    }
    if (swpanel_ai_data.run_headers_task == 1) {
        if (swpanel_ai_data.back_page == 'swpanel_ai_template') {
            $('#style-form').show();
        } else {
            loadHeadersData();
        }
    } else {
        if (swpanel_ai_style_data.variations && swpanel_ai_style_data.variations.length) {
            $('#style-form').show();
        } else {
            $('#style-form').hide();
            $('#loading').hide();
            $('#load-error').show().css('display', 'flex');
            $('#message-error').text(swpanel_ai_style_data.message_error || '');
            $('#retry-load').hide();
        }
    }
    $('#retry-load').on('click', function() {
        loadHeadersData();
    });
});


document.addEventListener('DOMContentLoaded', function () {
    const continueButton = document.getElementById('continue-button');
    const form = document.querySelector('form');
    const container = document.getElementById('style-container');
    const variations = swpanel_ai_style_data.variations;
    const selected = JSON.stringify(swpanel_ai_style_data.selected_variation);

    const checkSelection = () => {
        const styleSelected = form.querySelector('input[name="site_style"]:checked');
        if (continueButton){
            continueButton.disabled = !styleSelected;
        }
    };

    variations.forEach((variation, index) => {
        const title = variation.title?.rendered || variation.title || 'Untitled';
        const jsonValue = JSON.stringify(variation);
        const isChecked = selected === jsonValue;

        const wrapper = document.createElement('label');
        wrapper.className = 'style-card';

        const radio = document.createElement('input');
        radio.type = 'radio';
        radio.name = 'site_style';
        radio.value = jsonValue;
        radio.className = 'site_style';
        if (isChecked) {
            radio.checked = true;
            wrapper.classList.add('selected');
            checkSelection();
        }
        
        radio.addEventListener('click', function() {
            document.querySelectorAll('.style-card').forEach(c => c.classList.remove('selected'));
            wrapper.classList.add('selected');
            radio.checked = true;
            checkSelection();
        });

        const heading = document.createElement('div');
        heading.textContent = title;

        const img = document.createElement('img');
        img.src = `${swpanel_ai_data.pluginUrl}../admin/assets/img/${index}.PNG`;
        img.alt = title;

        wrapper.appendChild(radio);
        wrapper.appendChild(img);
        wrapper.appendChild(heading);
        container.appendChild(wrapper);
    });

    checkSelection();
});
