(function(){

  var s = document.createElement("script");

  s.src = "https://cdn.jsdelivr.net/npm/canvas-confetti@1.5.1/dist/confetti.browser.min.js";

  s.async = true;

  document.head.appendChild(s);

})();

jQuery(document).ready(function($){

  // Append the custom modal if it doesn't exist

  if ($('#customConfirmModal').length === 0) {

    $('body').append(`

      <div id="customConfirmModal" style="display:none; position: fixed; top:0; left:0; width: 100%; height:100%; background: rgba(0,0,0,0.5); z-index:10000;">

        <div style="position: relative; width:300px; margin: 20% auto; background: white; padding:20px; border-radius: 5px; text-align: center;">

          <p id="customConfirmMessage"></p>

          <button id="customConfirmYes" class="button button-primary">Yes</button>

          <button id="customConfirmNo" class="button">No</button>

        </div>

      </div>

    `);

  }

  

  // Function to show the custom confirmation modal

  function customConfirm(message, callback) {

    $('#customConfirmMessage').text(message);

    $('#customConfirmModal').show();

    $('#customConfirmYes').off('click').on('click', function(){

         $('#customConfirmModal').hide();

         callback(true);

    });

    $('#customConfirmNo').off('click').on('click', function(){

         $('#customConfirmModal').hide();

         callback(false);

    });

  }

  // Global variables for cache warming worker

  let worker, processing = false, activeBatches = 0;

  const statusDiv = $('#cache_warming_status');

  // Function to start the cache warming worker

  function startWorker(){

    if(typeof Worker !== "undefined"){

      let workerCode = `

        self.addEventListener("message", async function(event){

          const {ajaxUrl, nonce, batchSize, parallelRequests} = event.data;

          let offset = 0, totalProcessed = 0, totalUrls = 0, processing = true, activeBatches = 0;

          self.postMessage({type:"starting"});

          try {

            let initialResponse = await fetch(ajaxUrl, {

              method:"POST",

              headers: {"Content-Type": "application/x-www-form-urlencoded"},

              body: new URLSearchParams({action:"warm_cache_ajax", nonce:nonce, offset:offset, limit:batchSize})

            });

            let initialData = await initialResponse.json();

            totalUrls = (initialData.success && initialData.data.total) ? initialData.data.total : 0;

            let initialProcessed = (initialData.success && initialData.data.urls.length > 0) ? initialData.data.urls.length : 0;

            totalProcessed += initialProcessed;

            offset += batchSize;

          } catch(error) {}

          async function fetchBatch(batchOffset){

            activeBatches++;

            try {

              let response = await fetch(ajaxUrl, {

                method:"POST",

                headers: {"Content-Type": "application/x-www-form-urlencoded"},

                body: new URLSearchParams({action:"warm_cache_ajax", nonce:nonce, offset:batchOffset, limit:batchSize})

              });

              let data = await response.json();

              let urlsProcessed = (data.success && data.data.urls.length > 0) ? data.data.urls.length : 0;

              totalProcessed += urlsProcessed;

              return urlsProcessed;

            } catch(error){ 

              return 0;

            } finally {

              activeBatches--;

            }

          }

          async function processParallelBatches(){

            while(processing){

              let promises = [];

              for(let i = 0; i < parallelRequests; i++){

                promises.push(fetchBatch(offset + i * batchSize));

              }

              let results = await Promise.all(promises);

              let batchSum = results.reduce((sum, count) => sum + count, 0);

              offset += batchSize * parallelRequests;

              if(batchSum === 0 || totalProcessed >= totalUrls){

                processing = false;

                self.postMessage({type:"done", totalProcessed});

                self.close();

              }

            }

          }

          processParallelBatches();

        });

      `;

      let blob = new Blob([workerCode], {type:"application/javascript"});

      let workerURL = URL.createObjectURL(blob);

      worker = new Worker(workerURL);

      worker.postMessage({

        ajaxUrl: cacheMeBabyAjax.ajaxurl,

        nonce: cacheMeBabyAjax.nonce,

        batchSize: 10,

        parallelRequests: 3

      });

      worker.onmessage = function(event){

        if(event.data.type === "starting"){

          statusDiv.html(

            '<style>div#hide-during_clear {display: none;}</style>' +

            '<p style="line-height:1.0;font-size:45px; color:#222; text-align:center;"><b>Cache warming in progress!</b><br>' +

            '<span style="font-size:23px;">Please stay on this page until it completes.</span></p><br>' +

            '<img src="'+cacheMeBabyAjax.loadingGif+'" alt="Loading..." class="spinner-img"><br>'

          );

        } else if(event.data.type === "done"){

          processing = false;

statusDiv.html(

  '<p style="line-height:1.0;margin-bottom: 0px;font-size:45px; color:#222; text-align:center;"><b>&#127881; Cache fully warmed!</b></p>' +

  '<p style="font-size:18px; text-align:center;"><b>URLs warmed –</b> ' +

  '<span style="background: #00D78B; color: #fff; border: 0px;" class="cache-me-baby-count">' +

    event.data.totalProcessed +

  '</span></p>'

);

          //setTimeout(function(){ statusDiv.fadeOut("slow"); }, 3000);

          confetti({particleCount:150, spread:100, origin:{y:0.6}});

        }

      };

      worker.onerror = function(){

        statusDiv.append('<p style="color:red;">&#10060; Error occurred while warming the cache.</p>');

        if(worker){ worker.terminate(); worker = null; }

        processing = false;

      };

    } else {

      statusDiv.append('<p style="color:red;">&#10060; Your browser does not support Web Workers.</p>');

    }

  }

  

  // Warm cache button click handler with custom modal confirmation

  $('#warm_cache_ajax').off('click').on('click', function(e){

    e.preventDefault();

    customConfirm("Are you sure you want to warmup cache?", function(confirmed){

        if(confirmed){

            if(processing) return;

            processing = true;

            // Show status for Cloudflare purge

            statusDiv.show().html(

           '<style>div#hide-during_clear {display: none;}</style>' +

           '<p style="line-height:1.0;font-size:45px; color:#222; text-align:center;"><b>Clearing CloudFlare Cache...</b><br>' +

           '<span style="font-size:23px;">Please stay on this page until it completes.</span></p><br>' +

           '<img src="'+cacheMeBabyAjax.loadingGif+'" alt="Loading..." class="spinner-img"><br>'

         );

            // First, purge Cloudflare cache

            $.post(cacheMeBabyAjax.ajaxurl, {

                action:'purge_cloudflare_cache',

                nonce: cacheMeBabyAjax.nonce

            }, function(response){

                if(response.success){

                    // Cloudflare purge successful. Update status and then start cache warming.

                    statusDiv.html(

                        '<p style="font-size:45px; color:#222; text-align:center;"><b>&#127881; CloudFlare cache cleared!</b></p>' +

                        '<br><p style="font-size:45px; color:#222; text-align:center;"><b>Starting cache warm-up...</b></p><br>' +

                        '<img src="'+cacheMeBabyAjax.loadingGif+'" alt="Loading..." class="spinner-img"><br>'

                    );

                    startWorker();

                } else {

                    // Purge failed; display error and reset processing flag.

                    statusDiv.html('<p style="font-size:45px; color:red; text-align:center;"><b>&#10060; Error purging CloudFlare cache: '+response.data+'</b></p>');

                    processing = false;

                }

            }).fail(function(xhr, status, error){

                statusDiv.html('<p style="font-size:45px; color:red; text-align:center;"><b>&#10060; AJAX Error: '+error+'</b></p>');

                processing = false;

            });

        }

    });

});

  // Cloudflare button click handler with custom modal confirmation

  $('#warm_cache_cloudflare').off('click').on('click', function(e){

    e.preventDefault();

    customConfirm("Are you sure you want to clear Cloudflare cache?", function(confirmed){

      if(confirmed){

         statusDiv.show().html(

           '<style>div#hide-during_clear {display: none;}</style>' +

           '<p style="line-height:1.0;font-size:45px; color:#222; text-align:center;"><b>Clearing CloudFlare Cache...</b><br>' +

           '<span style="font-size:23px;">Please stay on this page until it completes.</span></p><br>' +

           '<img src="'+cacheMeBabyAjax.loadingGif+'" alt="Loading..." class="spinner-img"><br>'

         );

         $.post(cacheMeBabyAjax.ajaxurl, {action:'purge_cloudflare_cache', nonce:cacheMeBabyAjax.nonce}, function(response){

           if(response.success){

             statusDiv.html('<p style="font-size:45px; color:#222; text-align:center;"><b>&#127881; CloudFlare cache cleared!</b></p><br>');

             setTimeout(function(){ statusDiv.fadeOut("slow"); }, 3000);

             confetti({particleCount:150, spread:100, origin:{y:0.6}});

           } else {

             statusDiv.html('<p style="font-size:45px; color:red; text-align:center;"><b>&#10060; Error: '+response.data+'</b></p>');

           }

         });

      }

    });

  });

  

jQuery(document).ready(function($) {

    const $testButton = $('#test_cloudflare_connection');

    $testButton.on('click', function(e) {

        e.preventDefault();

        // Grab the values the user typed in (not saved yet)

        const zoneID   = $('#cache_me_baby_cloudflare_zone_id').val();

        const apiToken = $('#cache_me_baby_cloudflare_api_token').val();

        const email    = $('#cache_me_baby_cloudflare_email').val();

        // Switch to "testing" state

        $testButton

            .removeClass('test-connection-button connection-success-button connection-failed-button')

            .addClass('testing-connection-button')

            .prop('disabled', true)

            .text('Testing Connection...');

        // Send Ajax request with typed credentials

        $.post(cacheMeBabyAjax.ajaxurl, {

            action:    'test_cloudflare_connection',

            nonce:     cacheMeBabyAjax.nonce,

            zone_id:   zoneID,

            api_token: apiToken,

            email:     email

        })

        .done(function(response) {

            if (response.success) {

                // If test is successful

                $testButton

                    .removeClass('testing-connection-button')

                    .addClass('connection-success-button')

                    .text('Connection Successful!');

                

                // If you also want to revert the button after success, add a setTimeout here:

                setTimeout(function() {

                    $testButton

                        .removeClass('connection-success-button')

                        .addClass('test-connection-button')

                        .prop('disabled', false)

                        .text('Test Connection Again');

                }, 3000);

                

            } else {

                // If Cloudflare returned an error

                $testButton

                    .removeClass('testing-connection-button')

                    .addClass('connection-failed-button')

                    .text('Connection Failed!');

                // Revert button after 3 seconds

                setTimeout(function() {

                    $testButton

                        .removeClass('connection-failed-button')

                        .addClass('test-connection-button')

                        .prop('disabled', false)

                        .text('Test Connection');

                }, 3000);

            }

        })

        .fail(function() {

            // Network/transport error

            $testButton

                .removeClass('testing-connection-button')

                .addClass('connection-failed-button')

                .text('Connection Failed!');

            // Revert button after 3 seconds

            setTimeout(function() {

                $testButton

                    .removeClass('connection-failed-button')

                    .addClass('test-connection-button')

                    .prop('disabled', false)

                    .text('Test Connection');

            }, 3000);

        });

    });

});

  // Confirm before leaving while processing (using built-in confirm)

  $(document).on('click','a', function(e){

    if(processing){

      e.preventDefault();

      let customMessage = "Cache warming is still in progress.\nAre you sure you want to leave?\nThis process will be interrupted.";

      if(confirm(customMessage)){

        processing = false;

        if(worker){ worker.terminate(); worker = null; }

        window.location = $(this).attr('href');

      }

    }

  });

});