document.addEventListener("DOMContentLoaded", () => {
  const cards = document.querySelectorAll(".iframe-card");
  const preview = document.getElementById("iframe-preview");

  cards.forEach(card => {
    const input = card.querySelector("input[type=radio]");
    const iframe = card.querySelector("iframe");

    card.addEventListener("click", () => {
      preview.src = iframe.src;

      cards.forEach(c => c.classList.remove("selected"));
      card.classList.add("selected");

      input.checked = true;
    });
  });
  
  const firstCard = cards[0];
  if (firstCard) {
    const firstInput = firstCard.querySelector("input[type=radio]");
    const firstIframe = firstCard.querySelector("iframe");

    if (!document.querySelector(".iframe-card input[type=radio]:checked")) {
      firstCard.classList.add("selected");
      firstInput.checked = true;
      preview.src = firstIframe.src;
    }
  }
  
  document.querySelectorAll(".loading-iframe-container").forEach(wrapper => {
      const iframe = wrapper.querySelector("iframe");
      const loader = wrapper.querySelector(".loading-iframe");

      iframe.addEventListener("load", () => {
          loader.style.opacity = "0";
          setTimeout(() => loader.style.display = "none", 300);
      });
  });
  
    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='22%' 
                centerLabelToolText='22% ${__('Completed', 'swpanel-ai')}' centerLabelFontSize='34'
                showPlotBorder='1' enableSmartLabels='1' useEllipsesWhenOverflow='1'
                doughnutRadius='75%' startingAngle='270' manageLabelOverflow='1'
                centerLabelBold='1' animateClockwise='0'
            >
                <set value='78' label='${__('Pending', 'swpanel-ai')}' toolText='${__('Pending', 'swpanel-ai')}' color='#4DC2F7' borderColor='#4DC2F7'/>
                <set value='22' 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", "22%");
    });
});


jQuery(document).ready(function($) {
    function createTemplatePages() {
        $('#loading').show();
		    $('#loading').css('display', 'flex');
        $('#load-error').hide();

        $.ajax({
            url: swpanel_ai_data.ajax_url,
            type: 'POST',
            data: {
                action: 'swpanel_ai_create_template_pages',
            },
            success: function(response) {
                if (response.success) {
                    $('#loading').hide();
                    
                    let container = document.getElementById('iframe-grid');
                    let preview = document.getElementById('iframe-preview');
                    container.innerHTML = '';
                    response.data.forEach((item, index) => {
                      let label = document.createElement('label');
                      label.className = 'iframe-card';

                      label.innerHTML = `
                        <input type="radio" 
                          name="preview_id" 
                          value="${item.id}" 
                          ${index === 0 ? 'checked' : ''}
                          required>
                        <div class="loading-iframe-container">
                          <div class="loading-iframe">
                            <img src="${swpanel_ai_data.pluginUrl}../admin/assets/img/07-thin.svg" alt="loading iframe">
                          </div>
                          <iframe scrolling="no" src="${item.url}"></iframe>
                        </div>
                      `;

                      const iframe = label.querySelector("iframe");
                      const loader = label.querySelector(".loading-iframe");

                      iframe.addEventListener("load", () => {
                        loader.style.opacity = "0";
                        setTimeout(() => loader.style.display = "none", 300);
                      });

                      label.addEventListener('click', () => {
                        const iframe = label.querySelector('iframe');
                        const input = label.querySelector('input[type=radio]');

                        preview.src = iframe.src;

                        container.querySelectorAll('.iframe-card').forEach(c => c.classList.remove('selected'));
                        label.classList.add('selected');

                        input.checked = true;
                      });

                      container.appendChild(label);
                    });

                    if (response.data.length > 0) {
                      preview.src = response.data[0].url;
                      container.querySelector('.iframe-card').classList.add('selected');
                    }
                    $('#template-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);
            }
        });
    }

    createTemplatePages();
    $('#retry-load').on('click', function() {
        createTemplatePages();
    });
});
