// payflex-widget-2.0.0.js
(function () {
  "use strict";
  var $;
  var widgetInitialized = false;
  var currentAmount;
  var payType;

  var calculator = function ($script) {
    if (
      typeof $script.attr("src") !== "undefined" &&
      $("#payflexCalculatorWidget").length === 0 && !widgetInitialized
    ) {
      var widgetHtml = `
            <div id="payflexCalculatorWidget" style="font-family: 'Open Sans', sans-serif;" >
                <div class="payflex-widget-wrapper">
                <div class="payflex-w-full">
                    <div class="payflex-flex payflex-flex-row">
                        <div class="payflex-flex payflex-self-center">
                            <img id="payflex-logo" src="https://widgets.payflex.co.za/assets/widget-payflex.svg" alt="Payflex Logo" class="payflex-relative payflex-image-responsive">
                        </div>
                        <div class="payflex-text-center payflex-text-left payflex-flex-grow payflex-ml-4">
                            <p class="payflex-text-title payflex-font-extrabold payflex-text-left payflex-secondary-color">Buy now. Pay later. 0% interest.
                            </p>
                            <div id="payin-container" class="payflex-text-left">
                                <div class="">
                                    <p id="payflex-primary-color-inverse" class="payflex-text-subtitle payflex-text-left payflex-primary-color payflex-font-semibold">Choose your payment plan, and pay from as little as <br class="payflex-break" /><span class="payflex-font-extrabold" id="pay-in-amount">R1000</span> today.<br class="payflex-break" />
                                    <a href="#" class="payflex-text-subtitle payflex-secondary-color payflex-font-bold payflex-underline payflex-learn-more-both">Learn more</a></p>
                                    
                                </div>
                                
                            </div>
                          
                        </div>
                    </div>
                </div>
            </div>
        
            
        </div>
        `;
        var modalHtml = `
            <!-- The Modal -->
            <div id="payflex-modal" class="payflex-modal none" style="font-family: 'Open Sans', sans-serif;">
                <div class="payflex-modal-content payflex-bg-custom-primary payflex-rounded-3xl payflex-shadow-lg">
                    <div
                        class="payflex-bg-custom-primary payflex-flex payflex-flex-col payflex-items-center payflex-justify-center payflex-pt-4 payflex-pr-6 payflex-pl-6 payflex-pb-6 payflex-rounded-3xl payflex-shadow-lg">
                        <button class="payflex-flex payflex-self-end payflex-button-close">
                            <img class="payflex-w-6 payflex-h-6" src="https://widgets.payflex.co.za/assets/cancel-icon.png" />
                        </button>
                        <div class="payflex-w-full payflex-pt-2 payflex-flex payflex-justify-between payflex-items-center">
                            <img class="payflex-image-responsive payflex-dialog-img" src="https://widgets.payflex.co.za/assets/payflex.png" />
                            <div class="payflex-text-container payflex-mr-12">
                                <span class="payflex-text-primary payflex-md\:text-lg payflex-font-bold">NO INTEREST. NO FEES. </span><br />
                                <span class="payflex-secondary-color payflex-md\:text-lg payflex-font-bold"><span class="payflex-italic">THIS</span> IS
                                    SHOPPING.</span>
                            </div>
                        </div>
                        <div class="payflex-w-full payflex-h-px payflex-border-t payflex-border-primary payflex-my-6">&nbsp;</div>
        
                        <div class="payflex-left">
                          <div class="payflex-flex payflex-mb-4">
                            <div class="payflex-text-5xl payflex-font-bold payflex-text-left payflex-primary-color payflex-px-12">1</div>
                            <div class="payflex-text-left">
                              <div class="payflex-text-base payflex-sm\:text-lg payflex-md\:text-xl payflex-lg\:text-2xl payflex-font-bold payflex-text-left payflex-secondary-color">SELECT YOUR PAYMENT PLAN</div>
                              <p class="payflex-text-left payflex-text-base payflex-sm\:text-sm payflex-md\:text-md payflex-lg\:text-lg payflex-font-semibold payflex-primary-color">3 OR 4 INSTALMENTS</p>
                            </div>
                          </div>
                          <div class="payflex-flex payflex-mb-4">
                              <div class="payflex-text-5xl payflex-font-bold payflex-text-left payflex-primary-color payflex-px-12">2</div>
                              <div class="payflex-text-left">
                                  <div class="payflex-text-base payflex-sm\:text-lg payflex-md\:text-xl payflex-lg\:text-2xl payflex-font-bold payflex-secondary-color">PAY IN 3</div>
                                  <p class="payflex-primary-color payflex-font-semibold payflex-text-base payflex-sm\:text-sm payflex-md\:text-md payflex-lg\:text-lg">PAY OVER 3 PAYDAYS
                                  <br />INTEREST FREE</p>
                                  <p class="payflex-primary-color payflex-font-bold payflex-my-4">OR</p>
                                  <div class="payflex-text-base payflex-sm\:text-lg payflex-md\:text-xl payflex-lg\:text-2xl payflex-font-bold payflex-secondary-color">PAY IN 4</div>
                                  <p class="payflex-primary-color payflex-font-semibold payflex-text-base payflex-sm\:text-sm payflex-md\:text-md payflex-lg\:text-lg">PAY IN 4 INSTALMENTS OVER 6 WEEKS
                                  <br />INTEREST FREE</p>
                                  
                              </div>
                          </div>
                          <div class="payflex-flex payflex-mb-4">
                              <div class="payflex-text-5xl payflex-font-bold payflex-text-left payflex-primary-color payflex-px-12">3</div>
                              <div class="payflex-text-left">
                                <div class="payflex-text-base payflex-sm\:text-lg payflex-md\:text-xl payflex-lg\:text-2xl payflex-font-bold payflex-text-left payflex-secondary-color">FLEX! GET APPROVED</div>
                                <p class="payflex-text-left payflex-primary-color payflex-font-semibold payflex-text-base payflex-sm\:text-sm payflex-md\:text-md payflex-lg\:text-lg">PAY YOUR FIRST INSTALLMENT TODAY AND GET <br />WHAT YOU WANT NOW</p>
                              </div>
                          </div>
                        </div>
        
                        <div class="payflex-w-full payflex-h-px payflex-border-t payflex-border-primary payflex-mb-6">&nbsp;</div>
                        <div class="payflex-w-full payflex-flex payflex-flex-col payflex-sm\:flex-row payflex-justify-between payflex-md\:items-center payflex-mb-6">
                            <div class="payflex-md\:w-1\/3 payflex-flex payflex-md\:items-center payflex-mb-4 payflex-md\:mb-0">
                                <img class="payflex-w-5 payflex-h-5 payflex-mr-2" src="https://widgets.payflex.co.za/assets/check.svg" />
                                <span class="payflex-text-primary payflex-text-xs payflex-font-bold">You must be over 18 years old</span>
                            </div>
                            <div class="payflex-md\:w-1\/3 payflex-flex payflex-md\:items-center payflex-mb-4 payflex-md\:mb-0">
                                <img class="payflex-w-5 payflex-h-5 payflex-mr-2" src="https://widgets.payflex.co.za/assets/check.svg" />
                                <span class="payflex-text-primary payflex-text-xs payflex-font-bold">You must have a valid South African ID</span>
                            </div>
                            <div class="payflex-md\:w-1\/3 payflex-flex payflex-md\:items-center">
                                <img class="payflex-w-5 payflex-h-5 payflex-mr-2" src="https://widgets.payflex.co.za/assets/check.svg" />
                                <span class="payflex-text-primary payflex-text-xs payflex-font-bold">You must have a debit/credit card issued by
                                    Mastercard, Visa or Amex</span>
                            </div>
                        </div>
                        <div class="payflex-w-full payflex-h-px payflex-border-t payflex-border-primary payflex-mb-6">&nbsp;</div>
                        <div class="payflex-text-center">
                            <span class="payflex-secondary-color payflex-text-xs payflex-font-bold">Still want more information?</span>&nbsp;
                            <a href="http://www.payflex.co.za/#howitworks/" target="_blank" class="payflex-anchor-link payflex-text-primary payflex-text-xs payflex-font-bold payflex-underline">Click here</a>
                        </div>
                    </div>
                </div>
            </div>
        `;
      var $widget = $(widgetHtml);
      $script.after($widget);

      // Append modal to the body
      $("body").append(modalHtml);

      // Event handling using jQuery

      $widget.on("click", ".payflex-learn-more-both", function (event) {
        event.preventDefault();
        var modal = $("#payflex-modal");
        modal.css("display", "flex");
      });

      $(document).on("click", ".payflex-button-close", function () {
        var modal = $("#payflex-modal");
        modal.css("display", "none");
      });

      $(document).on("click", function (event) {
        if ($(event.target).is($("#payflex-modal"))) {
          var modal = $("#payflex-modal");
          modal.css("display", "none");
        }
      });

      $(document).ready(function() {
        function updatePayflexBreakDisplay() {
            var containerWidth = $('.payflex-widget-wrapper').width();
            if (containerWidth <= 768) {
                $('.payflex-break').hide();
            } else {
                $('.payflex-break').show();
            }
        }

        // Initial check
        updatePayflexBreakDisplay();

        // Update on window resize
        $(window).resize(updatePayflexBreakDisplay);
    });

      // Initial amount parsing and calculations
      currentAmount = parseAmount(getParam($script.attr("src"), "amount"));
      payType = getParam($script.attr("src"), "pay_type");
      updateInstallments(currentAmount);

      var themeType = getParam($script.attr("src"), "theme");
      if(themeType != undefined && themeType != ''){
        $("#payflex-primary-color-inverse").addClass('payflex-primary-color-inverse');
      }

      var logoType = getParam($script.attr("src"), "logo_type");

      if(logoType != undefined && logoType != ""){
        //Logo type specified
        if(logoType == 'navy'){
          $("#payflex-logo").attr('src', 'https://widgets.payflex.co.za/assets/widget-payflex-navy.svg');
        } else {
          $("#payflex-logo").attr('src', 'https://widgets.payflex.co.za/assets/widget-payflex.svg');
        }
      }
      widgetInitialized = true;
    }
  };

  function parseAmount(value) {
    if (!value) {
      return 0;
    }

    if(typeof value == 'string') {
      value = value.replace("R", "").replace(",", "");
    } else {
      value = value.toString();
    }
    
    var amount = parseFloat(value).toFixed(2);

    if (isNaN(amount) || amount < 0) {
      return 0;
    }
    return amount;
  }

  function updateInstallments(amount, type = undefined) {
    var installmentAmount3 = getInstallmentAmount(amount, 3);
    var installmentAmount4 = getInstallmentAmount(amount, 4);

    if(type) {
      payType = type;
    }

    // Update the UI with the new installment amounts
    // var payType = getParam($script.attr("src"), "pay_type");
    if (payType == 3) {
      $("#pay-in-amount").html(installmentAmount3);
    } else {
      $("#pay-in-amount").html(installmentAmount4);
    }
  }


  window.PayflexWidget = {
    update: function (newAmount, type = 4) {
      // Parse the new amount
      currentAmount = parseAmount(newAmount);
      // Recalculate and update the installments
      updateInstallments(currentAmount, type);
    },
  };


  function getInstallmentAmount(value, payType = 4) {
    value = +value;
    if (isNaN(value) || value < 0) {
      return 0;
    }
    var result = Math.floor((value * 100) / payType) / 100;
    return endsWithZeroCents(result)
      ? "R" + addThousandsSeparator(result.toFixed(0))
      : "R" + addThousandsSeparator(result.toFixed(2));
  }

  function endsWithZeroCents(value) {
    var fixed = value.toFixed(2);
    return fixed.lastIndexOf(".00") != -1;
  }

  function addThousandsSeparator(number) {
    let numStr = number.toString();
    let parts = numStr.split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
  }

  function getParam(url, name) {
    var results = new RegExp("[?&]" + name + "=([^&#]*)").exec(url);
    return results && results.length > 1 ? results[1] : "";
  }


  // Function to load external CSS
  function loadCSS(url) {
    return new Promise((resolve, reject) => {
      var link = document.createElement("link");
      link.rel = "stylesheet";
      link.href = url;
      document.head.appendChild(link);

      link.onload = () => resolve();
      link.onerror = () => reject(`Failed to load CSS: ${url}`);
    });
  }

  // Function to load external script
  function loadScript(url) {
    return new Promise((resolve, reject) => {
      var script = document.createElement("script");
      script.src = url;
      document.body.appendChild(script);

      script.onload = () => resolve();
      script.onerror = () => reject(`Failed to load script: ${url}`);
    });
  }

  // URLs for the external files
  // const cssUrl = "styles/output.css"; // Change this to your CSS file path
  const cssUrl = "https://widgets.payflex.co.za/styles/output.css"; // Change this to your CSS file path
  const scriptUrl = "https://widgets.payflex.co.za/ppQuery-3.2.1.js"; // Change this to your script URL

  // Load both CSS and script in parallel
  Promise.all([loadCSS(cssUrl), loadScript(scriptUrl)])
    .then(() => {
      console.log("Both CSS and script files loaded.");
      $ = ppQuery;
      var $script = $("script[src*='payflex-widget-']");
      if (typeof $script.attr("src") !== "undefined" && $("#payflexCalculatorWidget").length === 0 && !widgetInitialized) {
        var type = getParam($script.attr("src"), "type") || "calculator";
        var fn = eval(type);
        fn($script);
        $script.remove();
      }
    })
    .catch((error) => {
      console.error(error);
    });
})();
