(function($) {
  "use strict";

  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);
  const url = new URL(window.location.href);
  const pathname = url.pathname || "unknown";
  globalThis.rudderSdkLoaded = false;


  console.time('Rudderstak Load Time');
  window.RudderSnippetVersion = "3.0.14";
  var identifier = "rudderanalytics";
  if (!window[identifier]) {
    window[identifier] = [];
  }
  var rudderanalytics = window[identifier];
  if (Array.isArray(rudderanalytics)) {
    if (rudderanalytics.snippetExecuted === true && window.console && console.error) {
      console.error("RudderStack JavaScript SDK snippet included more than once.");
    } else {
      rudderanalytics.snippetExecuted = true;
      window.rudderAnalyticsBuildType = "legacy";
      var sdkBaseUrl = "https://cdn.rudderlabs.com/v3";
      var sdkName = "rsa.min.js";
      var scriptLoadingMode = "async";
      var methods = [ "setDefaultInstanceKey", "load", "ready", "page", "track", "identify", "alias", "group", "reset", "setAnonymousId", "startSession", "endSession", "consent" ];
      for (var i = 0; i < methods.length; i++) {
        var method = methods[i];
        rudderanalytics[method] = function(methodName) {
          return function() {
            if (Array.isArray(window[identifier])) {
              rudderanalytics.push([ methodName ].concat(Array.prototype.slice.call(arguments)));
            } else {
              var _methodName;
              (_methodName = window[identifier][methodName]) === null || _methodName === void 0 || _methodName.apply(window[identifier], arguments);
            }
          };
        }(method);
      }
      try {
        new Function('return import("")');
        window.rudderAnalyticsBuildType = "modern";
      } catch (e) {}
      var head = document.head || document.getElementsByTagName("head")[0];
      var body = document.body || document.getElementsByTagName("body")[0];
      window.rudderAnalyticsAddScript = function(url, extraAttributeKey, extraAttributeVal) {
        var scriptTag = document.createElement("script");
        scriptTag.src = url;
        scriptTag.setAttribute("data-loader", "RS_JS_SDK");
        if (extraAttributeKey && extraAttributeVal) {
          scriptTag.setAttribute(extraAttributeKey, extraAttributeVal);
        }
        if (scriptLoadingMode === "async") {
          scriptTag.async = true;
        } else if (scriptLoadingMode === "defer") {
          scriptTag.defer = true;
        }
        if (head) {
          head.insertBefore(scriptTag, head.firstChild);
        } else {
          body.insertBefore(scriptTag, body.firstChild);
        }
      };
      window.rudderAnalyticsMount = function() {
        if (typeof globalThis === "undefined") {
          Object.defineProperty(Object.prototype, "__globalThis_magic__", {
            get: function get() {
              return this;
            },
            configurable: true
          });
          __globalThis_magic__.globalThis = __globalThis_magic__;
          delete Object.prototype.__globalThis_magic__;
        }
        window.rudderAnalyticsAddScript("".concat(sdkBaseUrl, "/").concat(window.rudderAnalyticsBuildType, "/").concat(sdkName), "data-rsa-write-key", "2GbJqO8EiCnEGhkGmbEacrOhpMo");
      };
      if (typeof Promise === "undefined" || typeof globalThis === "undefined") {
        window.rudderAnalyticsAddScript("https://polyfill-fastly.io/v3/polyfill.min.js?version=3.111.0&features=Symbol%2CPromise&callback=rudderAnalyticsMount");
      } else {
        window.rudderAnalyticsMount();
      }
      var loadOptions = {
        onLoaded: function (rudderanalytics) {
          console.timeEnd('Rudderstak Load Time');
          console.log('Before Setting Anon ID - 1',  window.rudderanalytics?.getAnonymousId?.() ?? "")
            
          if(urlParams.get('anonymous_id')){
            window.rudderanalytics.setAnonymousId(urlParams.get('anonymous_id'));   
          }
          
          console.log('After Setting Anon ID - 1',  window.rudderanalytics?.getAnonymousId?.() ?? "")         
         

          globalThis.rudderSdkLoaded = true;
          setAnonIdInGravityForm(rudderanalytics);
          triggerRSAEvents(rudderanalytics);
        },
        sendAdblockPage: true,
        sendAdblockPageOptions: {
          integrations: {
            All: false,
              Amplitude: true
          }
        },
        storage: {
          encryption: {
            version: "legacy"
          }
        },
        logLevel: 'DEBUG'
      };
      rudderanalytics.load("2GbJqO8EiCnEGhkGmbEacrOhpMo", "https://homemadetepdo.dataplane.rudderstack.com", loadOptions);
    }
  }

  function triggerRSAEvents(r){
    const rudderAnonymousId = window.rudderanalytics?.getAnonymousId?.() ?? "";
    
    // Page load event
    window.rudderanalytics.page();

    /*
    * Trigger on every page view 
    * Event No = 
    */
    window.rudderanalytics.identify(
      "",
      {
      },
      {
        page: {
          path: window.location.pathname,
          referrer: document.referrer,
          search: document.title,
          title: document.title,
          url: window.location.href
        }
      },
      () => {
        // console.log("identify call - Trigger on every page view");
      }
    );

    if ($('body').find('#hmba_checkout_form').length > 0) {
      if (pathname == '/co/unlock' || pathname == '/co/more-recipes') {
        
        window.rudderanalytics.track("checkout_started", {
          content_type: "paywall",
          content_route: window.location.pathname,
          context_app_name: 'website'
        });

        window.rudderanalytics.identify(
          "",
          {
            email: urlParams.get('email') || "",
          },
          {
            page: {
              path: window.location.pathname,
              referrer: document.referrer,
              search: document.title,
              title: document.title,
              url: window.location.href
            }
          },
          () => {
            // console.log("identify call");
          }
        );
      }
    }

    $(".rs_trigger_view_event").find('a').click(function (e) {
      e.preventDefault();
      window.rudderanalytics.track("view", {
        context: "landing_page_button_click",
        context_app_name: 'website'
      });

      let u = new URL($(this).attr('href'));
      u.searchParams.append('rudder_web_anonymous_id', rudderAnonymousId);
      window.location.href = u;
      return true;
    });

    $(".rs_trigger_install_app_btn_event").find('a').click(function (e) {
      e.preventDefault();

      window.rudderanalytics.track("view", {
        context: "install_app_page_button_click",
        context_app_name: 'website'
      });

      let u = new URL($(this).attr('href'));
      window.location.href = u;
      return true;
    });

    /**
     * Usage: This function is responsible for appending a 'web_anon_id' query parameter to the URL of anchor (<a>) elements.
     * It processes elements with the class 'hmba_append_rudder_web_anon_id' or their parent elements that contain <a> tags.
     * To use this function, simply add the class 'hmba_append_rudder_web_anon_id' to the <a> tag or its parent element.
     */
    $(".hmba_append_rudder_web_anon_id a, .hmba_append_rudder_web_anon_id").each(function(index){
      if (this.tagName.toLowerCase() !== 'a') {
          return;
      }
      let link = $(this).attr('href');
      if (!link) { return; }
      let urlObj = new URL(link);
      urlObj.searchParams.set('rudder_web_anonymous_id', rudderAnonymousId); // This will add or update the query parameter
      $(this).attr('href',urlObj.toString());
    });
  }

  function setAnonIdInGravityForm(r){
    const rudderAnonymousId = window.rudderanalytics?.getAnonymousId?.() ?? "";
    // Active Campaign Add rudder_web_anonymous_id 
    if (jQuery("form._form_44").length > 0) {
      jQuery("form._form_44").find('input[name="field[142]"]').val(rudderAnonymousId);
    }

    // Gravity form Add rudder_web_anonymous_id
    if (jQuery("#gform_3").length > 0) {
      jQuery("#gform_3").find('#input_3_5').val(rudderAnonymousId);
    }

    if (jQuery("#gform_4").length > 0) {
      jQuery("#gform_4").find('#input_4_5').val(rudderAnonymousId);
    }

    if (jQuery("#gform_5").length > 0) {
      jQuery("#gform_5").find('#input_5_5').val(rudderAnonymousId);
    }

    if (jQuery("#gform_54").length > 0) {
      jQuery("#gform_54").find('#input_54_5').val(rudderAnonymousId);
    }

    if (jQuery("#gform_7").length > 0) {
      jQuery("#gform_7").find('#input_7_5').val(rudderAnonymousId);
    }

    if (jQuery("#gform_23").length > 0) {
      jQuery("#gform_23").find('#input_23_5').val(rudderAnonymousId);
    }
  }


})(jQuery);