@tagadapay/plugin-sdk 3.1.25 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +1129 -1129
  2. package/build-cdn.js +499 -499
  3. package/dist/external-tracker.js +5 -5
  4. package/dist/external-tracker.min.js +2 -2
  5. package/dist/external-tracker.min.js.map +2 -2
  6. package/dist/react/config/payment.d.ts +2 -2
  7. package/dist/react/config/payment.js +5 -5
  8. package/dist/react/hooks/usePayment.d.ts +7 -0
  9. package/dist/react/hooks/usePayment.js +1 -0
  10. package/dist/react/providers/TagadaProvider.js +5 -5
  11. package/dist/tagada-react-sdk-minimal.min.js +2 -2
  12. package/dist/tagada-react-sdk-minimal.min.js.map +4 -4
  13. package/dist/tagada-react-sdk.js +1616 -1275
  14. package/dist/tagada-react-sdk.min.js +2 -2
  15. package/dist/tagada-react-sdk.min.js.map +4 -4
  16. package/dist/tagada-sdk.js +869 -27
  17. package/dist/tagada-sdk.min.js +2 -2
  18. package/dist/tagada-sdk.min.js.map +4 -4
  19. package/dist/v2/core/config/environment.d.ts +3 -3
  20. package/dist/v2/core/config/environment.js +7 -7
  21. package/dist/v2/core/funnelClient.d.ts +2 -0
  22. package/dist/v2/core/resources/funnel.d.ts +1 -1
  23. package/dist/v2/core/resources/geo.d.ts +50 -0
  24. package/dist/v2/core/resources/geo.js +35 -0
  25. package/dist/v2/core/resources/payments.d.ts +19 -1
  26. package/dist/v2/core/resources/payments.js +8 -0
  27. package/dist/v2/core/utils/previewModeIndicator.js +101 -101
  28. package/dist/v2/react/components/FunnelScriptInjector.js +167 -19
  29. package/dist/v2/react/components/StripeExpressButton.d.ts +8 -0
  30. package/dist/v2/react/components/StripeExpressButton.js +22 -1
  31. package/dist/v2/react/hooks/payment-actions/useNgeniusThreedsAction.d.ts +15 -0
  32. package/dist/v2/react/hooks/payment-actions/useNgeniusThreedsAction.js +166 -0
  33. package/dist/v2/react/hooks/payment-actions/usePaymentActionHandler.js +12 -0
  34. package/dist/v2/react/hooks/payment-processing/usePaymentProcessors.js +1 -0
  35. package/dist/v2/react/hooks/useISOData.js +25 -7
  36. package/dist/v2/react/hooks/usePaymentPolling.d.ts +1 -1
  37. package/dist/v2/react/providers/ExpressPaymentMethodsProvider.js +12 -4
  38. package/dist/v2/react/providers/TagadaProvider.js +5 -5
  39. package/dist/v2/standalone/apple-pay-service.d.ts +12 -0
  40. package/dist/v2/standalone/apple-pay-service.js +12 -0
  41. package/dist/v2/standalone/external-tracker.d.ts +1 -1
  42. package/dist/v2/standalone/google-pay-service.d.ts +9 -0
  43. package/dist/v2/standalone/google-pay-service.js +9 -0
  44. package/dist/v2/standalone/index.d.ts +8 -1
  45. package/dist/v2/standalone/index.js +7 -0
  46. package/dist/v2/standalone/payment-service.d.ts +18 -5
  47. package/dist/v2/standalone/payment-service.js +62 -9
  48. package/package.json +115 -114
@@ -1,5 +1,5 @@
1
1
  /**
2
- * TagadaPay External Tracker v3.1.25
2
+ * TagadaPay External Tracker v4.0.0
3
3
  * CDN Bundle - Standalone tracking for external pages (Debug Build)
4
4
  * @license MIT
5
5
  */
@@ -120,10 +120,10 @@ var TagadaTrackerBundle = (() => {
120
120
  }
121
121
  return "local";
122
122
  }
123
- if (hostname === "app.tagadapay.com" || hostname.includes("tagadapay.com") || hostname.includes("yourproductiondomain.com")) {
123
+ if (hostname.includes("tagada.io") || hostname.includes("tagadapay.com") || hostname.includes("yourproductiondomain.com")) {
124
124
  return "production";
125
125
  }
126
- if (hostname === "app.tagadapay.dev" || hostname.includes("tagadapay.dev") || hostname.includes("vercel.app") || hostname.includes("netlify.app") || hostname.includes("surge.sh") || hostname.includes("github.io") || hostname.includes("herokuapp.com") || hostname.includes("railway.app") || href.includes("?env=dev") || href.includes("?dev=true") || href.includes("#dev")) {
126
+ if (hostname.includes("tagada.dev") || hostname.includes("tagadapay.dev") || hostname.includes("vercel.app") || hostname.includes("netlify.app") || hostname.includes("surge.sh") || hostname.includes("github.io") || hostname.includes("herokuapp.com") || hostname.includes("railway.app") || href.includes("?env=dev") || href.includes("?dev=true") || href.includes("#dev")) {
127
127
  return "development";
128
128
  }
129
129
  console.warn("[SDK] Unknown domain: ".concat(hostname, ", defaulting to production"));
@@ -145,7 +145,7 @@ var TagadaTrackerBundle = (() => {
145
145
  "use strict";
146
146
  ENVIRONMENT_CONFIGS = {
147
147
  production: {
148
- baseUrl: "https://app.tagadapay.com",
148
+ baseUrl: "https://api.tagada.io",
149
149
  endpoints: {
150
150
  checkout: {
151
151
  sessionInit: "/api/v1/checkout/session/init",
@@ -163,7 +163,7 @@ var TagadaTrackerBundle = (() => {
163
163
  }
164
164
  },
165
165
  development: {
166
- baseUrl: "https://app.tagadapay.dev",
166
+ baseUrl: "https://api.tagada.dev",
167
167
  endpoints: {
168
168
  checkout: {
169
169
  sessionInit: "/api/v1/checkout/session/init",
@@ -1,9 +1,9 @@
1
1
  /**
2
- * TagadaPay External Tracker v3.1.25
2
+ * TagadaPay External Tracker v4.0.0
3
3
  * CDN Bundle - Standalone tracking for external pages
4
4
  * @license MIT
5
5
  */
6
- "use strict";var TagadaTrackerBundle=(()=>{var re=Object.defineProperty,Ct=Object.defineProperties,It=Object.getOwnPropertyDescriptor,wt=Object.getOwnPropertyDescriptors,vt=Object.getOwnPropertyNames,Fe=Object.getOwnPropertySymbols;var Ne=Object.prototype.hasOwnProperty,St=Object.prototype.propertyIsEnumerable;var De=(n,e,t)=>e in n?re(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,h=(n,e)=>{for(var t in e||(e={}))Ne.call(e,t)&&De(n,t,e[t]);if(Fe)for(var t of Fe(e))St.call(e,t)&&De(n,t,e[t]);return n},b=(n,e)=>Ct(n,wt(e));var N=(n,e)=>()=>(n&&(e=n(n=0)),e);var Te=(n,e)=>{for(var t in e)re(n,t,{get:e[t],enumerable:!0})},Tt=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vt(e))!Ne.call(n,o)&&o!==t&&re(n,o,{get:()=>e[o],enumerable:!(i=It(e,o))||i.enumerable});return n};var bt=n=>Tt(re({},"__esModule",{value:!0}),n);function Ue(n){var i;if(typeof document=="undefined")return null;let t="; ".concat(document.cookie).split("; ".concat(n,"="));return t.length===2&&((i=t.pop())==null?void 0:i.split(";").shift())||null}function Oe(n="local"){let e=Le[n];if(!e)return console.warn("Unknown environment: ".concat(n,". Falling back to local.")),{environment:"local",apiConfig:Le.local};let t=null;if(typeof window!="undefined"&&(t=new URLSearchParams(window.location.search).get("tagadaClientBaseUrl"),!t))try{t=localStorage.getItem("tgd_client_base_url")||Ue("tgd_client_base_url")}catch(o){}return t?(console.log("[SDK] Using custom API base URL override: ".concat(t)),{environment:n,apiConfig:b(h({},e),{baseUrl:t})}):{environment:n,apiConfig:e}}function J(){var o;if(console.log("[SDK] detectEnvironment() called"),typeof window=="undefined")return"local";let e=new URLSearchParams(window.location.search).get("tagadaClientEnv");if(e&&(e==="production"||e==="development"||e==="local"))return console.log("[SDK] Using explicit environment override: ".concat(e)),e;try{let r=localStorage.getItem("tgd_client_env")||Ue("tgd_client_env");if(r&&(r==="production"||r==="development"||r==="local"))return console.log("[SDK] Using persisted environment override: ".concat(r)),r}catch(r){}let t=window.location.hostname,i=window.location.href;if(console.log('[SDK] detectEnvironment() - hostname: "'.concat(t,'"')),t==="localhost"||t.startsWith("127.")||t.startsWith("192.168.")||t.startsWith("10.")||t.includes(".local")||t===""||t==="0.0.0.0"||t.includes("ngrok-free.dev")||t.includes("ngrok-free.app")||t.includes("ngrok.io")||t.includes("ngrok.app")||t.includes(".loclx.io")){if(console.log("[SDK] detectEnvironment() - returning LOCAL"),typeof window!="undefined"&&((o=window==null?void 0:window.__TAGADA_ENV__)!=null&&o.TAGADA_ENVIRONMENT)){let r=window.__TAGADA_ENV__.TAGADA_ENVIRONMENT.toLowerCase();if(r==="production"||r==="development"||r==="local")return console.log("[SDK] Local override detected: ".concat(r)),r}return"local"}return t==="app.tagadapay.com"||t.includes("tagadapay.com")||t.includes("yourproductiondomain.com")?"production":t==="app.tagadapay.dev"||t.includes("tagadapay.dev")||t.includes("vercel.app")||t.includes("netlify.app")||t.includes("surge.sh")||t.includes("github.io")||t.includes("herokuapp.com")||t.includes("railway.app")||i.includes("?env=dev")||i.includes("?dev=true")||i.includes("#dev")?"development":(console.warn("[SDK] Unknown domain: ".concat(t,", defaulting to production")),"production")}function Y(n=!1){return J()!=="local"?!1:n&&typeof window!="undefined"?!window.location.hostname.includes(".cdn."):!0}var Le,se=N(()=>{"use strict";Le={production:{baseUrl:"https://app.tagadapay.com",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionInitAsync:"/api/v1/checkout/session/init-async",sessionStatus:"/api/v1/checkout/session/status",asyncStatus:"/api/public/v1/checkout/async-status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}},development:{baseUrl:"https://app.tagadapay.dev",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionInitAsync:"/api/v1/checkout/session/init-async",sessionStatus:"/api/v1/checkout/session/status",asyncStatus:"/api/public/v1/checkout/async-status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}},local:{baseUrl:"http://app.localhost:3000",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionInitAsync:"/api/v1/checkout/session/init-async",sessionStatus:"/api/v1/checkout/session/status",asyncStatus:"/api/public/v1/checkout/async-status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}}}});var ae,Me=N(()=>{"use strict";ae=class{constructor(e){this.apiClient=e}async initialize(e){return this.apiClient.post("/api/v1/funnel/initialize",e)}async navigate(e){return this.apiClient.post("/api/v1/funnel/navigate",e)}async updateContext(e,t){return this.apiClient.patch("/api/v1/funnel/context/".concat(e),t)}async endSession(e){return this.apiClient.delete("/api/v1/funnel/session/".concat(e))}async getSession(e,t,i){let o=new URLSearchParams;t&&o.append("currentUrl",t),i&&o.append("includeDebugData","true");let r="/api/v1/funnel/session/".concat(e).concat(o.toString()?"?".concat(o):"");return this.apiClient.get(r)}}});var $,be=N(()=>{"use strict";$=class{constructor(){this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){this.listeners.forEach(t=>{try{t(e)}catch(i){console.error("Error in event listener:",i)}})}clear(){this.listeners.clear()}}});function x(n){if(typeof window!="undefined")try{let t=localStorage.getItem(le)!==n;localStorage.setItem(le,n),t&&window.dispatchEvent(new Event("storage"))}catch(e){console.error("Failed to save token to localStorage:",e)}}function X(){if(typeof window!="undefined")try{return localStorage.getItem(le)}catch(n){return console.error("Failed to get token from localStorage:",n),null}return null}function B(){if(typeof window!="undefined")try{localStorage.removeItem(le)}catch(n){console.error("Failed to clear token from localStorage:",n)}}var le,j=N(()=>{"use strict";le="cms_token"});function ze(n){typeof document!="undefined"&&(document.cookie="".concat(xe,"=").concat(n,"; path=/; max-age=2592000; SameSite=Lax"))}function $e(){if(typeof document=="undefined")return;let n=document.cookie.split("; ").find(e=>e.startsWith("".concat(xe,"=")));return n?n.split("=")[1]:void 0}function ce(){typeof document!="undefined"&&(document.cookie="".concat(xe,"=; path=/; max-age=0"))}var xe,de=N(()=>{"use strict";xe="tgd-funnel-session-id"});function K(n){if(typeof window=="undefined")return null;try{return localStorage.getItem(n)}catch(e){return null}}function V(n,e){if(typeof window!="undefined")try{localStorage.setItem(n,e)}catch(t){}}function Z(n){var i;if(typeof document=="undefined")return null;let t=document.cookie.split(";").find(o=>o.trim().startsWith("".concat(n,"=")));return t?(i=t.split("=")[1])==null?void 0:i.trim():null}function Q(n,e,t=86400){if(typeof document!="undefined"){if(n==="tgd_draft"||n==="tgd-draft"){console.warn("\u{1F6E1}\uFE0F [SDK] Blocked attempt to set ".concat(n," as cookie - this should only be in localStorage"));return}document.cookie="".concat(n,"=").concat(e,"; path=/; max-age=").concat(t)}}function je(n){typeof document!="undefined"&&(document.cookie="".concat(n,"=; path=/; max-age=0"))}function U(){if(typeof window=="undefined")return{};let n=new URLSearchParams(window.location.search),e,t=n.get("draft");if(t!==null)e=t==="true";else{let y=K(C.DRAFT);y!==null&&(e=y==="true")}let i,o=n.get("funnelTracking");if(o!==null)i=o!=="false";else{let y=K(C.FUNNEL_TRACKING)||Z(C.FUNNEL_TRACKING);y!==null&&(i=y!=="false")}let r=n.get("token")||X()||null,s=n.get("funnelSessionId")||null,a=n.get("funnelId")||null,c,p=n.get("funnelEnv");p&&(p==="staging"||p==="production")&&(c=p);let m=n.get("forceReset")==="true",l,f=n.get("tagadaClientEnv");if(f&&(f==="production"||f==="development"||f==="local"))l=f;else{let y=K(C.CLIENT_ENV)||Z(C.CLIENT_ENV);y&&(y==="production"||y==="development"||y==="local")&&(l=y)}let u,d=n.get("tagadaClientBaseUrl");if(d)u=d;else{let y=K(C.CLIENT_BASE_URL)||Z(C.CLIENT_BASE_URL);y&&(u=y)}let w,g=n.get("currency");if(g)w=g;else{let y=K(C.CURRENCY)||Z(C.CURRENCY);y&&(w=y)}let I,R=n.get("locale");if(R)I=R;else{let y=K(C.LOCALE)||Z(C.LOCALE);y&&(I=y)}return{forceReset:m,token:r,funnelSessionId:s,funnelId:a,draft:e,funnelTracking:i,funnelEnv:c,tagadaClientEnv:l,tagadaClientBaseUrl:u,currency:w,locale:I}}function ee(){var e;return(e=U().draft)!=null?e:!1}function Ee(n){if(typeof window!="undefined")if(n)V(C.DRAFT,"true");else try{localStorage.removeItem(C.DRAFT)}catch(e){}}function Ke(n=!1){let e=null;typeof window!="undefined"&&(e=new URLSearchParams(window.location.search).get("token"));let t=U(),i=t.forceReset||!1;if(!i&&!t.token)return Be(),!1;n&&(console.log("[SDK] Detected params:",t),console.log("[SDK] URL token (direct read):",e?e.substring(0,20)+"...":"none")),i&&(n&&console.log("[SDK] Force reset: Clearing all stored state"),B(),ce(),typeof window!="undefined"&&window.localStorage&&Object.keys(localStorage).forEach(s=>{(s.startsWith("tagadapay_")||s.startsWith("tgd_"))&&(n&&console.log("[SDK] Clearing localStorage: ".concat(s)),localStorage.removeItem(s))}));let o=e||t.token;return o!=null?(n&&console.log("[SDK] Setting token from URL:",o.substring(0,20)+"..."),o===""||o==="null"?B():(x(o),n&&console.log("[SDK] \u2705 Token set in localStorage immediately after clear"))):i&&(n&&console.log("[SDK] Force reset mode (no token in URL)"),B()),Be(),t.funnelSessionId&&n&&console.log("[SDK] Using funnelSessionId from URL:",t.funnelSessionId),i}function Be(){if(typeof window=="undefined")return;let n=new URLSearchParams(window.location.search),e=n.get("draft");e!==null&&Ee(e==="true");let t=n.get("funnelTracking");t!==null&&xt(t!=="false");let i=n.get("tagadaClientEnv");i&&(i==="production"||i==="development"||i==="local")&&Et(i);let o=n.get("tagadaClientBaseUrl");o&&kt(o);let r=n.get("currency");r&&(V(C.CURRENCY,r.toUpperCase()),Q(C.CURRENCY,r.toUpperCase(),86400));let s=n.get("locale");s&&(V(C.LOCALE,s),Q(C.LOCALE,s,86400))}function xt(n){if(typeof window=="undefined")return;let e=n?"true":"false";V(C.FUNNEL_TRACKING,e),Q(C.FUNNEL_TRACKING,e,86400)}function Et(n){typeof window!="undefined"&&(V(C.CLIENT_ENV,n),Q(C.CLIENT_ENV,n,86400))}function Ve(){if(typeof window!="undefined")try{localStorage.removeItem(C.CLIENT_ENV),je(C.CLIENT_ENV)}catch(n){}}function kt(n){typeof window!="undefined"&&(V(C.CLIENT_BASE_URL,n),Q(C.CLIENT_BASE_URL,n,86400))}function Ge(){if(typeof window!="undefined")try{localStorage.removeItem(C.CLIENT_BASE_URL),je(C.CLIENT_BASE_URL)}catch(n){}}function He(){var e;return(e=U().funnelTracking)!=null?e:!0}var C,ue=N(()=>{"use strict";j();de();C={DRAFT:"tgd_draft",FUNNEL_TRACKING:"tgd_funnel_tracking",FORCE_RESET:"tgd_force_reset",CLIENT_ENV:"tgd_client_env",CLIENT_BASE_URL:"tgd_client_base_url",CURRENCY:"tgd_currency",LOCALE:"tgd_locale"}});var qe={};Te(qe,{injectPreviewModeIndicator:()=>At,isIndicatorInjected:()=>_t,removePreviewModeIndicator:()=>Pt});function ke(n){if(typeof window=="undefined"||typeof document=="undefined")return;let e=window.location.hostname,t=e.split("."),i=["",e,"."+e];for(let a=1;a<t.length;a++){let c=t.slice(a).join(".");i.push(c),i.push("."+c)}let o=window.location.pathname.split("/").filter(a=>a),r=["/"],s="";o.forEach(a=>{s+="/"+a,r.push(s)}),i.forEach(a=>{r.forEach(c=>{let p="".concat(n,"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=").concat(c),m=a?"; domain=".concat(a):"";document.cookie=p+m,document.cookie=p+m+"; secure",document.cookie=p+m+"; SameSite=None; secure",document.cookie=p+m+"; SameSite=Lax",document.cookie=p+m+"; SameSite=Strict"})})}function Rt(){if(typeof window=="undefined"||!confirm("\u{1F6AA} Leave Preview Mode?\n\nThis will clear ALL cookies and localStorage (including Shopify session, cart, and preview settings) and reload the page.\n\nAre you sure?"))return;let e=new URL(window.location.href);["draft","funnelEnv","funnelTracking","tagadaClientEnv","tagadaClientBaseUrl","forceReset","funnelId","funnelSessionId","token"].forEach(r=>e.searchParams.delete(r)),window.history.replaceState({},"",e.href);try{let r=Object.getOwnPropertyDescriptor(Document.prototype,"cookie")||Object.getOwnPropertyDescriptor(HTMLDocument.prototype,"cookie");r&&r.set&&Object.defineProperty(document,"cookie",{configurable:!0,enumerable:!0,get:function(){return r.get?r.get.call(this):""},set:function(s){if(typeof s=="string"){let a=s.toLowerCase();if(a.includes("tgd_draft")||a.includes("tgd-draft")||a.includes("tgd.draft")||a.includes("tgddraft")){if(a.includes("max-age=0")||a.includes("expires=thu, 01 jan 1970")){r.set&&r.set.call(this,s);return}console.warn("\u{1F6E1}\uFE0F [TagadaPay] BLOCKED: tgd_draft should never be a cookie");return}}r.set&&r.set.call(this,s)}})}catch(r){console.warn("[TagadaPay] Could not install cookie blocker:",r)}if(window.localStorage)try{localStorage.removeItem("tgd_draft"),localStorage.removeItem("tgd_funnel_tracking"),localStorage.removeItem("tgd_client_env"),localStorage.removeItem("tgd_client_base_url"),localStorage.removeItem("cms_token")}catch(r){console.warn("[TagadaPay] Failed to clear some localStorage keys:",r)}B(),ce(),Ve(),Ge(),window.localStorage&&localStorage.clear(),window.sessionStorage&&sessionStorage.clear(),["tgd-funnel-session-id","tgd_draft","tgd_funnel_tracking","tgd_client_env","tgd_client_base_url","cms_token","tagadapay_session"].forEach(r=>ke(r)),["tgd-draft","tgd_draft","tgd.draft","tgddraft"].forEach(r=>ke(r)),document.cookie&&document.cookie.split(";").forEach(s=>{let a=s.split("=")[0].trim();if(!a)return;let c=window.location.hostname,p=c.split("."),m=["",c,"."+c];for(let d=1;d<p.length;d++){let w=p.slice(d).join(".");m.push(w),m.push("."+w)}let l=window.location.pathname.split("/").filter(d=>d),f=["/"],u="";l.forEach(d=>{u+="/"+d,f.push(u)}),m.forEach(d=>{f.forEach(w=>{let g="".concat(a,"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=").concat(w),I=d?"; domain=".concat(d):"";document.cookie=g+I,document.cookie=g+I+"; secure",document.cookie=g+I+"; SameSite=None; secure",document.cookie=g+I+"; SameSite=Lax",document.cookie=g+I+"; SameSite=Strict",document.cookie=g+I+"; secure; SameSite=None",document.cookie=g+I+"; secure; SameSite=Lax",document.cookie=g+I+"; secure; SameSite=Strict"})})}),setTimeout(()=>{window.localStorage&&localStorage.length>0&&localStorage.clear(),ke("tgd_draft"),typeof window.stop=="function"&&window.stop(),window.location.replace(e.href)},10)}function At(){if(fe||typeof window=="undefined"||typeof document=="undefined")return;let n=U(),e=ee(),t=!He(),i=!!(n.tagadaClientEnv||n.tagadaClientBaseUrl);if(!e&&!t&&!i)return;let o=document.createElement("div");o.id="tgd-preview-indicator",o.style.cssText='\n position: fixed;\n bottom: 16px;\n right: 16px;\n z-index: 999999;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n ';let r=document.createElement("div");r.style.cssText="\n background: ".concat(e?"#ff9500":"#007aff",";\n color: white;\n padding: 8px 12px;\n border-radius: 8px;\n font-size: 13px;\n font-weight: 600;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);\n cursor: pointer;\n transition: all 0.2s ease;\n display: flex;\n align-items: center;\n gap: 6px;\n "),r.innerHTML='\n <span style="font-size: 16px;">\u{1F50D}</span>\n <span>'.concat(e?"Preview Mode":"Dev Mode","</span>\n ");let s=document.createElement("div");s.style.cssText="\n position: absolute;\n bottom: calc(100% + 8px);\n right: 0;\n background: white;\n border: 1px solid #e5e5e5;\n border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n padding: 12px;\n min-width: 250px;\n font-size: 12px;\n line-height: 1.5;\n display: none;\n ",s.style.paddingTop="20px";let a=document.createElement("div");a.style.cssText="\n position: absolute;\n bottom: 100%;\n left: 0;\n right: 0;\n height: 8px;\n display: none;\n ";let c='<div style="margin-bottom: 8px; font-weight: 600; color: #1d1d1f;">Current Environment</div>';c+='<div style="display: flex; flex-direction: column; gap: 6px;">',e&&(c+='\n <div style="display: flex; justify-content: space-between; color: #86868b;">\n <span>Draft Mode:</span>\n <span style="color: #ff9500; font-weight: 600;">ON</span>\n </div>\n '),t&&(c+='\n <div style="display: flex; justify-content: space-between; color: #86868b;">\n <span>Tracking:</span>\n <span style="color: #ff3b30; font-weight: 600;">DISABLED</span>\n </div>\n '),n.funnelEnv&&(c+='\n <div style="display: flex; justify-content: space-between; color: #86868b;">\n <span>Funnel Env:</span>\n <span style="color: #1d1d1f; font-weight: 600; font-family: monospace; font-size: 11px;">\n '.concat(n.funnelEnv,"\n </span>\n </div>\n ")),n.tagadaClientEnv&&(c+='\n <div style="display: flex; justify-content: space-between; color: #86868b;">\n <span>API Env:</span>\n <span style="color: #1d1d1f; font-weight: 600; font-family: monospace; font-size: 11px;">\n '.concat(n.tagadaClientEnv,"\n </span>\n </div>\n ")),n.tagadaClientBaseUrl&&(c+='\n <div style="color: #86868b;">\n <div style="margin-bottom: 4px;">API URL:</div>\n <div style="color: #1d1d1f; font-weight: 600; font-family: monospace; font-size: 10px; word-break: break-all; background: #f5f5f7; padding: 4px 6px; border-radius: 4px;">\n '.concat(n.tagadaClientBaseUrl,"\n </div>\n </div>\n ")),n.funnelId&&(c+='\n <div style="color: #86868b; margin-top: 4px; padding-top: 8px; border-top: 1px solid #e5e5e5;">\n <div style="margin-bottom: 4px;">Funnel ID:</div>\n <div style="color: #1d1d1f; font-family: monospace; font-size: 10px; word-break: break-all; background: #f5f5f7; padding: 4px 6px; border-radius: 4px;">\n '.concat(n.funnelId,"\n </div>\n </div>\n ")),c+="</div>",c+='\n <div style="margin-top: 12px; padding-top: 8px; border-top: 1px solid #e5e5e5; font-size: 11px; color: #86868b; text-align: center;">\n Add <code style="background: #f5f5f7; padding: 2px 4px; border-radius: 3px;">?forceReset=true</code> to reset\n </div>\n ',c+='\n <div style="margin-top: 12px; padding-top: 8px; border-top: 1px solid #e5e5e5;">\n <button id="tgd-leave-preview" style="\n background: #ff3b30;\n color: white;\n border: none;\n border-radius: 6px;\n padding: 10px 12px;\n font-size: 13px;\n font-weight: 600;\n cursor: pointer;\n transition: opacity 0.2s;\n width: 100%;\n ">\n \u{1F6AA} Leave Preview Mode\n </button>\n </div>\n ',s.innerHTML=c;let p=!1,m=()=>{p=!0,s.style.display="block",a.style.display="block"},l=()=>{p=!1,setTimeout(()=>{p||(s.style.display="none",a.style.display="none")},100)};r.addEventListener("mouseenter",m),r.addEventListener("mouseleave",l),a.addEventListener("mouseenter",m),a.addEventListener("mouseleave",l),s.addEventListener("mouseenter",m),s.addEventListener("mouseleave",l);let f=s.querySelector("#tgd-leave-preview");f&&(f.addEventListener("mouseenter",()=>{f.style.opacity="0.8"}),f.addEventListener("mouseleave",()=>{f.style.opacity="1"}),f.addEventListener("click",u=>{u.stopPropagation(),Rt()})),o.appendChild(r),o.appendChild(a),o.appendChild(s),document.body.appendChild(o),G=o,fe=!0}function Pt(){G&&G.parentNode&&(G.parentNode.removeChild(G),G=null,fe=!1)}function _t(){return fe}var G,fe,We=N(()=>{"use strict";ue();j();de();G=null,fe=!1});var rt={};Te(rt,{FunnelClient:()=>ne,TrackingProvider:()=>Ze,findMethod:()=>tt,getAssignedOrderBumpOfferIds:()=>Bt,getAssignedPaymentFlowId:()=>it,getAssignedPixels:()=>$t,getAssignedResources:()=>ot,getAssignedScripts:()=>zt,getAssignedStaticResources:()=>Mt,getAssignedStepConfig:()=>P,getAssignedUpsellOfferIds:()=>jt,getEnabledMethods:()=>Qe,getExpressMethods:()=>et,getExpressMethodsByProcessor:()=>Ft,getLocalFunnelConfig:()=>nt,isMethodEnabled:()=>Dt,loadLocalFunnelConfig:()=>Ut});function Qe(n){return n?Object.values(n).filter(e=>e.enabled):[]}function et(n){return Qe(n).filter(e=>e.express)}function Ft(n){let e={};for(let t of et(n)){let i=t.processorId||t.integrationId||t.provider;e[i]||(e[i]=[]),e[i].push(t)}return e}function tt(n,e){if(n){for(let t of Object.values(n))if(t.method===e&&t.enabled)return t}}function Dt(n,e){return!!tt(n,e)}function Nt(){if(typeof window!="undefined"){if(window.__TGD_FUNNEL_ID__)return window.__TGD_FUNNEL_ID__;if(typeof document!="undefined"){let n=document.querySelector('meta[name="x-funnel-id"]');return(n==null?void 0:n.getAttribute("content"))||void 0}}}function ge(){if(typeof window!="undefined"){if(window.__TGD_FUNNEL_VARIANT_ID__)return window.__TGD_FUNNEL_VARIANT_ID__;if(typeof document!="undefined"){let n=document.querySelector('meta[name="x-funnel-variant-id"]');return(n==null?void 0:n.getAttribute("content"))||void 0}}}function te(){if(typeof window!="undefined"){if(window.__TGD_FUNNEL_STEP_ID__)return window.__TGD_FUNNEL_STEP_ID__;if(typeof document!="undefined"){let n=document.querySelector('meta[name="x-funnel-step-id"]');return(n==null?void 0:n.getAttribute("content"))||void 0}}}function Ye(n){if(!n||typeof n!="string")return;let e=n.trim();if(!e)return;let t=[()=>JSON.parse(e),()=>JSON.parse(decodeURIComponent(e)),()=>JSON.parse(decodeURIComponent(decodeURIComponent(e)))];for(let i of t)try{let o=i();if(o&&typeof o=="object")return o}catch(o){}typeof console!="undefined"&&console.warn("[SDK] Failed to parse stepConfig:",e.substring(0,100))}function Lt(){if(typeof window=="undefined")return!1;let n=window.location.hostname;return n==="localhost"||n==="127.0.0.1"||n.endsWith(".localhost")&&!n.includes(".cdn.")}async function Ut(){if(!Lt())return null;if(E!==void 0)return E;if(Re)return await new Promise(n=>setTimeout(n,100)),E!=null?E:null;Re=!0;try{console.log("\u{1F6E0}\uFE0F [SDK] Loading local funnel config from /config/funnel.local.json...");let n=await fetch("/config/funnel.local.json");if(!n.ok)return console.log("\u{1F6E0}\uFE0F [SDK] funnel.local.json not found (this is fine in production)"),E=null,null;let e=await n.json();return console.log("\u{1F6E0}\uFE0F [SDK] \u2705 Loaded local funnel config:",e),E=e,e}catch(n){return console.log("\u{1F6E0}\uFE0F [SDK] funnel.local.json not available:",n),E=null,null}finally{Re=!1}}function nt(){return E!=null?E:null}function Ot(n){let e=h(h({},n.staticResources),n.resources);return{payment:n.paymentFlowId?{paymentFlowId:n.paymentFlowId}:void 0,resources:Object.keys(e).length>0?e:void 0,scripts:n.scripts,pixels:n.pixels,orderBumps:n.orderBumps,upsellOffers:n.upsellOffers}}function P(){if(typeof window=="undefined")return;let n=nt();if(n)return console.log("\u{1F6E0}\uFE0F [SDK] Using local funnel.local.json (overrides injected)"),Ot(n);let e=window.__TGD_STEP_CONFIG__;if(e){let t=Ye(e);if(t)return t}if(typeof document!="undefined"){let t=document.querySelector('meta[name="x-step-config"]'),i=t==null?void 0:t.getAttribute("content");if(i){let o=Ye(i);if(o)return o}}}function it(){var t,i;let n=P(),e=(t=n==null?void 0:n.paymentSetupConfig)==null?void 0:t.card;if(e!=null&&e.paymentFlowId)return e.paymentFlowId;if((i=n==null?void 0:n.payment)!=null&&i.paymentFlowId)return n.payment.paymentFlowId;if(typeof window!="undefined"){if(window.__TGD_PAYMENT_FLOW_ID__)return window.__TGD_PAYMENT_FLOW_ID__;if(typeof document!="undefined"){let o=document.querySelector('meta[name="x-payment-flow-id"]');return(o==null?void 0:o.getAttribute("content"))||void 0}}}function ot(){let n=P(),e=n==null?void 0:n.staticResources,t=n==null?void 0:n.resources;if(!(!e&&!t))return h(h({},e),t)}function Mt(){return ot()}function zt(n){let e=P();if(!(e!=null&&e.scripts))return;let t=e.scripts.filter(i=>i.enabled);return n&&(t=t.filter(i=>i.position===n||!i.position&&n==="head-end")),t.length>0?t:void 0}function Xe(n){let e="containerId"in n?"containerId":"pixelId",t=n[e];if(!t||!t.includes(";")&&!t.includes(","))return[n];let i=t.split(/[;,]/).map(o=>o.trim()).filter(o=>o.length>0);return i.length<=1?[n]:i.map(o=>b(h({},n),{[e]:o}))}function $t(){let n=P(),e=n==null?void 0:n.pixels;if(!e||typeof e!="object")return;let t={};for(let[i,o]of Object.entries(e))o&&(Array.isArray(o)?t[i]=o.flatMap(r=>Xe(r)):typeof o=="object"&&(t[i]=Xe(o)));return Object.keys(t).length>0?t:void 0}function Bt(){let n=P();if(n!=null&&n.orderBumps&&n.orderBumps.mode==="custom")return n.orderBumps.enabledOfferIds}function jt(){let n=P();if(n!=null&&n.upsellOffers&&n.upsellOffers.mode==="custom")return n.upsellOffers.enabledUpsellIds}var Je,Ze,E,Re,ne,pe=N(()=>{"use strict";se();Me();be();ue();de();Je=()=>Promise.resolve().then(()=>(We(),qe)).then(n=>n.injectPreviewModeIndicator()),Ze=(r=>(r.FACEBOOK="facebook",r.TIKTOK="tiktok",r.SNAPCHAT="snapchat",r.PINTEREST="pinterest",r.GTM="gtm",r))(Ze||{});Re=!1;ne=class{constructor(e){this.eventDispatcher=new $;this.isInitializing=!1;this.initializationAttempted=!1;this.config=e,this.resource=new ae(e.apiClient),this.state={context:null,isLoading:!1,isInitialized:!1,isNavigating:!1,error:null,sessionError:null}}setConfig(e){this.config=h(h({},this.config),e)}subscribe(e){return this.eventDispatcher.subscribe(e)}getState(){return this.state}getDetectedSessionId(){var i;if((i=this.state.context)!=null&&i.sessionId)return this.state.context.sessionId;if(typeof window=="undefined")return null;let t=new URLSearchParams(window.location.search).get("funnelSessionId");return t||$e()||null}resetInitialization(){this.initializationAttempted=!1,this.isInitializing=!1,this.updateState({context:null,isInitialized:!1})}async autoInitialize(e,t,i){if(this.state.context)return this.state.context;if(this.isInitializing||this.initializationAttempted)return null;this.initializationAttempted=!0,this.isInitializing=!0,this.updateState({isLoading:!0,error:null});try{let o=this.getDetectedSessionId(),a=new URLSearchParams(typeof window!="undefined"?window.location.search:"").get("funnelId")||i,c=Nt(),p=ge(),m=te(),l=U(),f=this.config.funnelId||c||a,u=this.config.stepId||m,d=typeof window!="undefined"?new URLSearchParams(window.location.search):null,w=d==null?void 0:d.get("funnelEnv");this.config.debugMode&&console.log("\u{1F680} [FunnelClient] Auto-initializing...",{existingSessionId:o,effectiveFunnelId:f,funnelVariantId:p,funnelStepId:u,draft:l.draft,funnelTracking:l.funnelTracking,funnelEnv:w,tagadaClientEnv:l.tagadaClientEnv,tagadaClientBaseUrl:l.tagadaClientBaseUrl,source:{funnelId:this.config.funnelId?"config":c?"injected":a?"url/prop":"none",stepId:this.config.stepId?"config":m?"injected":"none"}});let g=await this.resource.initialize({cmsSession:{customerId:e.customerId,sessionId:e.sessionId,storeId:t.id,accountId:t.accountId},funnelId:f,existingSessionId:o||void 0,currentUrl:typeof window!="undefined"?window.location.href:void 0,funnelVariantId:p,funnelStepId:u,draft:l.draft,funnelTracking:l.funnelTracking,funnelEnv:w||void 0,tagadaClientEnv:l.tagadaClientEnv,tagadaClientBaseUrl:l.tagadaClientBaseUrl,currency:l.currency,locale:l.locale});if(g.success&&g.context){let I=this.enrichContext(g.context);return this.handleSessionSuccess(I),Je(),I}else throw new Error(g.error||"Failed to initialize funnel session")}catch(o){let r=o instanceof Error?o:new Error(String(o));throw this.updateState({error:r,isLoading:!1}),this.config.debugMode&&console.error("\u274C [FunnelClient] Init failed:",r),r}finally{this.isInitializing=!1}}async initialize(e,t,i,o){this.updateState({isLoading:!0,error:null});try{let r=ge(),s=te();this.config.debugMode&&(r&&console.log("\u{1F3AF} [FunnelClient] Detected A/B test variant:",r),s&&console.log("\u{1F3AF} [FunnelClient] Detected step ID:",s));let a=await this.resource.initialize({cmsSession:{customerId:e.customerId,sessionId:e.sessionId,storeId:t.id,accountId:t.accountId},funnelId:i,entryStepId:o,currentUrl:typeof window!="undefined"?window.location.href:void 0,funnelVariantId:r,funnelStepId:s});if(a.success&&a.context){let c=this.enrichContext(a.context);return this.handleSessionSuccess(c),Je(),c}else throw new Error(a.error||"Failed to initialize")}catch(r){let s=r instanceof Error?r:new Error(String(r));throw this.updateState({error:s,isLoading:!1}),s}}async navigate(e,t){var i,o,r,s,a,c;if(t!=null&&t.waitForSession&&!((i=this.state.context)!=null&&i.sessionId)){this.config.debugMode&&console.log("\u23F3 [FunnelClient] Waiting for session before navigation...");let p=5e3,m=Date.now();for(;!((o=this.state.context)!=null&&o.sessionId)&&Date.now()-m<p;)await new Promise(l=>setTimeout(l,100));(r=this.state.context)!=null&&r.sessionId&&this.config.debugMode&&console.log("\u2705 [FunnelClient] Session ready, proceeding with navigation")}if(!((s=this.state.context)!=null&&s.sessionId))throw new Error("No active session");this.updateState({isNavigating:!0,isLoading:!0});try{let p=ge(),m=te(),l=typeof window!="undefined"?window.location.href:void 0;!m&&this.config.stepId&&(m=this.config.stepId,this.config.debugMode&&console.log("\u{1F50D} [FunnelClient.navigate] Using stepId from config (no injection):",m)),!p&&this.config.variantId&&(p=this.config.variantId,this.config.debugMode&&console.log("\u{1F50D} [FunnelClient.navigate] Using variantId from config (no injection):",p)),this.config.debugMode&&console.log("\u{1F50D} [FunnelClient.navigate] Sending to backend:",{sessionId:this.state.context.sessionId,currentUrl:l,funnelStepId:m||"(not found)",funnelVariantId:p||"(not found)",hasInjectedStepId:!!te(),hasInjectedVariantId:!!ge(),usedConfigFallback:!te()&&!!this.config.stepId,customerTags:(t==null?void 0:t.customerTags)||"(none)",deviceId:(t==null?void 0:t.deviceId)||"(none)"});let f=(t==null?void 0:t.fireAndForget)||!1,u=await this.resource.navigate({sessionId:this.state.context.sessionId,event:e,currentUrl:l,funnelStepId:m,funnelVariantId:p,fireAndForget:f,customerTags:t==null?void 0:t.customerTags,deviceId:t==null?void 0:t.deviceId});if(!u.success||!u.result)throw new Error(u.error||"Navigation failed");let d=u.result;if(d.queued)return this.updateState({isNavigating:!1,isLoading:!1}),d.sessionId&&d.sessionId!==((a=this.state.context)==null?void 0:a.sessionId)&&(this.config.debugMode&&console.log("\u{1F525} [FunnelClient] Session ID updated: ".concat((c=this.state.context)==null?void 0:c.sessionId," \u2192 ").concat(d.sessionId)),this.state.context&&(this.state.context.sessionId=d.sessionId)),this.config.debugMode&&console.log("\u{1F525} [FunnelClient] Navigation queued (fire-and-forget mode)"),d;let w=(t==null?void 0:t.autoRedirect)!==void 0?t.autoRedirect:this.config.autoRedirect!==!1;return this.updateState({isNavigating:!1,isLoading:!1}),w&&(d!=null&&d.url)&&typeof window!="undefined"&&(this.config.debugMode&&console.log("\u{1F680} [FunnelClient] Auto-redirecting to:",d.url,"(skipped session refresh - next page will initialize)"),window.location.replace(d.url)),d}catch(p){let m=p instanceof Error?p:new Error(String(p));throw this.updateState({error:m,isNavigating:!1,isLoading:!1}),m}}async goToStep(e,t){return this.navigate({type:"direct_navigation",data:{targetStepId:e}},t)}async refreshSession(){var e;if((e=this.state.context)!=null&&e.sessionId)try{let t=await this.resource.getSession(this.state.context.sessionId);if(t.success&&t.context){let i=this.enrichContext(t.context);return this.updateState({context:i,sessionError:null}),i}}catch(t){this.updateState({sessionError:t instanceof Error?t:new Error(String(t))})}}async updateContext(e){var t;if(!((t=this.state.context)!=null&&t.sessionId))throw new Error("No active session");this.updateState({isLoading:!0});try{let i=await this.resource.updateContext(this.state.context.sessionId,{contextUpdates:e});if(i.success)await this.refreshSession();else throw new Error(i.error||"Failed to update context")}finally{this.updateState({isLoading:!1})}}async endSession(){var e;if((e=this.state.context)!=null&&e.sessionId)try{await this.resource.endSession(this.state.context.sessionId)}finally{this.state.context=null,this.updateState({context:null,isInitialized:!1})}}updateState(e){this.state=h(h({},this.state),e),this.eventDispatcher.notify(this.state)}handleSessionSuccess(e){ze(e.sessionId),this.updateState({context:e,isLoading:!1,isInitialized:!0,error:null,sessionError:null})}enrichContext(e){var s,a;if((((s=this.config.environment)==null?void 0:s.environment)||J())!=="local")return e;let i=((a=this.config.pluginConfig)==null?void 0:a.staticResources)||{};if(Object.keys(i).length===0)return e;let o=e.static||{};return Object.keys(i).every(c=>o[c]===i[c])&&Object.keys(o).length===Object.keys(i).length?e:b(h({},e),{static:h(h({},i),o)})}}});var mn={};Te(mn,{TRACKER_VERSION:()=>_e,TagadaExternalTracker:()=>Se,TagadaTracker:()=>yt});se();pe();var _={NETWORK_ERROR:"network_error",API_ERROR:"api_error",AUTH_REQUIRED:"auth_required",TOKEN_EXPIRED:"token_expired",NOT_FOUND:"not_found",VALIDATION_ERROR:"validation_error",CIRCUIT_BREAKER:"circuit_breaker",PAYMENT_FAILED:"payment_failed",CARD_DECLINED:"card_declined",SESSION_EXPIRED:"session_expired",RATE_LIMITED:"rate_limited",TIMEOUT:"timeout",UNKNOWN:"unknown"},L=class extends Error{constructor(e,t){var i;super(e),this.name="TagadaError",this.code=t.code,this.statusCode=t.statusCode,this.retryable=(i=t.retryable)!=null?i:!1,this.details=t.details,Object.setPrototypeOf(this,new.target.prototype)}},O=class extends L{constructor(e,t,i){var o,r;super(e,{code:(o=i==null?void 0:i.code)!=null?o:_.API_ERROR,statusCode:t,retryable:(r=i==null?void 0:i.retryable)!=null?r:t>=500,details:i==null?void 0:i.details}),this.name="TagadaApiError"}},me=class extends L{constructor(e="Network request failed"){super(e,{code:_.NETWORK_ERROR,retryable:!0}),this.name="TagadaNetworkError"}},he=class extends L{constructor(e="Authentication required",t=401){super(e,{code:_.AUTH_REQUIRED,statusCode:t,retryable:!1}),this.name="TagadaAuthError"}};var ye=class extends L{constructor(e){super(e,{code:_.CIRCUIT_BREAKER,retryable:!1}),this.name="TagadaCircuitBreakerError"}};var Ce=class{constructor(e){this.currentToken=null;this.tokenProvider=null;this.requestHistory=new Map;this.WINDOW_MS=5e3;this.MAX_REQUESTS=30;this.baseURL=e.baseURL,this.timeout=e.timeout||6e4,this.defaultHeaders=h({"Content-Type":"application/json"},e.headers),typeof setInterval!="undefined"&&setInterval(()=>this.cleanupHistory(),1e4)}setTokenProvider(e){this.tokenProvider=e}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,i){return this.request("POST",e,t,i)}async put(e,t,i){return this.request("PUT",e,t,i)}async patch(e,t,i){return this.request("PATCH",e,t,i)}async delete(e,t){return this.request("DELETE",e,void 0,t)}setHeader(e,t){this.defaultHeaders[e]=t}removeHeader(e){delete this.defaultHeaders[e]}updateToken(e){this.currentToken=e,e?this.setHeader("x-cms-token",e):(this.removeHeader("x-cms-token"),console.log("[SDK] Token removed from ApiClient"))}getCurrentToken(){return this.currentToken}updateConfig(e){e.baseURL&&(this.baseURL=e.baseURL),e.timeout&&(this.timeout=e.timeout),e.headers&&Object.assign(this.defaultHeaders,e.headers),console.log("[SDK] ApiClient configuration updated")}async request(e,t,i,o){let r="".concat(e,":").concat(t);try{this.checkRequestLimit(r)}catch(l){throw console.error("[SDK] \u{1F6D1} Request blocked by Circuit Breaker:",l),l}if(!(o!=null&&o.skipAuth)&&!this.currentToken&&this.tokenProvider)try{console.log("[SDK] Waiting for token...");let l=await this.tokenProvider();l&&this.updateToken(l)}catch(l){console.error("[SDK] Failed to get token from provider:",l)}let s=h({},this.defaultHeaders);o!=null&&o.headers&&Object.assign(s,o.headers),!(o!=null&&o.skipAuth)&&this.currentToken&&(s["x-cms-token"]=this.currentToken);let a="".concat(this.baseURL).concat(t);if(o!=null&&o.params){let l=new URLSearchParams(o.params);a+="?".concat(l.toString())}console.log("[SDK] Making ".concat(e," request to: ").concat(a));let c=new AbortController,p=setTimeout(()=>c.abort(),this.timeout),m=o!=null&&o.signal?Kt([o.signal,c.signal]):c.signal;try{let l={method:e,headers:s,signal:m};i!==void 0&&(l.body=JSON.stringify(i));let f=await fetch(a,l);if(!f.ok){let d=await this.safeParseJson(f);throw this.toTagadaError(f.status,d,f.statusText)}return await f.json()}catch(l){throw l instanceof L?l:l instanceof DOMException&&l.name==="AbortError"?new O("Request timed out",0,{code:_.TIMEOUT,retryable:!0}):l instanceof TypeError?new me(l.message):l instanceof Error?l:new Error(String(l))}finally{clearTimeout(p)}}toTagadaError(e,t,i){var r,s,a;let o=(s=(r=t==null?void 0:t.message)!=null?r:t==null?void 0:t.error)!=null?s:i;return e===401||e===403?new he(o,e):e===429?new O(o,429,{code:_.RATE_LIMITED,retryable:!0}):e===404?new O(o,404,{code:_.NOT_FOUND,retryable:!1}):new O(o,e,{code:(a=t==null?void 0:t.code)!=null?a:_.API_ERROR,details:t,retryable:e>=500})}async safeParseJson(e){try{return await e.json()}catch(t){return}}checkRequestLimit(e){let t=Date.now(),i=this.requestHistory.get(e);if(!i){this.requestHistory.set(e,{count:1,firstRequestTime:t});return}if(t-i.firstRequestTime>this.WINDOW_MS){this.requestHistory.set(e,{count:1,firstRequestTime:t});return}if(i.count++,i.count>this.MAX_REQUESTS)throw new ye("Circuit Breaker: Too many requests to ".concat(e," (").concat(i.count," in ").concat(this.WINDOW_MS,"ms)"))}cleanupHistory(){let e=Date.now();for(let[t,i]of this.requestHistory.entries())e-i.firstRequestTime>this.WINDOW_MS&&this.requestHistory.delete(t)}};function Kt(n){let e=new AbortController;for(let t of n){if(t.aborted)return e.abort(t.reason),e.signal;t.addEventListener("abort",()=>e.abort(t.reason),{once:!0,signal:e.signal})}return e.signal}function Vt(){return{width:window.screen.width,height:window.screen.height}}function Gt(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(n){return"UTC"}}function st(){try{return navigator.language||"en-US"}catch(n){return"en-US"}}var M=typeof navigator!="undefined"?navigator.userAgent:"";function k(n,...e){for(let t of e){let i=n.match(t);if(i)return i}return null}function Ht(n){let e=[[/EdgA?\/([\d.]+)/i,"Edge"],[/OPR\/([\d.]+)/i,"Opera"],[/Brave\/([\d.]+)/i,"Brave"],[/Vivaldi\/([\d.]+)/i,"Vivaldi"],[/SamsungBrowser\/([\d.]+)/i,"Samsung Internet"],[/UCBrowser\/([\d.]+)/i,"UC Browser"],[/Firefox\/([\d.]+)/i,"Firefox"],[/CriOS\/([\d.]+)/i,"Chrome"],[/FxiOS\/([\d.]+)/i,"Firefox"],[/Chrome\/([\d.]+)/i,"Chrome"],[/Version\/([\d.]+).*Safari/i,"Safari"],[/Safari\/([\d.]+)/i,"Safari"]];for(let[t,i]of e){let o=n.match(t);if(o){let r=o[1]||"";return{name:i,version:r,major:r.split(".")[0]||""}}}return{name:"",version:"",major:""}}function qt(n){let e=k(n,/Windows NT ([\d.]+)/i)||k(n,/Mac OS X ([\d_.]+)/i)||k(n,/Android ([\d.]+)/i)||k(n,/iPhone OS ([\d_]+)/i)||k(n,/iPad.*OS ([\d_]+)/i)||k(n,/CrOS[\w ]*\/([\d.]+)/i)||k(n,/Linux/i);if(!e)return{name:"",version:""};let t=e[0],i=(e[1]||"").replace(/_/g,".");return/Windows/i.test(t)?{name:"Windows",version:{"10.0":"10","6.3":"8.1","6.2":"8","6.1":"7","6.0":"Vista","5.1":"XP"}[i]||i}:/Mac OS X/i.test(t)?{name:"macOS",version:i}:/Android/i.test(t)?{name:"Android",version:i}:/iPhone|iPad/i.test(t)?{name:"iOS",version:i}:/CrOS/i.test(t)?{name:"Chrome OS",version:i}:/Linux/i.test(t)?{name:"Linux",version:""}:{name:"",version:""}}function Wt(n){var e;if(/iPad/i.test(n))return{type:"tablet",vendor:"Apple",model:"iPad"};if(/iPhone/i.test(n))return{type:"mobile",vendor:"Apple",model:"iPhone"};if(/iPod/i.test(n))return{type:"mobile",vendor:"Apple",model:"iPod"};if(/Android/i.test(n)){let t=n.match(/Android[\s\d.]+;\s*([^)]+?)(?:\s+Build)/i);return{type:/Mobile/i.test(n)?"mobile":"tablet",model:(e=t==null?void 0:t[1])==null?void 0:e.trim()}}}function Jt(n){let e=k(n,/AppleWebKit\/([\d.]+)/i)||k(n,/Gecko\/([\d.]+)/i)||k(n,/Trident\/([\d.]+)/i)||k(n,/Presto\/([\d.]+)/i);if(!e)return{name:"",version:""};let t=e[0],i=e[1]||"";return/AppleWebKit/i.test(t)?{name:"WebKit",version:i}:/Gecko/i.test(t)?{name:"Gecko",version:i}:/Trident/i.test(t)?{name:"Trident",version:i}:/Presto/i.test(t)?{name:"Presto",version:i}:{name:"",version:""}}function Yt(n){return/x86_64|x64|amd64|Win64/i.test(n)?{architecture:"amd64"}:/ia32|x86/i.test(n)?{architecture:"ia32"}:/aarch64|arm64/i.test(n)?{architecture:"arm64"}:/arm/i.test(n)?{architecture:"arm"}:{architecture:""}}function Xt(){return navigator.webdriver?!0:/bot|crawl|spider|slurp|Googlebot|bingbot|yandex|baidu|duckduck|facebookexternalhit|Twitterbot|linkedinbot|embedly|quora|pinterest|redditbot|Slackbot|Discordbot|WhatsApp|TelegramBot|Applebot/i.test(M)}function Zt(n){return/Chrome|Chromium|Edge|Brave|Opera|Vivaldi|Arc/i.test(n)}function Qt(){return window.matchMedia("(display-mode: standalone)").matches||navigator.standalone===!0}function en(n){return/mac/i.test(n)?navigator.maxTouchPoints>0:!1}function at(){if(typeof window=="undefined")return{userAgent:{name:"",browser:{major:"",name:"",version:""},os:{name:"",version:""},device:void 0,engine:{name:"",version:""},cpu:{architecture:""}},screenResolution:{width:0,height:0},timeZone:"UTC",flags:{isBot:!1,isChromeFamily:!1,isStandalonePWA:!1,isAppleSilicon:!1}};let n=Ht(M),e=qt(M),t=Wt(M),i=Jt(M),o=Yt(M),r;try{r={isBot:Xt(),isChromeFamily:Zt(n.name),isStandalonePWA:Qt(),isAppleSilicon:en(e.name)}}catch(s){r={isBot:!1,isChromeFamily:!1,isStandalonePWA:!1,isAppleSilicon:!1}}return{userAgent:{name:M,browser:n,os:e,device:t,engine:i,cpu:o},screenResolution:Vt(),timeZone:Gt(),flags:r}}function lt(){if(typeof window=="undefined")return{};let n=new URLSearchParams(window.location.search);return{locale:n.get("locale")||void 0,currency:n.get("currency")||void 0,utmSource:n.get("utm_source")||void 0,utmMedium:n.get("utm_medium")||void 0,utmCampaign:n.get("utm_campaign")||void 0,gclid:n.get("gclid")||void 0}}var Ie=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){this.listeners.has(e)&&this.listeners.get(e).delete(t)}async emit(e,t){if(this.listeners.has(e)){let i=Array.from(this.listeners.get(e));await Promise.all(i.map(o=>{try{return Promise.resolve(o(t))}catch(r){return console.error('[EventBus] Error in listener for event "'.concat(e,'":'),r),Promise.resolve()}}))}}clear(){this.listeners.clear()}};be();function ie(n){try{let e=n.split(".");if(e.length!==3)return console.error("Invalid JWT token format"),null;let t=e[1],i=t+"=".repeat((4-t.length%4)%4),o=atob(i),r=JSON.parse(o);return r.exp&&Date.now()>=r.exp*1e3?(console.warn("JWT token is expired"),null):{sessionId:r.sessionId,storeId:r.storeId,accountId:r.accountId,customerId:r.customerId,role:r.role,isValid:!0,isLoading:!1}}catch(e){return console.error("Failed to decode JWT token:",e),null}}function ct(n){try{let e=n.split(".");if(e.length!==3)return!0;let t=e[1],i=t+"=".repeat((4-t.length%4)%4),o=atob(i),r=JSON.parse(o);return r.exp?Date.now()>=r.exp*1e3:!1}catch(e){return console.error("Failed to check token expiration:",e),!0}}se();var H={},tn=["","VITE_","REACT_APP_","NEXT_PUBLIC_"];function F(n,e=tn){var t,i,o;for(let r of e){let s=r?"".concat(r).concat(n):n;if(typeof process!="undefined"&&((t=process==null?void 0:process.env)!=null&&t[s]))return console.log("process.env[".concat(s,"]"),process.env[s]),process.env[s];if(typeof H!="undefined"&&((i=H==null?void 0:H.env)!=null&&i[s]))return console.log("import.meta.env[".concat(s,"]"),H.env[s]),H.env[s];if(typeof window!="undefined"&&((o=window==null?void 0:window.__TAGADA_ENV__)!=null&&o[s]))return console.log("window.__TAGADA_ENV__[".concat(s,"]"),window.__TAGADA_ENV__[s]),window.__TAGADA_ENV__[s]}}var nn=async(n="default")=>{try{if((F("TAGADA_ENV")||F("TAGADA_ENVIRONMENT"))==="production"||!Y(!0))return null;let t=await fetch("/.local.json");if(!t.ok)return null;let i=await t.json(),o={},r=!1;try{let a=await fetch("/config/".concat(n,".tgd.json"));a.ok||(a=await fetch("/config/".concat(n,".json"))),a.ok&&(o=await a.json(),r=!0)}catch(a){}if(!r&&n!=="default"){console.warn("\u26A0\uFE0F Config variant '".concat(n,"' not found, falling back to 'default'"));try{let a=await fetch("/config/default.tgd.json");a.ok||(a=await fetch("/config/default.json")),a.ok&&(o=await a.json(),r=!0,console.log("\u2705 Fallback to 'default' config successful"))}catch(a){}}r||console.warn(n==="default"?"\u26A0\uFE0F No 'default' config found. Create /config/default.tgd.json":"\u26A0\uFE0F Neither '".concat(n,"' nor 'default' config found. Create /config/default.tgd.json"));let s={storeId:i.storeId,accountId:i.accountId,basePath:i.basePath,config:o};return console.log("\u{1F6E0}\uFE0F Using local development plugin config:",s),s}catch(e){return null}},on=async()=>{try{if((F("TAGADA_ENV")||F("TAGADA_ENVIRONMENT"))==="production"||!Y(!0))return null;try{console.log("\u{1F6E0}\uFE0F [V2] Attempting to load /config/funnel.local.json...");let i=await fetch("/config/funnel.local.json");if(i.ok){let o=await i.json();console.log("\u{1F6E0}\uFE0F [V2] \u2705 Loaded local funnel config (NEW format):",o);let{loadLocalFunnelConfig:r}=await Promise.resolve().then(()=>(pe(),rt));if(await r(),o.staticResources){let s={};for(let[a,c]of Object.entries(o.staticResources))s[a]={id:c};return s}return null}}catch(i){console.log("\u{1F6E0}\uFE0F [V2] funnel.local.json not found, trying legacy format...")}console.log("\u{1F6E0}\uFE0F [V2] Attempting to load /config/resources.static.json (legacy)...");let e=await fetch("/config/resources.static.json");if(!e.ok)return console.log("\u{1F6E0}\uFE0F [V2] No local static resources found"),null;let t=await e.json();return console.log("\u{1F6E0}\uFE0F [V2] \u2705 Loaded legacy static resources:",t),t}catch(n){return console.error("\u{1F6E0}\uFE0F [V2] \u274C Error loading static resources:",n),null}},we=n=>{if(typeof document=="undefined")return;let e=document.querySelector('meta[name="'.concat(n,'"]'));return(e==null?void 0:e.getAttribute("content"))||void 0},rn=()=>{if(typeof window!="undefined"&&window.__TAGADA_PLUGIN_CONFIG__)return window.__TAGADA_PLUGIN_CONFIG__;try{let n=we("x-plugin-config");if(n)return JSON.parse(decodeURIComponent(n))}catch(n){}return{}};var sn=async()=>{try{if(typeof document=="undefined")return null;let n=we("x-plugin-store-id"),e=we("x-plugin-account-id");if(!n)return null;let t=we("x-plugin-base-path")||"/",i=rn();e||console.warn("\u26A0\uFE0F Plugin config: Account ID not found in meta tags");let o={storeId:n,accountId:e,basePath:t,config:i};return console.log("\u{1F680} [HIGHEST PRIORITY] Plugin config loaded from meta tags (runtime injected config):",{storeId:n,accountId:e,basePath:t,configKeys:Object.keys(i),configSize:JSON.stringify(i).length}),o}catch(n){return console.warn("\u26A0\uFE0F Error loading production config from meta tags:",n),null}},dt=async(n="default",e)=>{var s,a;console.log("\u{1F527} [V2] loadPluginConfig called with variant:",n);let t=await on(),i=await sn();if(i){let c=b(h({},i),{staticResources:t!=null?t:void 0});return console.log("\u2705 [V2] Using INJECTED config from meta tags (HIGHEST PRIORITY)"),c}if(e){let c={storeId:e.storeId,accountId:e.accountId,basePath:(s=e.basePath)!=null?s:"/",config:(a=e.config)!=null?a:{},staticResources:t!=null?t:void 0};return console.log("\u2705 [V2] Using raw config parameter (PRIORITY 2)"),c}let o=await ln();if(o){let c=b(h({},o),{staticResources:t!=null?t:void 0});return console.log("\u2705 [V2] Using environment variables config (PRIORITY 3 - build time)"),c}let r=await nn(n);if(r){let c=b(h({},r),{staticResources:t!=null?t:void 0});return console.log("\u2705 [V2] Using local dev config files (PRIORITY 4)"),c}return console.warn("\u26A0\uFE0F [V2] No plugin config found - using defaults"),{basePath:"/",config:{},staticResources:t!=null?t:void 0}};async function an(n="default",e){try{if(!Y())return null;if(e)return e;let t=["/config/".concat(n,".config.json"),"/config/".concat(n,".tgd.json"),"/config/".concat(n,".json")];for(let i of t)try{let o=await fetch(i);if(o.ok)return await o.json()}catch(o){continue}return console.warn("\u26A0\uFE0F [loadLocalConfig] No config found for '".concat(n,"'")),null}catch(t){return console.error("[loadLocalConfig] Error loading config:",t),null}}async function ln(){try{if(!Y())return;let n=F("TAGADA_STORE_ID"),e=F("TAGADA_ACCOUNT_ID"),t=F("TAGADA_BASE_PATH"),i=F("TAGADA_CONFIG_NAME");if(!n||!e)return;let o=await an(i);if(!o)return;let r={storeId:n,accountId:e,basePath:t||"/",config:o};return console.log("\u{1F6E0}\uFE0F [createRawPluginConfig] Using environment variables (build-time config):",{hasStoreId:!!r.storeId,hasAccountId:!!r.accountId,basePath:r.basePath,hasConfig:!!r.config}),r}catch(n){console.error("[createRawPluginConfig] Error creating config:",n);return}}ue();j();j();var Ae=new Map,Pe=new Set;function cn(){return typeof window=="undefined"?null:new URLSearchParams(window.location.search).get("authCode")}async function ut(n,e,t,i=!1){if(Pe.has(n))throw i&&console.log("[AuthHandoff] Code already resolved, skipping duplicate request"),new Error("Auth code already resolved");let o=Ae.get(n);if(o)return i&&console.log("[AuthHandoff] Resolution already in progress, waiting for existing request"),o;i&&console.log("[AuthHandoff] Resolving authCode:",n.substring(0,15)+"...");let r=(async()=>{try{let s=await fetch("".concat(t,"/api/v1/cms/auth/resolve-handoff"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:n,storeId:e})});if(!s.ok){let c=await s.json().catch(()=>({message:"Unknown error"}));throw new Error(c.message||"Failed to resolve auth handoff: ".concat(s.status))}let a=await s.json();return i&&console.log("[AuthHandoff] \u2705 Resolved successfully:",{customerId:a.customer.id,role:a.customer.role,hasContext:Object.keys(a.context).length>0}),i&&console.log("[AuthHandoff] Storing new token (overriding existing)"),x(a.token),dn(i),Pe.add(n),a}catch(s){throw console.error("[AuthHandoff] \u274C Failed to resolve:",s),s}finally{Ae.delete(n)}})();return Ae.set(n,r),r}function dn(n=!1){if(typeof window=="undefined")return;let e=new URL(window.location.href);e.searchParams.has("authCode")&&(e.searchParams.delete("authCode"),window.history.replaceState({},"",e.pathname+e.search+e.hash),n&&console.log("[AuthHandoff] Cleaned authCode from URL"))}function ft(){let n=cn();return!(!n||!n.startsWith("ah_")||Pe.has(n))}var ve=class{constructor(e={}){this.bus=new Ie;this.eventDispatcher=new $;this.tokenPromise=null;this.tokenResolver=null;this.isInitializingSession=!1;this.lastSessionInitError=null;this.sessionInitRetryCount=0;this.MAX_SESSION_INIT_RETRIES=3;var a,c,p,m;this.config=e,this.instanceId=Math.random().toString(36).substr(2,9),this.boundHandleStorageChange=this.handleStorageChange.bind(this),this.boundHandlePageshow=l=>{if(l.persisted)if(this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Page restored from BFcache (back button), re-initializing funnel...")),this.funnel&&this.state.session&&this.state.store){this.funnel.resetInitialization();let f=this.getAccountId(),d=new URLSearchParams(typeof window!="undefined"?window.location.search:"").get("funnelId")||void 0;this.funnel.autoInitialize({customerId:this.state.session.customerId,sessionId:this.state.session.sessionId},{id:this.state.store.id,accountId:f},d).catch(w=>{console.error("[TagadaClient] Funnel re-initialization failed:",w)})}else this.sessionInitRetryCount=0,this.initialize()},console.log("[TagadaClient ".concat(this.instanceId,"] Initializing...")),console.log("[TagadaClient ".concat(this.instanceId,"] Config:"),{debugMode:e.debugMode,hasRawPluginConfig:!!e.rawPluginConfig,rawPluginConfig:e.rawPluginConfig,features:e.features}),Ke(this.config.debugMode)&&this.config.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Preview mode active - state cleared"));let i=this.resolveEnvironment(),o=Oe(i);e.customApiConfig&&(o=b(h(h({},o),e.customApiConfig),{apiConfig:h(h({},o.apiConfig),e.customApiConfig.apiConfig)}),this.config.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Applied custom API config:"),o.apiConfig.baseUrl)),this.state={auth:{isAuthenticated:!1,isLoading:!1,customer:null,session:null},session:null,customer:null,locale:{locale:"en-US",language:"en",region:"US",messages:{}},currency:{code:"USD",symbol:"$",name:"US Dollar"},store:null,environment:o,isLoading:!0,isInitialized:!1,isSessionInitialized:!1,pluginConfig:{basePath:"/",config:{}},pluginConfigLoading:!0,debugMode:(a=e.debugMode)!=null?a:i!=="production",token:null},console.log("[TagadaClient ".concat(this.instanceId,"] Initial state:"),{pluginConfigLoading:this.state.pluginConfigLoading,hasRawPluginConfig:!!e.rawPluginConfig}),this.apiClient=new Ce({baseURL:o.apiConfig.baseUrl});let r=(c=e.features)==null?void 0:c.funnel;if(r!==!1){let l=typeof r=="object"?r:{};this.funnel=new ne({apiClient:this.apiClient,debugMode:this.state.debugMode,pluginConfig:this.state.pluginConfig,environment:this.state.environment,autoRedirect:l.autoRedirect,funnelId:(p=e.rawPluginConfig)==null?void 0:p.funnelId,stepId:(m=e.rawPluginConfig)==null?void 0:m.stepId})}this.apiClient.setTokenProvider(this.waitForToken.bind(this)),typeof window!="undefined"&&(window.addEventListener("storage",this.boundHandleStorageChange),window.addEventListener("pageshow",this.boundHandlePageshow)),this.setupConfigHotReload(),this.initialize()}destroy(){typeof window!="undefined"&&(window.removeEventListener("storage",this.boundHandleStorageChange),window.removeEventListener("pageshow",this.boundHandlePageshow)),this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Destroyed")),this.eventDispatcher.clear(),this.bus.clear()}handleStorageChange(){if(X()===this.state.token){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Token unchanged (ignoring event)"));return}if(this.isInitializingSession){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Session initialization in progress, skipping storage change"));return}if(this.sessionInitRetryCount>=this.MAX_SESSION_INIT_RETRIES&&this.lastSessionInitError){this.state.debugMode&&console.error("[TagadaClient ".concat(this.instanceId,"] Max session init retries reached, giving up"),this.lastSessionInitError);return}this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Storage changed, re-initializing token...")),this.initializeToken()}subscribe(e){return this.eventDispatcher.subscribe(e)}getState(){return this.state}updateState(e){this.state=h(h({},this.state),e),this.eventDispatcher.notify(this.state)}resolveEnvironment(){return this.config.environment?this.config.environment:J()}async initialize(){try{await this.initializePluginConfig(),this.state.pluginConfig.storeId?await this.initializeToken():(console.warn("[TagadaClient] No store ID found in plugin config. Skipping token initialization."),this.updateState({isLoading:!1,isInitialized:!0}))}catch(e){console.error("[TagadaClient] Initialization failed:",e),this.updateState({isLoading:!1,isInitialized:!0})}}async initializePluginConfig(){if(console.log("[TagadaClient ".concat(this.instanceId,"] initializePluginConfig called"),{pluginConfigLoading:this.state.pluginConfigLoading,hasRawPluginConfig:!!this.config.rawPluginConfig}),!this.state.pluginConfigLoading){console.log("[TagadaClient ".concat(this.instanceId,"] Plugin config already loading or loaded, skipping..."));return}try{let e=this.config.localConfig||"default";console.log("[TagadaClient ".concat(this.instanceId,"] Loading plugin config with variant: ").concat(e));let t=await dt(e,this.config.rawPluginConfig);console.log("[TagadaClient ".concat(this.instanceId,"] Plugin config loaded:"),t),this.updateState({pluginConfig:t,pluginConfigLoading:!1}),this.funnel&&this.funnel.setConfig({pluginConfig:t,environment:this.state.environment})}catch(e){console.error("[TagadaClient] Failed to load plugin config:",e),this.updateState({pluginConfig:{basePath:"/",config:{}},pluginConfigLoading:!1})}}async initializeToken(){var e;if(ft()){let t=this.state.pluginConfig.storeId;if(!t)return console.error("[TagadaClient] Cannot resolve authCode: storeId not found in config"),this.fallbackToNormalFlow();console.log("[TagadaClient ".concat(this.instanceId,"] \u{1F510} Cross-domain auth detected, resolving..."));try{let i=new URLSearchParams(window.location.search).get("authCode");if(!i)return this.fallbackToNormalFlow();let o=await ut(i,t,this.state.environment.apiConfig.baseUrl,this.state.debugMode);console.log("[TagadaClient ".concat(this.instanceId,"] \u2705 Auth handoff resolved:"),{customerId:o.customer.id,role:o.customer.role,hasContext:Object.keys(o.context).length>0}),this.setToken(o.token);let r=ie(o.token);r?(this.updateState({session:r}),await this.initializeSession(r),(e=o.context)!=null&&e.funnelSessionId&&this.funnel&&this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Restoring funnel session from handoff context:"),o.context.funnelSessionId)):(console.error("[TagadaClient] Failed to decode token from handoff"),this.updateState({isInitialized:!0,isLoading:!1}));return}catch(i){console.error("[TagadaClient ".concat(this.instanceId,"] \u274C Auth handoff failed, falling back to normal flow:"),i)}}await this.fallbackToNormalFlow()}async fallbackToNormalFlow(){let t=new URLSearchParams(typeof window!="undefined"?window.location.search:"").get("token");t&&(this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] \u{1F512} URL token detected, setting immediately to prevent race condition")),this.apiClient.updateToken(t),x(t));let i=X();console.log("[TagadaClient ".concat(this.instanceId,"] Initializing token (normal flow)..."),{hasExistingToken:!!i,hasQueryToken:!!t,storeId:this.state.pluginConfig.storeId});let o=null,r=!1;if(t?(o=t,r=!0):i&&!ct(i)&&(o=i),o){this.setToken(o),r&&(this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Persisting query token to storage...")),x(o));let s=ie(o);s?(this.updateState({session:s}),await this.initializeSession(s)):(console.error("[TagadaClient] Failed to decode token"),this.updateState({isInitialized:!0,isLoading:!1}))}else{let s=this.state.pluginConfig.storeId;console.log("[TagadaClient ".concat(this.instanceId,"] No existing token, creating anonymous token..."),{hasStoreId:!!s,storeId:s}),s?await this.createAnonymousToken(s):(console.warn("[TagadaClient ".concat(this.instanceId,"] No storeId in plugin config, skipping anonymous token creation")),this.updateState({isInitialized:!0,isLoading:!1}))}}setToken(e){this.apiClient.updateToken(e),this.updateState({token:e}),this.tokenResolver&&(this.tokenResolver(e),this.tokenPromise=null,this.tokenResolver=null)}waitForToken(){return this.apiClient.getCurrentToken()?Promise.resolve(this.apiClient.getCurrentToken()):(this.tokenPromise||(this.tokenPromise=new Promise(e=>{this.tokenResolver=e})),this.tokenPromise)}async createAnonymousToken(e){if(typeof window!="undefined"){let i=new URLSearchParams(window.location.search).get("token");if(i){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] \u{1F512} URL has token, skipping anonymous token creation")),this.setToken(i),x(i);let o=ie(i);o&&(this.updateState({session:o}),await this.initializeSession(o));return}}if(this.isInitializingSession){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Session initialization in progress, skipping anonymous token creation"));return}try{let t=ee();this.state.debugMode&&console.log("[TagadaClient] Creating anonymous token for store:",e,{draft:t});let i=await this.apiClient.post("/api/v1/cms/session/anonymous",{storeId:e,role:"anonymous",draft:t},{skipAuth:!0});this.setToken(i.token),x(i.token);let o=ie(i.token);o&&(this.updateState({session:o}),await this.initializeSession(o)),this.updateState({isSessionInitialized:!0})}catch(t){console.error("[TagadaClient] Failed to create anonymous token:",t),this.updateState({isInitialized:!0,isLoading:!1})}}async initializeSession(e){var t,i,o,r,s,a,c,p,m,l,f;if(this.isInitializingSession){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Session initialization already in progress, skipping"));return}this.isInitializingSession=!0;try{this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Initializing session..."),{sessionId:e.sessionId});let u=await at(),d=lt(),w=st(),g=ee(),I=new URLSearchParams(window.location.search).get("draft");I!==null&&Ee(I==="true");let R={storeId:e.storeId,accountId:e.accountId,customerId:e.customerId,role:e.role,browserLocale:w,queryLocale:d.locale,queryCurrency:d.currency,utmSource:d.utmSource,utmMedium:d.utmMedium,utmCampaign:d.utmCampaign,gclid:d.gclid,browser:u.userAgent.browser.name,browserVersion:u.userAgent.browser.version,os:u.userAgent.os.name,osVersion:u.userAgent.os.version,deviceType:(t=u.userAgent.device)==null?void 0:t.type,deviceModel:(i=u.userAgent.device)==null?void 0:i.model,deviceVendor:(o=u.userAgent.device)==null?void 0:o.vendor,userAgent:u.userAgent.name,engineName:u.userAgent.engine.name,engineVersion:u.userAgent.engine.version,cpuArchitecture:u.userAgent.cpu.architecture,isBot:(s=(r=u.flags)==null?void 0:r.isBot)!=null?s:!1,isChromeFamily:(c=(a=u.flags)==null?void 0:a.isChromeFamily)!=null?c:!1,isStandalonePWA:(m=(p=u.flags)==null?void 0:p.isStandalonePWA)!=null?m:!1,isAppleSilicon:(f=(l=u.flags)==null?void 0:l.isAppleSilicon)!=null?f:!1,screenWidth:u.screenResolution.width,screenHeight:u.screenResolution.height,timeZone:u.timeZone,draft:g,fetchMessages:!1},y=await this.apiClient.post("/api/v1/cms/session/v2/init",R);this.lastSessionInitError=null,this.sessionInitRetryCount=0,this.updateSessionState(y,e),this.updateState({isInitialized:!0,isSessionInitialized:!0,isLoading:!1}),this.state.debugMode&&console.log("[TagadaClient] Session initialized successfully")}catch(u){this.lastSessionInitError=u,this.sessionInitRetryCount++,console.error("[TagadaClient] Error initializing session (attempt ".concat(this.sessionInitRetryCount,"/").concat(this.MAX_SESSION_INIT_RETRIES,"):"),u),this.updateState({isInitialized:!0,isLoading:!1})}finally{this.isInitializingSession=!1}}updateSessionState(e,t){var s,a,c,p,m,l,f,u,d,w;if(e.store){let g=e.store,I=b(h({},e.store),{accountId:g.accountId||((s=this.state.pluginConfig)==null?void 0:s.accountId)||t.accountId||"",presentmentCurrencies:g.presentmentCurrencies||[e.store.currency||"USD"],chargeCurrencies:g.chargeCurrencies||[e.store.currency||"USD"]});this.updateState({store:I})}if(e.locale){let g={locale:e.locale,language:e.locale.split("-")[0],region:(a=e.locale.split("-")[1])!=null?a:"US",messages:(c=e.messages)!=null?c:{}};this.updateState({locale:g})}if(e.store){let g={code:e.store.currency,symbol:this.getCurrencySymbol(e.store.currency),name:this.getCurrencyName(e.store.currency)};this.updateState({currency:g})}let i={isAuthenticated:(m=(p=e.customer)==null?void 0:p.isAuthenticated)!=null?m:!1,isLoading:!1,customer:(l=e.customer)!=null?l:null,session:t};this.updateState({customer:(f=e.customer)!=null?f:null,auth:i});let o=(u=this.config.features)==null?void 0:u.funnel,r=typeof o=="object"&&o.skipAutoInit;if(this.funnel&&!r&&t.customerId&&((d=e.store)!=null&&d.id)){let g=e.store.accountId||((w=this.state.pluginConfig)==null?void 0:w.accountId)||t.accountId||"";if(g){let R=new URLSearchParams(typeof window!="undefined"?window.location.search:"").get("funnelId")||void 0;this.state.debugMode&&console.log("[TagadaClient] Auto-initializing funnel...",{customerId:t.customerId,storeId:e.store.id,accountId:g,funnelId:R||"auto-detect"}),this.funnel.autoInitialize({customerId:t.customerId,sessionId:t.sessionId},{id:e.store.id,accountId:g},R).catch(y=>{console.error("[TagadaClient] Funnel auto-initialization failed:",y)})}else console.warn("[TagadaClient] Cannot auto-initialize funnel: accountId is missing")}}getCurrencySymbol(e){return{USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$"}[e]||e}getCurrencyName(e){return{USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar"}[e]||e}getAccountId(){var e,t,i;return((e=this.state.store)==null?void 0:e.accountId)||((t=this.state.pluginConfig)==null?void 0:t.accountId)||((i=this.state.session)==null?void 0:i.accountId)||""}updatePluginConfig(e){this.state.debugMode&&console.log("[TagadaClient] Hot-reloading config:",e);let t=h(h({},this.state.pluginConfig.config),e);this.updateState({pluginConfig:b(h({},this.state.pluginConfig),{config:t})}),this.bus.emit("CONFIG_UPDATED",t),this.state.debugMode&&console.log("[TagadaClient] Config updated successfully")}setupConfigHotReload(){if(typeof window=="undefined")return;let e=t=>{var i,o;if(((i=t.data)==null?void 0:i.type)==="TAGADAPAY_CONFIG_UPDATE"){let{config:r}=t.data;this.state.debugMode&&console.log("[TagadaClient] Received config update from parent:",r),this.updatePluginConfig(r)}else if(((o=t.data)==null?void 0:o.type)==="APPLY_STYLES_TO_ELEMENT"){let{elementId:r,styles:s}=t.data;this.state.debugMode&&console.log("[TagadaClient] Received style application request:",{elementId:r,styles:s}),this.applyStylesToElement(r,s)}};window.addEventListener("message",e),this.state.debugMode&&console.log("[TagadaClient] Config hot-reload and style manipulation listeners enabled")}applyStylesToElement(e,t){if(typeof document=="undefined")return;let i="tagada-editor-highlight",o=document.getElementById(i);o&&o.remove();let r=l=>{var y;let u=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]).has(l.tagName.toLowerCase()),d=l;if(u){let T=l.parentElement;if((T==null?void 0:T.getAttribute("data-tagada-highlight-wrapper"))==="true"&&T instanceof HTMLElement)d=T;else{let v=document.createElement("div");v.setAttribute("data-tagada-highlight-wrapper","true");let oe=window.getComputedStyle(l),z=oe.display;if(z==="inline"?v.style.display="inline-block":v.style.display=z,v.style.position="relative",z==="inline"||z.includes("inline")){let D=oe.verticalAlign;D&&D!=="baseline"&&(v.style.verticalAlign=D)}["width","height","minWidth","minHeight","maxWidth","maxHeight","flex","flexGrow","flexShrink","flexBasis","gridColumn","gridRow","gridColumnStart","gridColumnEnd","gridRowStart","gridRowEnd","gridArea","alignSelf","justifySelf","boxSizing","gap","rowGap","columnGap","order","aspectRatio"].forEach(D=>{let W=D.replace(/([A-Z])/g,"-$1").toLowerCase(),A=oe.getPropertyValue(W);A&&A.trim()!==""&&(D==="flex"&&A!=="none"&&A!=="0 1 auto"?v.style.flex=A:D==="boxSizing"?v.style.boxSizing=A:v.style.setProperty(W,A))}),l.style&&["width","height","min-width","min-height","max-width","max-height","flex","flex-grow","flex-shrink","flex-basis","grid-column","grid-row","grid-column-start","grid-column-end","grid-row-start","grid-row-end","grid-area","align-self","justify-self","box-sizing","gap","row-gap","column-gap","order","aspect-ratio"].forEach(W=>{let A=l.style.getPropertyValue(W);A&&v.style.setProperty(W,A)}),(y=l.parentNode)==null||y.insertBefore(v,l),v.appendChild(l),d=v}}let w=getComputedStyle(u?l:d);(d.style.position==="static"||!d.style.position)&&(d.style.position="relative");let g=document.createElement("div");g.id=i,g.style.position="absolute",g.style.inset="0",g.style.pointerEvents="none",g.style.zIndex="9999",g.style.boxSizing="border-box",g.style.background="none",g.style.border="none",g.style.outline="none",g.style.margin="0",g.style.padding="0";let I=w.borderRadius;I&&(g.style.borderRadius=I),d.appendChild(g);let R=t||{boxShadow:"0 0 0 2px rgb(239 68 68)"};if(Object.entries(R).forEach(([T,q])=>{let v=T.includes("-")?T.replace(/-([a-z])/g,(oe,z)=>z.toUpperCase()):T;T.includes("-")?g.style.setProperty(T,q):g.style[v]=q}),l.scrollIntoView({behavior:"smooth",block:"center"}),this.state.debugMode){let T=Object.entries(R).map(([q,v])=>"".concat(q,": ").concat(v)).join("; ");console.log("[TagadaClient] Applied styles to highlight div of element #".concat(e,":"),T)}},s=5,a=1e3,c=0,p=l=>{let f=window.getComputedStyle(l);return f.display==="none"||f.visibility==="hidden"||f.opacity==="0"||l.hidden||l.offsetWidth===0||l.offsetHeight===0},m=()=>{let l=document.querySelectorAll('[editor-id~="'.concat(e,'"]'));if(l.length===0){if(c+=1,c>=s){this.state.debugMode&&console.warn('[TagadaClient] Element with editor-id containing "'.concat(e,'" not found after ').concat(s," attempts"));return}this.state.debugMode&&console.warn('[TagadaClient] Element with editor-id containing "'.concat(e,'" not found (attempt ').concat(c,"/").concat(s,"), retrying in ").concat(a/1e3,"s")),setTimeout(m,a);return}let f=null;if(l.length===1)f=l[0];else{for(let u=0;u<l.length;u++)if(!p(l[u])){f=l[u];break}f||(f=l[0])}f&&r(f)};m()}};pe();function un(){if(typeof window=="undefined"||typeof document=="undefined")return[];let n=P();return n!=null&&n.scripts?n.scripts.filter(e=>e.enabled):[]}function fn(n,e){let t=n.position||"body-end",i="tagada-stepconfig-script-".concat(e);if(document.getElementById(i))return;let o=n.content.trim(),r=o.match(/^<script[^>]*>([\s\S]*)<\/script>$/i);if(r&&(o=r[1].trim()),!o)return;let s="(function() {\n try {\n // Script: "+n.name+"\n"+o+'\n } catch (error) {\n console.error("[TagadaPay] StepConfig script error:", error);\n }\n})();',a=document.createElement("script");switch(a.id=i,a.setAttribute("data-tagada-stepconfig-script","true"),a.setAttribute("data-script-name",n.name),a.textContent=s,t){case"head-start":document.head.firstChild?document.head.insertBefore(a,document.head.firstChild):document.head.appendChild(a);break;case"head-end":document.head.appendChild(a);break;case"body-start":document.body.firstChild?document.body.insertBefore(a,document.body.firstChild):document.body.appendChild(a);break;case"body-end":default:document.body.appendChild(a);break}}function gt(){let n=un();n.length!==0&&n.forEach((e,t)=>{fn(e,t)})}if(typeof window!="undefined"&&typeof document!="undefined"){let n=()=>{document.body?gt():document.addEventListener("DOMContentLoaded",gt,{once:!0})};"requestIdleCallback"in window?window.requestIdleCallback(n,{timeout:100}):setTimeout(n,0)}function pt(n={}){return new ve(n)}j();var _e="1.0.0";function mt(n){return typeof window=="undefined"?null:new URLSearchParams(window.location.search).get(n)}function S(n,...e){n&&console.log("[TagadaTracker]",...e)}function ht(...n){console.warn("[TagadaTracker]",...n)}function gn(n){if(!n.storeId||typeof n.storeId!="string")throw new Error("TagadaTracker: storeId is required and must be a non-empty string.");if(!n.accountId||typeof n.accountId!="string")throw new Error("TagadaTracker: accountId is required and must be a non-empty string.");if(!n.stepId||typeof n.stepId!="string")throw new Error("TagadaTracker: stepId is required and must be a non-empty string.");if(n.apiBaseUrl)try{new URL(n.apiBaseUrl)}catch(e){throw new Error('TagadaTracker: apiBaseUrl is not a valid URL: "'.concat(n.apiBaseUrl,'"'))}}async function pn(n,e,t){let i;for(let o=0;o<=e;o++)try{return await n()}catch(r){if(i=r instanceof Error?r:new Error(String(r)),o<e){let s=Math.min(1e3*2**o,8e3);S(t,"Retry ".concat(o+1,"/").concat(e," in ").concat(s,"ms...")),await new Promise(a=>setTimeout(a,s))}}throw i}var Se=class{constructor(){this.config=null;this.client=null;this.initialized=!1;this.initializing=!1;this.unsubscribe=null;this.version=_e}async init(e){var i,o;if(this.initialized)return S(e.debug||!1,"Already initialized \u2014 returning existing session."),this.getSession();if(this.initializing)return S(e.debug||!1,"Initialization in progress \u2014 skipping duplicate call."),null;this.initializing=!0,this.config=h({debug:!1},e);let t=this.config.debug;try{gn(this.config)}catch(r){this.initializing=!1;let s=r instanceof Error?r:new Error(String(r));if(this.config.onError)return this.config.onError(s),null;throw s}S(t,"\u{1F680} Initializing external tracker v".concat(_e),{storeId:e.storeId,accountId:e.accountId,stepId:e.stepId,funnelId:e.funnelId});try{let r=mt("token");r&&(x(r),S(t,"\u{1F511} Bootstrapped token from URL")),this.client=pt({debugMode:t,features:{funnel:{skipAutoInit:!0}},rawPluginConfig:{storeId:this.config.storeId,accountId:this.config.accountId},customApiConfig:this.config.apiBaseUrl?{apiConfig:{baseUrl:this.config.apiBaseUrl.trim()}}:void 0}),await this.waitForClientReady();let s=await pn(()=>this.initializeFunnel(),2,t);S(t,"\u2705 Session initialized:",s),this.initialized=!0;let a=this.getSession();return a&&((o=(i=this.config).onReady)==null||o.call(i,a)),a}catch(r){let s=r instanceof Error?r:new Error(String(r));if(S(t,"\u274C Initialization failed:",s),this.config.onError)return this.config.onError(s),null;throw s}finally{this.initializing=!1}}getSession(){var t,i;if(!((i=(t=this.client)==null?void 0:t.funnel)!=null&&i.state.context))return null;let e=this.client.funnel.state.context;return{sessionId:e.sessionId,customerId:e.customerId,storeId:e.storeId,funnelId:e.funnelId,currentStepId:e.currentStepId,cmsToken:this.client.state.token||void 0}}isReady(){var e,t;return this.initialized&&!!((t=(e=this.client)==null?void 0:e.funnel)!=null&&t.state.context)}async navigate(e){if(!this.isReady())throw new Error("TagadaTracker: not initialized. Call init() first.");S(this.config.debug,"\u{1F680} Navigating:",e);let t=e.autoRedirect!==!1;try{let i=await this.client.funnel.navigate({type:e.eventType,data:e.eventData||{}},{autoRedirect:!1});return i!=null&&i.url?(S(this.config.debug,"\u2705 Navigation result:",i.url),t&&typeof window!="undefined"&&(window.location.href=e.returnUrl||i.url),{url:i.url}):null}catch(i){throw S(this.config.debug,"\u274C Navigation failed:",i),i}}async trackEvent(e){if(!this.isReady()){ht("trackEvent called before init \u2014 event dropped:",e.name);return}S(this.config.debug,"\u{1F4CA} Tracking event:",e.name,e.data);try{await this.client.funnel.navigate({type:e.name,data:e.data||{}},{autoRedirect:!1})}catch(t){S(this.config.debug,"\u26A0\uFE0F Event tracking failed (non-critical):",e.name)}}getCustomerId(){var e,t,i,o,r;return((t=(e=this.client)==null?void 0:e.state.auth.customer)==null?void 0:t.id)||((r=(o=(i=this.client)==null?void 0:i.funnel)==null?void 0:o.state.context)==null?void 0:r.customerId)||null}getFunnelSessionId(){var e,t,i;return((i=(t=(e=this.client)==null?void 0:e.funnel)==null?void 0:t.state.context)==null?void 0:i.sessionId)||null}buildUrl(e,t){let i=this.getSession();if(!i)return e;let o=new URL(e,typeof window!="undefined"?window.location.origin:void 0);return o.searchParams.set("funnelSessionId",i.sessionId),i.cmsToken&&o.searchParams.set("token",i.cmsToken),i.funnelId&&o.searchParams.set("funnelId",i.funnelId),o.searchParams.set("storeId",i.storeId),t&&Object.entries(t).forEach(([r,s])=>{o.searchParams.set(r,s)}),o.toString()}getClient(){return this.client}async reset(e){var o,r;if(!this.client||!this.config)throw new Error("TagadaTracker: not initialized. Call init() first.");S(this.config.debug,"\u{1F504} Resetting to step:",e),this.config.stepId=e;let t=await this.initializeFunnel(),i=this.getSession();return i&&((r=(o=this.config).onReady)==null||r.call(o,i)),i}destroy(){var e,t;this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.client&&((t=(e=this.client).destroy)==null||t.call(e)),this.client=null,this.config=null,this.initialized=!1,this.initializing=!1,S(!1,"\u{1F5D1}\uFE0F Tracker destroyed")}async waitForClientReady(){if(this.client)return new Promise(e=>{var o;if((o=this.client)!=null&&o.state.isInitialized){e();return}let t=!1,i=setTimeout(()=>{var r;t||(t=!0,S(((r=this.config)==null?void 0:r.debug)||!1,"\u23F1\uFE0F Client ready timeout \u2014 proceeding"),e())},1e4);this.unsubscribe=this.client.subscribe(()=>{var r;!t&&((r=this.client)!=null&&r.state.isInitialized)&&(t=!0,clearTimeout(i),e())})})}async initializeFunnel(){var s,a,c;if(!((s=this.client)!=null&&s.funnel))return null;let e=(a=this.client.state.auth.customer)==null?void 0:a.id,t=(c=this.client.state.auth.session)==null?void 0:c.sessionId;!e&&!t&&ht("No auth session available \u2014 funnel init may fail.");let i={customerId:e||"anon_placeholder",sessionId:t||"sess_placeholder"},o={id:this.config.storeId,accountId:this.config.accountId},r=this.config.stepId;return S(this.config.debug,"\u{1F50D} Initializing funnel at step:",r),this.client.funnel.initialize(i,o,this.config.funnelId||mt("funnelId")||void 0,r)}},yt=new Se;typeof window!="undefined"&&(window.TagadaTracker=yt);return bt(mn);})();
6
+ "use strict";var TagadaTrackerBundle=(()=>{var re=Object.defineProperty,Ct=Object.defineProperties,It=Object.getOwnPropertyDescriptor,wt=Object.getOwnPropertyDescriptors,vt=Object.getOwnPropertyNames,Fe=Object.getOwnPropertySymbols;var Ne=Object.prototype.hasOwnProperty,St=Object.prototype.propertyIsEnumerable;var De=(n,e,t)=>e in n?re(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,h=(n,e)=>{for(var t in e||(e={}))Ne.call(e,t)&&De(n,t,e[t]);if(Fe)for(var t of Fe(e))St.call(e,t)&&De(n,t,e[t]);return n},b=(n,e)=>Ct(n,wt(e));var N=(n,e)=>()=>(n&&(e=n(n=0)),e);var Te=(n,e)=>{for(var t in e)re(n,t,{get:e[t],enumerable:!0})},Tt=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vt(e))!Ne.call(n,o)&&o!==t&&re(n,o,{get:()=>e[o],enumerable:!(i=It(e,o))||i.enumerable});return n};var bt=n=>Tt(re({},"__esModule",{value:!0}),n);function Ue(n){var i;if(typeof document=="undefined")return null;let t="; ".concat(document.cookie).split("; ".concat(n,"="));return t.length===2&&((i=t.pop())==null?void 0:i.split(";").shift())||null}function Oe(n="local"){let e=Le[n];if(!e)return console.warn("Unknown environment: ".concat(n,". Falling back to local.")),{environment:"local",apiConfig:Le.local};let t=null;if(typeof window!="undefined"&&(t=new URLSearchParams(window.location.search).get("tagadaClientBaseUrl"),!t))try{t=localStorage.getItem("tgd_client_base_url")||Ue("tgd_client_base_url")}catch(o){}return t?(console.log("[SDK] Using custom API base URL override: ".concat(t)),{environment:n,apiConfig:b(h({},e),{baseUrl:t})}):{environment:n,apiConfig:e}}function J(){var o;if(console.log("[SDK] detectEnvironment() called"),typeof window=="undefined")return"local";let e=new URLSearchParams(window.location.search).get("tagadaClientEnv");if(e&&(e==="production"||e==="development"||e==="local"))return console.log("[SDK] Using explicit environment override: ".concat(e)),e;try{let r=localStorage.getItem("tgd_client_env")||Ue("tgd_client_env");if(r&&(r==="production"||r==="development"||r==="local"))return console.log("[SDK] Using persisted environment override: ".concat(r)),r}catch(r){}let t=window.location.hostname,i=window.location.href;if(console.log('[SDK] detectEnvironment() - hostname: "'.concat(t,'"')),t==="localhost"||t.startsWith("127.")||t.startsWith("192.168.")||t.startsWith("10.")||t.includes(".local")||t===""||t==="0.0.0.0"||t.includes("ngrok-free.dev")||t.includes("ngrok-free.app")||t.includes("ngrok.io")||t.includes("ngrok.app")||t.includes(".loclx.io")){if(console.log("[SDK] detectEnvironment() - returning LOCAL"),typeof window!="undefined"&&((o=window==null?void 0:window.__TAGADA_ENV__)!=null&&o.TAGADA_ENVIRONMENT)){let r=window.__TAGADA_ENV__.TAGADA_ENVIRONMENT.toLowerCase();if(r==="production"||r==="development"||r==="local")return console.log("[SDK] Local override detected: ".concat(r)),r}return"local"}return t.includes("tagada.io")||t.includes("tagadapay.com")||t.includes("yourproductiondomain.com")?"production":t.includes("tagada.dev")||t.includes("tagadapay.dev")||t.includes("vercel.app")||t.includes("netlify.app")||t.includes("surge.sh")||t.includes("github.io")||t.includes("herokuapp.com")||t.includes("railway.app")||i.includes("?env=dev")||i.includes("?dev=true")||i.includes("#dev")?"development":(console.warn("[SDK] Unknown domain: ".concat(t,", defaulting to production")),"production")}function Y(n=!1){return J()!=="local"?!1:n&&typeof window!="undefined"?!window.location.hostname.includes(".cdn."):!0}var Le,se=N(()=>{"use strict";Le={production:{baseUrl:"https://api.tagada.io",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionInitAsync:"/api/v1/checkout/session/init-async",sessionStatus:"/api/v1/checkout/session/status",asyncStatus:"/api/public/v1/checkout/async-status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}},development:{baseUrl:"https://api.tagada.dev",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionInitAsync:"/api/v1/checkout/session/init-async",sessionStatus:"/api/v1/checkout/session/status",asyncStatus:"/api/public/v1/checkout/async-status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}},local:{baseUrl:"http://app.localhost:3000",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionInitAsync:"/api/v1/checkout/session/init-async",sessionStatus:"/api/v1/checkout/session/status",asyncStatus:"/api/public/v1/checkout/async-status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}}}});var ae,Me=N(()=>{"use strict";ae=class{constructor(e){this.apiClient=e}async initialize(e){return this.apiClient.post("/api/v1/funnel/initialize",e)}async navigate(e){return this.apiClient.post("/api/v1/funnel/navigate",e)}async updateContext(e,t){return this.apiClient.patch("/api/v1/funnel/context/".concat(e),t)}async endSession(e){return this.apiClient.delete("/api/v1/funnel/session/".concat(e))}async getSession(e,t,i){let o=new URLSearchParams;t&&o.append("currentUrl",t),i&&o.append("includeDebugData","true");let r="/api/v1/funnel/session/".concat(e).concat(o.toString()?"?".concat(o):"");return this.apiClient.get(r)}}});var $,be=N(()=>{"use strict";$=class{constructor(){this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){this.listeners.forEach(t=>{try{t(e)}catch(i){console.error("Error in event listener:",i)}})}clear(){this.listeners.clear()}}});function x(n){if(typeof window!="undefined")try{let t=localStorage.getItem(le)!==n;localStorage.setItem(le,n),t&&window.dispatchEvent(new Event("storage"))}catch(e){console.error("Failed to save token to localStorage:",e)}}function X(){if(typeof window!="undefined")try{return localStorage.getItem(le)}catch(n){return console.error("Failed to get token from localStorage:",n),null}return null}function B(){if(typeof window!="undefined")try{localStorage.removeItem(le)}catch(n){console.error("Failed to clear token from localStorage:",n)}}var le,j=N(()=>{"use strict";le="cms_token"});function ze(n){typeof document!="undefined"&&(document.cookie="".concat(xe,"=").concat(n,"; path=/; max-age=2592000; SameSite=Lax"))}function $e(){if(typeof document=="undefined")return;let n=document.cookie.split("; ").find(e=>e.startsWith("".concat(xe,"=")));return n?n.split("=")[1]:void 0}function ce(){typeof document!="undefined"&&(document.cookie="".concat(xe,"=; path=/; max-age=0"))}var xe,de=N(()=>{"use strict";xe="tgd-funnel-session-id"});function G(n){if(typeof window=="undefined")return null;try{return localStorage.getItem(n)}catch(e){return null}}function K(n,e){if(typeof window!="undefined")try{localStorage.setItem(n,e)}catch(t){}}function Z(n){var i;if(typeof document=="undefined")return null;let t=document.cookie.split(";").find(o=>o.trim().startsWith("".concat(n,"=")));return t?(i=t.split("=")[1])==null?void 0:i.trim():null}function Q(n,e,t=86400){if(typeof document!="undefined"){if(n==="tgd_draft"||n==="tgd-draft"){console.warn("\u{1F6E1}\uFE0F [SDK] Blocked attempt to set ".concat(n," as cookie - this should only be in localStorage"));return}document.cookie="".concat(n,"=").concat(e,"; path=/; max-age=").concat(t)}}function je(n){typeof document!="undefined"&&(document.cookie="".concat(n,"=; path=/; max-age=0"))}function U(){if(typeof window=="undefined")return{};let n=new URLSearchParams(window.location.search),e,t=n.get("draft");if(t!==null)e=t==="true";else{let y=G(C.DRAFT);y!==null&&(e=y==="true")}let i,o=n.get("funnelTracking");if(o!==null)i=o!=="false";else{let y=G(C.FUNNEL_TRACKING)||Z(C.FUNNEL_TRACKING);y!==null&&(i=y!=="false")}let r=n.get("token")||X()||null,s=n.get("funnelSessionId")||null,a=n.get("funnelId")||null,c,p=n.get("funnelEnv");p&&(p==="staging"||p==="production")&&(c=p);let m=n.get("forceReset")==="true",l,f=n.get("tagadaClientEnv");if(f&&(f==="production"||f==="development"||f==="local"))l=f;else{let y=G(C.CLIENT_ENV)||Z(C.CLIENT_ENV);y&&(y==="production"||y==="development"||y==="local")&&(l=y)}let u,d=n.get("tagadaClientBaseUrl");if(d)u=d;else{let y=G(C.CLIENT_BASE_URL)||Z(C.CLIENT_BASE_URL);y&&(u=y)}let w,g=n.get("currency");if(g)w=g;else{let y=G(C.CURRENCY)||Z(C.CURRENCY);y&&(w=y)}let I,R=n.get("locale");if(R)I=R;else{let y=G(C.LOCALE)||Z(C.LOCALE);y&&(I=y)}return{forceReset:m,token:r,funnelSessionId:s,funnelId:a,draft:e,funnelTracking:i,funnelEnv:c,tagadaClientEnv:l,tagadaClientBaseUrl:u,currency:w,locale:I}}function ee(){var e;return(e=U().draft)!=null?e:!1}function Ee(n){if(typeof window!="undefined")if(n)K(C.DRAFT,"true");else try{localStorage.removeItem(C.DRAFT)}catch(e){}}function Ge(n=!1){let e=null;typeof window!="undefined"&&(e=new URLSearchParams(window.location.search).get("token"));let t=U(),i=t.forceReset||!1;if(!i&&!t.token)return Be(),!1;n&&(console.log("[SDK] Detected params:",t),console.log("[SDK] URL token (direct read):",e?e.substring(0,20)+"...":"none")),i&&(n&&console.log("[SDK] Force reset: Clearing all stored state"),B(),ce(),typeof window!="undefined"&&window.localStorage&&Object.keys(localStorage).forEach(s=>{(s.startsWith("tagadapay_")||s.startsWith("tgd_"))&&(n&&console.log("[SDK] Clearing localStorage: ".concat(s)),localStorage.removeItem(s))}));let o=e||t.token;return o!=null?(n&&console.log("[SDK] Setting token from URL:",o.substring(0,20)+"..."),o===""||o==="null"?B():(x(o),n&&console.log("[SDK] \u2705 Token set in localStorage immediately after clear"))):i&&(n&&console.log("[SDK] Force reset mode (no token in URL)"),B()),Be(),t.funnelSessionId&&n&&console.log("[SDK] Using funnelSessionId from URL:",t.funnelSessionId),i}function Be(){if(typeof window=="undefined")return;let n=new URLSearchParams(window.location.search),e=n.get("draft");e!==null&&Ee(e==="true");let t=n.get("funnelTracking");t!==null&&xt(t!=="false");let i=n.get("tagadaClientEnv");i&&(i==="production"||i==="development"||i==="local")&&Et(i);let o=n.get("tagadaClientBaseUrl");o&&kt(o);let r=n.get("currency");r&&(K(C.CURRENCY,r.toUpperCase()),Q(C.CURRENCY,r.toUpperCase(),86400));let s=n.get("locale");s&&(K(C.LOCALE,s),Q(C.LOCALE,s,86400))}function xt(n){if(typeof window=="undefined")return;let e=n?"true":"false";K(C.FUNNEL_TRACKING,e),Q(C.FUNNEL_TRACKING,e,86400)}function Et(n){typeof window!="undefined"&&(K(C.CLIENT_ENV,n),Q(C.CLIENT_ENV,n,86400))}function Ke(){if(typeof window!="undefined")try{localStorage.removeItem(C.CLIENT_ENV),je(C.CLIENT_ENV)}catch(n){}}function kt(n){typeof window!="undefined"&&(K(C.CLIENT_BASE_URL,n),Q(C.CLIENT_BASE_URL,n,86400))}function Ve(){if(typeof window!="undefined")try{localStorage.removeItem(C.CLIENT_BASE_URL),je(C.CLIENT_BASE_URL)}catch(n){}}function He(){var e;return(e=U().funnelTracking)!=null?e:!0}var C,ue=N(()=>{"use strict";j();de();C={DRAFT:"tgd_draft",FUNNEL_TRACKING:"tgd_funnel_tracking",FORCE_RESET:"tgd_force_reset",CLIENT_ENV:"tgd_client_env",CLIENT_BASE_URL:"tgd_client_base_url",CURRENCY:"tgd_currency",LOCALE:"tgd_locale"}});var qe={};Te(qe,{injectPreviewModeIndicator:()=>At,isIndicatorInjected:()=>_t,removePreviewModeIndicator:()=>Pt});function ke(n){if(typeof window=="undefined"||typeof document=="undefined")return;let e=window.location.hostname,t=e.split("."),i=["",e,"."+e];for(let a=1;a<t.length;a++){let c=t.slice(a).join(".");i.push(c),i.push("."+c)}let o=window.location.pathname.split("/").filter(a=>a),r=["/"],s="";o.forEach(a=>{s+="/"+a,r.push(s)}),i.forEach(a=>{r.forEach(c=>{let p="".concat(n,"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=").concat(c),m=a?"; domain=".concat(a):"";document.cookie=p+m,document.cookie=p+m+"; secure",document.cookie=p+m+"; SameSite=None; secure",document.cookie=p+m+"; SameSite=Lax",document.cookie=p+m+"; SameSite=Strict"})})}function Rt(){if(typeof window=="undefined"||!confirm("\u{1F6AA} Leave Preview Mode?\n\nThis will clear ALL cookies and localStorage (including Shopify session, cart, and preview settings) and reload the page.\n\nAre you sure?"))return;let e=new URL(window.location.href);["draft","funnelEnv","funnelTracking","tagadaClientEnv","tagadaClientBaseUrl","forceReset","funnelId","funnelSessionId","token"].forEach(r=>e.searchParams.delete(r)),window.history.replaceState({},"",e.href);try{let r=Object.getOwnPropertyDescriptor(Document.prototype,"cookie")||Object.getOwnPropertyDescriptor(HTMLDocument.prototype,"cookie");r&&r.set&&Object.defineProperty(document,"cookie",{configurable:!0,enumerable:!0,get:function(){return r.get?r.get.call(this):""},set:function(s){if(typeof s=="string"){let a=s.toLowerCase();if(a.includes("tgd_draft")||a.includes("tgd-draft")||a.includes("tgd.draft")||a.includes("tgddraft")){if(a.includes("max-age=0")||a.includes("expires=thu, 01 jan 1970")){r.set&&r.set.call(this,s);return}console.warn("\u{1F6E1}\uFE0F [TagadaPay] BLOCKED: tgd_draft should never be a cookie");return}}r.set&&r.set.call(this,s)}})}catch(r){console.warn("[TagadaPay] Could not install cookie blocker:",r)}if(window.localStorage)try{localStorage.removeItem("tgd_draft"),localStorage.removeItem("tgd_funnel_tracking"),localStorage.removeItem("tgd_client_env"),localStorage.removeItem("tgd_client_base_url"),localStorage.removeItem("cms_token")}catch(r){console.warn("[TagadaPay] Failed to clear some localStorage keys:",r)}B(),ce(),Ke(),Ve(),window.localStorage&&localStorage.clear(),window.sessionStorage&&sessionStorage.clear(),["tgd-funnel-session-id","tgd_draft","tgd_funnel_tracking","tgd_client_env","tgd_client_base_url","cms_token","tagadapay_session"].forEach(r=>ke(r)),["tgd-draft","tgd_draft","tgd.draft","tgddraft"].forEach(r=>ke(r)),document.cookie&&document.cookie.split(";").forEach(s=>{let a=s.split("=")[0].trim();if(!a)return;let c=window.location.hostname,p=c.split("."),m=["",c,"."+c];for(let d=1;d<p.length;d++){let w=p.slice(d).join(".");m.push(w),m.push("."+w)}let l=window.location.pathname.split("/").filter(d=>d),f=["/"],u="";l.forEach(d=>{u+="/"+d,f.push(u)}),m.forEach(d=>{f.forEach(w=>{let g="".concat(a,"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=").concat(w),I=d?"; domain=".concat(d):"";document.cookie=g+I,document.cookie=g+I+"; secure",document.cookie=g+I+"; SameSite=None; secure",document.cookie=g+I+"; SameSite=Lax",document.cookie=g+I+"; SameSite=Strict",document.cookie=g+I+"; secure; SameSite=None",document.cookie=g+I+"; secure; SameSite=Lax",document.cookie=g+I+"; secure; SameSite=Strict"})})}),setTimeout(()=>{window.localStorage&&localStorage.length>0&&localStorage.clear(),ke("tgd_draft"),typeof window.stop=="function"&&window.stop(),window.location.replace(e.href)},10)}function At(){if(fe||typeof window=="undefined"||typeof document=="undefined")return;let n=U(),e=ee(),t=!He(),i=!!(n.tagadaClientEnv||n.tagadaClientBaseUrl);if(!e&&!t&&!i)return;let o=document.createElement("div");o.id="tgd-preview-indicator",o.style.cssText='\n position: fixed;\n bottom: 16px;\n right: 16px;\n z-index: 999999;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n ';let r=document.createElement("div");r.style.cssText="\n background: ".concat(e?"#ff9500":"#007aff",";\n color: white;\n padding: 8px 12px;\n border-radius: 8px;\n font-size: 13px;\n font-weight: 600;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);\n cursor: pointer;\n transition: all 0.2s ease;\n display: flex;\n align-items: center;\n gap: 6px;\n "),r.innerHTML='\n <span style="font-size: 16px;">\u{1F50D}</span>\n <span>'.concat(e?"Preview Mode":"Dev Mode","</span>\n ");let s=document.createElement("div");s.style.cssText="\n position: absolute;\n bottom: calc(100% + 8px);\n right: 0;\n background: white;\n border: 1px solid #e5e5e5;\n border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n padding: 12px;\n min-width: 250px;\n font-size: 12px;\n line-height: 1.5;\n display: none;\n ",s.style.paddingTop="20px";let a=document.createElement("div");a.style.cssText="\n position: absolute;\n bottom: 100%;\n left: 0;\n right: 0;\n height: 8px;\n display: none;\n ";let c='<div style="margin-bottom: 8px; font-weight: 600; color: #1d1d1f;">Current Environment</div>';c+='<div style="display: flex; flex-direction: column; gap: 6px;">',e&&(c+='\n <div style="display: flex; justify-content: space-between; color: #86868b;">\n <span>Draft Mode:</span>\n <span style="color: #ff9500; font-weight: 600;">ON</span>\n </div>\n '),t&&(c+='\n <div style="display: flex; justify-content: space-between; color: #86868b;">\n <span>Tracking:</span>\n <span style="color: #ff3b30; font-weight: 600;">DISABLED</span>\n </div>\n '),n.funnelEnv&&(c+='\n <div style="display: flex; justify-content: space-between; color: #86868b;">\n <span>Funnel Env:</span>\n <span style="color: #1d1d1f; font-weight: 600; font-family: monospace; font-size: 11px;">\n '.concat(n.funnelEnv,"\n </span>\n </div>\n ")),n.tagadaClientEnv&&(c+='\n <div style="display: flex; justify-content: space-between; color: #86868b;">\n <span>API Env:</span>\n <span style="color: #1d1d1f; font-weight: 600; font-family: monospace; font-size: 11px;">\n '.concat(n.tagadaClientEnv,"\n </span>\n </div>\n ")),n.tagadaClientBaseUrl&&(c+='\n <div style="color: #86868b;">\n <div style="margin-bottom: 4px;">API URL:</div>\n <div style="color: #1d1d1f; font-weight: 600; font-family: monospace; font-size: 10px; word-break: break-all; background: #f5f5f7; padding: 4px 6px; border-radius: 4px;">\n '.concat(n.tagadaClientBaseUrl,"\n </div>\n </div>\n ")),n.funnelId&&(c+='\n <div style="color: #86868b; margin-top: 4px; padding-top: 8px; border-top: 1px solid #e5e5e5;">\n <div style="margin-bottom: 4px;">Funnel ID:</div>\n <div style="color: #1d1d1f; font-family: monospace; font-size: 10px; word-break: break-all; background: #f5f5f7; padding: 4px 6px; border-radius: 4px;">\n '.concat(n.funnelId,"\n </div>\n </div>\n ")),c+="</div>",c+='\n <div style="margin-top: 12px; padding-top: 8px; border-top: 1px solid #e5e5e5; font-size: 11px; color: #86868b; text-align: center;">\n Add <code style="background: #f5f5f7; padding: 2px 4px; border-radius: 3px;">?forceReset=true</code> to reset\n </div>\n ',c+='\n <div style="margin-top: 12px; padding-top: 8px; border-top: 1px solid #e5e5e5;">\n <button id="tgd-leave-preview" style="\n background: #ff3b30;\n color: white;\n border: none;\n border-radius: 6px;\n padding: 10px 12px;\n font-size: 13px;\n font-weight: 600;\n cursor: pointer;\n transition: opacity 0.2s;\n width: 100%;\n ">\n \u{1F6AA} Leave Preview Mode\n </button>\n </div>\n ',s.innerHTML=c;let p=!1,m=()=>{p=!0,s.style.display="block",a.style.display="block"},l=()=>{p=!1,setTimeout(()=>{p||(s.style.display="none",a.style.display="none")},100)};r.addEventListener("mouseenter",m),r.addEventListener("mouseleave",l),a.addEventListener("mouseenter",m),a.addEventListener("mouseleave",l),s.addEventListener("mouseenter",m),s.addEventListener("mouseleave",l);let f=s.querySelector("#tgd-leave-preview");f&&(f.addEventListener("mouseenter",()=>{f.style.opacity="0.8"}),f.addEventListener("mouseleave",()=>{f.style.opacity="1"}),f.addEventListener("click",u=>{u.stopPropagation(),Rt()})),o.appendChild(r),o.appendChild(a),o.appendChild(s),document.body.appendChild(o),V=o,fe=!0}function Pt(){V&&V.parentNode&&(V.parentNode.removeChild(V),V=null,fe=!1)}function _t(){return fe}var V,fe,We=N(()=>{"use strict";ue();j();de();V=null,fe=!1});var rt={};Te(rt,{FunnelClient:()=>ne,TrackingProvider:()=>Ze,findMethod:()=>tt,getAssignedOrderBumpOfferIds:()=>Bt,getAssignedPaymentFlowId:()=>it,getAssignedPixels:()=>$t,getAssignedResources:()=>ot,getAssignedScripts:()=>zt,getAssignedStaticResources:()=>Mt,getAssignedStepConfig:()=>P,getAssignedUpsellOfferIds:()=>jt,getEnabledMethods:()=>Qe,getExpressMethods:()=>et,getExpressMethodsByProcessor:()=>Ft,getLocalFunnelConfig:()=>nt,isMethodEnabled:()=>Dt,loadLocalFunnelConfig:()=>Ut});function Qe(n){return n?Object.values(n).filter(e=>e.enabled):[]}function et(n){return Qe(n).filter(e=>e.express)}function Ft(n){let e={};for(let t of et(n)){let i=t.processorId||t.integrationId||t.provider;e[i]||(e[i]=[]),e[i].push(t)}return e}function tt(n,e){if(n){for(let t of Object.values(n))if(t.method===e&&t.enabled)return t}}function Dt(n,e){return!!tt(n,e)}function Nt(){if(typeof window!="undefined"){if(window.__TGD_FUNNEL_ID__)return window.__TGD_FUNNEL_ID__;if(typeof document!="undefined"){let n=document.querySelector('meta[name="x-funnel-id"]');return(n==null?void 0:n.getAttribute("content"))||void 0}}}function ge(){if(typeof window!="undefined"){if(window.__TGD_FUNNEL_VARIANT_ID__)return window.__TGD_FUNNEL_VARIANT_ID__;if(typeof document!="undefined"){let n=document.querySelector('meta[name="x-funnel-variant-id"]');return(n==null?void 0:n.getAttribute("content"))||void 0}}}function te(){if(typeof window!="undefined"){if(window.__TGD_FUNNEL_STEP_ID__)return window.__TGD_FUNNEL_STEP_ID__;if(typeof document!="undefined"){let n=document.querySelector('meta[name="x-funnel-step-id"]');return(n==null?void 0:n.getAttribute("content"))||void 0}}}function Ye(n){if(!n||typeof n!="string")return;let e=n.trim();if(!e)return;let t=[()=>JSON.parse(e),()=>JSON.parse(decodeURIComponent(e)),()=>JSON.parse(decodeURIComponent(decodeURIComponent(e)))];for(let i of t)try{let o=i();if(o&&typeof o=="object")return o}catch(o){}typeof console!="undefined"&&console.warn("[SDK] Failed to parse stepConfig:",e.substring(0,100))}function Lt(){if(typeof window=="undefined")return!1;let n=window.location.hostname;return n==="localhost"||n==="127.0.0.1"||n.endsWith(".localhost")&&!n.includes(".cdn.")}async function Ut(){if(!Lt())return null;if(E!==void 0)return E;if(Re)return await new Promise(n=>setTimeout(n,100)),E!=null?E:null;Re=!0;try{console.log("\u{1F6E0}\uFE0F [SDK] Loading local funnel config from /config/funnel.local.json...");let n=await fetch("/config/funnel.local.json");if(!n.ok)return console.log("\u{1F6E0}\uFE0F [SDK] funnel.local.json not found (this is fine in production)"),E=null,null;let e=await n.json();return console.log("\u{1F6E0}\uFE0F [SDK] \u2705 Loaded local funnel config:",e),E=e,e}catch(n){return console.log("\u{1F6E0}\uFE0F [SDK] funnel.local.json not available:",n),E=null,null}finally{Re=!1}}function nt(){return E!=null?E:null}function Ot(n){let e=h(h({},n.staticResources),n.resources);return{payment:n.paymentFlowId?{paymentFlowId:n.paymentFlowId}:void 0,resources:Object.keys(e).length>0?e:void 0,scripts:n.scripts,pixels:n.pixels,orderBumps:n.orderBumps,upsellOffers:n.upsellOffers}}function P(){if(typeof window=="undefined")return;let n=nt();if(n)return console.log("\u{1F6E0}\uFE0F [SDK] Using local funnel.local.json (overrides injected)"),Ot(n);let e=window.__TGD_STEP_CONFIG__;if(e){let t=Ye(e);if(t)return t}if(typeof document!="undefined"){let t=document.querySelector('meta[name="x-step-config"]'),i=t==null?void 0:t.getAttribute("content");if(i){let o=Ye(i);if(o)return o}}}function it(){var t,i;let n=P(),e=(t=n==null?void 0:n.paymentSetupConfig)==null?void 0:t.card;if(e!=null&&e.paymentFlowId)return e.paymentFlowId;if((i=n==null?void 0:n.payment)!=null&&i.paymentFlowId)return n.payment.paymentFlowId;if(typeof window!="undefined"){if(window.__TGD_PAYMENT_FLOW_ID__)return window.__TGD_PAYMENT_FLOW_ID__;if(typeof document!="undefined"){let o=document.querySelector('meta[name="x-payment-flow-id"]');return(o==null?void 0:o.getAttribute("content"))||void 0}}}function ot(){let n=P(),e=n==null?void 0:n.staticResources,t=n==null?void 0:n.resources;if(!(!e&&!t))return h(h({},e),t)}function Mt(){return ot()}function zt(n){let e=P();if(!(e!=null&&e.scripts))return;let t=e.scripts.filter(i=>i.enabled);return n&&(t=t.filter(i=>i.position===n||!i.position&&n==="head-end")),t.length>0?t:void 0}function Xe(n){let e="containerId"in n?"containerId":"pixelId",t=n[e];if(!t||!t.includes(";")&&!t.includes(","))return[n];let i=t.split(/[;,]/).map(o=>o.trim()).filter(o=>o.length>0);return i.length<=1?[n]:i.map(o=>b(h({},n),{[e]:o}))}function $t(){let n=P(),e=n==null?void 0:n.pixels;if(!e||typeof e!="object")return;let t={};for(let[i,o]of Object.entries(e))o&&(Array.isArray(o)?t[i]=o.flatMap(r=>Xe(r)):typeof o=="object"&&(t[i]=Xe(o)));return Object.keys(t).length>0?t:void 0}function Bt(){let n=P();if(n!=null&&n.orderBumps&&n.orderBumps.mode==="custom")return n.orderBumps.enabledOfferIds}function jt(){let n=P();if(n!=null&&n.upsellOffers&&n.upsellOffers.mode==="custom")return n.upsellOffers.enabledUpsellIds}var Je,Ze,E,Re,ne,pe=N(()=>{"use strict";se();Me();be();ue();de();Je=()=>Promise.resolve().then(()=>(We(),qe)).then(n=>n.injectPreviewModeIndicator()),Ze=(r=>(r.FACEBOOK="facebook",r.TIKTOK="tiktok",r.SNAPCHAT="snapchat",r.PINTEREST="pinterest",r.GTM="gtm",r))(Ze||{});Re=!1;ne=class{constructor(e){this.eventDispatcher=new $;this.isInitializing=!1;this.initializationAttempted=!1;this.config=e,this.resource=new ae(e.apiClient),this.state={context:null,isLoading:!1,isInitialized:!1,isNavigating:!1,error:null,sessionError:null}}setConfig(e){this.config=h(h({},this.config),e)}subscribe(e){return this.eventDispatcher.subscribe(e)}getState(){return this.state}getDetectedSessionId(){var i;if((i=this.state.context)!=null&&i.sessionId)return this.state.context.sessionId;if(typeof window=="undefined")return null;let t=new URLSearchParams(window.location.search).get("funnelSessionId");return t||$e()||null}resetInitialization(){this.initializationAttempted=!1,this.isInitializing=!1,this.updateState({context:null,isInitialized:!1})}async autoInitialize(e,t,i){if(this.state.context)return this.state.context;if(this.isInitializing||this.initializationAttempted)return null;this.initializationAttempted=!0,this.isInitializing=!0,this.updateState({isLoading:!0,error:null});try{let o=this.getDetectedSessionId(),a=new URLSearchParams(typeof window!="undefined"?window.location.search:"").get("funnelId")||i,c=Nt(),p=ge(),m=te(),l=U(),f=this.config.funnelId||c||a,u=this.config.stepId||m,d=typeof window!="undefined"?new URLSearchParams(window.location.search):null,w=d==null?void 0:d.get("funnelEnv");this.config.debugMode&&console.log("\u{1F680} [FunnelClient] Auto-initializing...",{existingSessionId:o,effectiveFunnelId:f,funnelVariantId:p,funnelStepId:u,draft:l.draft,funnelTracking:l.funnelTracking,funnelEnv:w,tagadaClientEnv:l.tagadaClientEnv,tagadaClientBaseUrl:l.tagadaClientBaseUrl,source:{funnelId:this.config.funnelId?"config":c?"injected":a?"url/prop":"none",stepId:this.config.stepId?"config":m?"injected":"none"}});let g=await this.resource.initialize({cmsSession:{customerId:e.customerId,sessionId:e.sessionId,storeId:t.id,accountId:t.accountId},funnelId:f,existingSessionId:o||void 0,currentUrl:typeof window!="undefined"?window.location.href:void 0,funnelVariantId:p,funnelStepId:u,draft:l.draft,funnelTracking:l.funnelTracking,funnelEnv:w||void 0,tagadaClientEnv:l.tagadaClientEnv,tagadaClientBaseUrl:l.tagadaClientBaseUrl,currency:l.currency,locale:l.locale});if(g.success&&g.context){let I=this.enrichContext(g.context);return this.handleSessionSuccess(I),Je(),I}else throw new Error(g.error||"Failed to initialize funnel session")}catch(o){let r=o instanceof Error?o:new Error(String(o));throw this.updateState({error:r,isLoading:!1}),this.config.debugMode&&console.error("\u274C [FunnelClient] Init failed:",r),r}finally{this.isInitializing=!1}}async initialize(e,t,i,o){this.updateState({isLoading:!0,error:null});try{let r=ge(),s=te();this.config.debugMode&&(r&&console.log("\u{1F3AF} [FunnelClient] Detected A/B test variant:",r),s&&console.log("\u{1F3AF} [FunnelClient] Detected step ID:",s));let a=await this.resource.initialize({cmsSession:{customerId:e.customerId,sessionId:e.sessionId,storeId:t.id,accountId:t.accountId},funnelId:i,entryStepId:o,currentUrl:typeof window!="undefined"?window.location.href:void 0,funnelVariantId:r,funnelStepId:s});if(a.success&&a.context){let c=this.enrichContext(a.context);return this.handleSessionSuccess(c),Je(),c}else throw new Error(a.error||"Failed to initialize")}catch(r){let s=r instanceof Error?r:new Error(String(r));throw this.updateState({error:s,isLoading:!1}),s}}async navigate(e,t){var i,o,r,s,a,c;if(t!=null&&t.waitForSession&&!((i=this.state.context)!=null&&i.sessionId)){this.config.debugMode&&console.log("\u23F3 [FunnelClient] Waiting for session before navigation...");let p=5e3,m=Date.now();for(;!((o=this.state.context)!=null&&o.sessionId)&&Date.now()-m<p;)await new Promise(l=>setTimeout(l,100));(r=this.state.context)!=null&&r.sessionId&&this.config.debugMode&&console.log("\u2705 [FunnelClient] Session ready, proceeding with navigation")}if(!((s=this.state.context)!=null&&s.sessionId))throw new Error("No active session");this.updateState({isNavigating:!0,isLoading:!0});try{let p=ge(),m=te(),l=typeof window!="undefined"?window.location.href:void 0;!m&&this.config.stepId&&(m=this.config.stepId,this.config.debugMode&&console.log("\u{1F50D} [FunnelClient.navigate] Using stepId from config (no injection):",m)),!p&&this.config.variantId&&(p=this.config.variantId,this.config.debugMode&&console.log("\u{1F50D} [FunnelClient.navigate] Using variantId from config (no injection):",p)),this.config.debugMode&&console.log("\u{1F50D} [FunnelClient.navigate] Sending to backend:",{sessionId:this.state.context.sessionId,currentUrl:l,funnelStepId:m||"(not found)",funnelVariantId:p||"(not found)",hasInjectedStepId:!!te(),hasInjectedVariantId:!!ge(),usedConfigFallback:!te()&&!!this.config.stepId,customerTags:(t==null?void 0:t.customerTags)||"(none)",deviceId:(t==null?void 0:t.deviceId)||"(none)"});let f=(t==null?void 0:t.fireAndForget)||!1,u=await this.resource.navigate({sessionId:this.state.context.sessionId,event:e,currentUrl:l,funnelStepId:m,funnelVariantId:p,fireAndForget:f,customerTags:t==null?void 0:t.customerTags,deviceId:t==null?void 0:t.deviceId});if(!u.success||!u.result)throw new Error(u.error||"Navigation failed");let d=u.result;if(d.queued)return this.updateState({isNavigating:!1,isLoading:!1}),d.sessionId&&d.sessionId!==((a=this.state.context)==null?void 0:a.sessionId)&&(this.config.debugMode&&console.log("\u{1F525} [FunnelClient] Session ID updated: ".concat((c=this.state.context)==null?void 0:c.sessionId," \u2192 ").concat(d.sessionId)),this.state.context&&(this.state.context.sessionId=d.sessionId)),this.config.debugMode&&console.log("\u{1F525} [FunnelClient] Navigation queued (fire-and-forget mode)"),d;let w=(t==null?void 0:t.autoRedirect)!==void 0?t.autoRedirect:this.config.autoRedirect!==!1;return this.updateState({isNavigating:!1,isLoading:!1}),w&&(d!=null&&d.url)&&typeof window!="undefined"&&(this.config.debugMode&&console.log("\u{1F680} [FunnelClient] Auto-redirecting to:",d.url,"(skipped session refresh - next page will initialize)"),window.location.replace(d.url)),d}catch(p){let m=p instanceof Error?p:new Error(String(p));throw this.updateState({error:m,isNavigating:!1,isLoading:!1}),m}}async goToStep(e,t){return this.navigate({type:"direct_navigation",data:{targetStepId:e}},t)}async refreshSession(){var e;if((e=this.state.context)!=null&&e.sessionId)try{let t=await this.resource.getSession(this.state.context.sessionId);if(t.success&&t.context){let i=this.enrichContext(t.context);return this.updateState({context:i,sessionError:null}),i}}catch(t){this.updateState({sessionError:t instanceof Error?t:new Error(String(t))})}}async updateContext(e){var t;if(!((t=this.state.context)!=null&&t.sessionId))throw new Error("No active session");this.updateState({isLoading:!0});try{let i=await this.resource.updateContext(this.state.context.sessionId,{contextUpdates:e});if(i.success)await this.refreshSession();else throw new Error(i.error||"Failed to update context")}finally{this.updateState({isLoading:!1})}}async endSession(){var e;if((e=this.state.context)!=null&&e.sessionId)try{await this.resource.endSession(this.state.context.sessionId)}finally{this.state.context=null,this.updateState({context:null,isInitialized:!1})}}updateState(e){this.state=h(h({},this.state),e),this.eventDispatcher.notify(this.state)}handleSessionSuccess(e){ze(e.sessionId),this.updateState({context:e,isLoading:!1,isInitialized:!0,error:null,sessionError:null})}enrichContext(e){var s,a;if((((s=this.config.environment)==null?void 0:s.environment)||J())!=="local")return e;let i=((a=this.config.pluginConfig)==null?void 0:a.staticResources)||{};if(Object.keys(i).length===0)return e;let o=e.static||{};return Object.keys(i).every(c=>o[c]===i[c])&&Object.keys(o).length===Object.keys(i).length?e:b(h({},e),{static:h(h({},i),o)})}}});var mn={};Te(mn,{TRACKER_VERSION:()=>_e,TagadaExternalTracker:()=>Se,TagadaTracker:()=>yt});se();pe();var _={NETWORK_ERROR:"network_error",API_ERROR:"api_error",AUTH_REQUIRED:"auth_required",TOKEN_EXPIRED:"token_expired",NOT_FOUND:"not_found",VALIDATION_ERROR:"validation_error",CIRCUIT_BREAKER:"circuit_breaker",PAYMENT_FAILED:"payment_failed",CARD_DECLINED:"card_declined",SESSION_EXPIRED:"session_expired",RATE_LIMITED:"rate_limited",TIMEOUT:"timeout",UNKNOWN:"unknown"},L=class extends Error{constructor(e,t){var i;super(e),this.name="TagadaError",this.code=t.code,this.statusCode=t.statusCode,this.retryable=(i=t.retryable)!=null?i:!1,this.details=t.details,Object.setPrototypeOf(this,new.target.prototype)}},O=class extends L{constructor(e,t,i){var o,r;super(e,{code:(o=i==null?void 0:i.code)!=null?o:_.API_ERROR,statusCode:t,retryable:(r=i==null?void 0:i.retryable)!=null?r:t>=500,details:i==null?void 0:i.details}),this.name="TagadaApiError"}},me=class extends L{constructor(e="Network request failed"){super(e,{code:_.NETWORK_ERROR,retryable:!0}),this.name="TagadaNetworkError"}},he=class extends L{constructor(e="Authentication required",t=401){super(e,{code:_.AUTH_REQUIRED,statusCode:t,retryable:!1}),this.name="TagadaAuthError"}};var ye=class extends L{constructor(e){super(e,{code:_.CIRCUIT_BREAKER,retryable:!1}),this.name="TagadaCircuitBreakerError"}};var Ce=class{constructor(e){this.currentToken=null;this.tokenProvider=null;this.requestHistory=new Map;this.WINDOW_MS=5e3;this.MAX_REQUESTS=30;this.baseURL=e.baseURL,this.timeout=e.timeout||6e4,this.defaultHeaders=h({"Content-Type":"application/json"},e.headers),typeof setInterval!="undefined"&&setInterval(()=>this.cleanupHistory(),1e4)}setTokenProvider(e){this.tokenProvider=e}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,i){return this.request("POST",e,t,i)}async put(e,t,i){return this.request("PUT",e,t,i)}async patch(e,t,i){return this.request("PATCH",e,t,i)}async delete(e,t){return this.request("DELETE",e,void 0,t)}setHeader(e,t){this.defaultHeaders[e]=t}removeHeader(e){delete this.defaultHeaders[e]}updateToken(e){this.currentToken=e,e?this.setHeader("x-cms-token",e):(this.removeHeader("x-cms-token"),console.log("[SDK] Token removed from ApiClient"))}getCurrentToken(){return this.currentToken}updateConfig(e){e.baseURL&&(this.baseURL=e.baseURL),e.timeout&&(this.timeout=e.timeout),e.headers&&Object.assign(this.defaultHeaders,e.headers),console.log("[SDK] ApiClient configuration updated")}async request(e,t,i,o){let r="".concat(e,":").concat(t);try{this.checkRequestLimit(r)}catch(l){throw console.error("[SDK] \u{1F6D1} Request blocked by Circuit Breaker:",l),l}if(!(o!=null&&o.skipAuth)&&!this.currentToken&&this.tokenProvider)try{console.log("[SDK] Waiting for token...");let l=await this.tokenProvider();l&&this.updateToken(l)}catch(l){console.error("[SDK] Failed to get token from provider:",l)}let s=h({},this.defaultHeaders);o!=null&&o.headers&&Object.assign(s,o.headers),!(o!=null&&o.skipAuth)&&this.currentToken&&(s["x-cms-token"]=this.currentToken);let a="".concat(this.baseURL).concat(t);if(o!=null&&o.params){let l=new URLSearchParams(o.params);a+="?".concat(l.toString())}console.log("[SDK] Making ".concat(e," request to: ").concat(a));let c=new AbortController,p=setTimeout(()=>c.abort(),this.timeout),m=o!=null&&o.signal?Gt([o.signal,c.signal]):c.signal;try{let l={method:e,headers:s,signal:m};i!==void 0&&(l.body=JSON.stringify(i));let f=await fetch(a,l);if(!f.ok){let d=await this.safeParseJson(f);throw this.toTagadaError(f.status,d,f.statusText)}return await f.json()}catch(l){throw l instanceof L?l:l instanceof DOMException&&l.name==="AbortError"?new O("Request timed out",0,{code:_.TIMEOUT,retryable:!0}):l instanceof TypeError?new me(l.message):l instanceof Error?l:new Error(String(l))}finally{clearTimeout(p)}}toTagadaError(e,t,i){var r,s,a;let o=(s=(r=t==null?void 0:t.message)!=null?r:t==null?void 0:t.error)!=null?s:i;return e===401||e===403?new he(o,e):e===429?new O(o,429,{code:_.RATE_LIMITED,retryable:!0}):e===404?new O(o,404,{code:_.NOT_FOUND,retryable:!1}):new O(o,e,{code:(a=t==null?void 0:t.code)!=null?a:_.API_ERROR,details:t,retryable:e>=500})}async safeParseJson(e){try{return await e.json()}catch(t){return}}checkRequestLimit(e){let t=Date.now(),i=this.requestHistory.get(e);if(!i){this.requestHistory.set(e,{count:1,firstRequestTime:t});return}if(t-i.firstRequestTime>this.WINDOW_MS){this.requestHistory.set(e,{count:1,firstRequestTime:t});return}if(i.count++,i.count>this.MAX_REQUESTS)throw new ye("Circuit Breaker: Too many requests to ".concat(e," (").concat(i.count," in ").concat(this.WINDOW_MS,"ms)"))}cleanupHistory(){let e=Date.now();for(let[t,i]of this.requestHistory.entries())e-i.firstRequestTime>this.WINDOW_MS&&this.requestHistory.delete(t)}};function Gt(n){let e=new AbortController;for(let t of n){if(t.aborted)return e.abort(t.reason),e.signal;t.addEventListener("abort",()=>e.abort(t.reason),{once:!0,signal:e.signal})}return e.signal}function Kt(){return{width:window.screen.width,height:window.screen.height}}function Vt(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(n){return"UTC"}}function st(){try{return navigator.language||"en-US"}catch(n){return"en-US"}}var M=typeof navigator!="undefined"?navigator.userAgent:"";function k(n,...e){for(let t of e){let i=n.match(t);if(i)return i}return null}function Ht(n){let e=[[/EdgA?\/([\d.]+)/i,"Edge"],[/OPR\/([\d.]+)/i,"Opera"],[/Brave\/([\d.]+)/i,"Brave"],[/Vivaldi\/([\d.]+)/i,"Vivaldi"],[/SamsungBrowser\/([\d.]+)/i,"Samsung Internet"],[/UCBrowser\/([\d.]+)/i,"UC Browser"],[/Firefox\/([\d.]+)/i,"Firefox"],[/CriOS\/([\d.]+)/i,"Chrome"],[/FxiOS\/([\d.]+)/i,"Firefox"],[/Chrome\/([\d.]+)/i,"Chrome"],[/Version\/([\d.]+).*Safari/i,"Safari"],[/Safari\/([\d.]+)/i,"Safari"]];for(let[t,i]of e){let o=n.match(t);if(o){let r=o[1]||"";return{name:i,version:r,major:r.split(".")[0]||""}}}return{name:"",version:"",major:""}}function qt(n){let e=k(n,/Windows NT ([\d.]+)/i)||k(n,/Mac OS X ([\d_.]+)/i)||k(n,/Android ([\d.]+)/i)||k(n,/iPhone OS ([\d_]+)/i)||k(n,/iPad.*OS ([\d_]+)/i)||k(n,/CrOS[\w ]*\/([\d.]+)/i)||k(n,/Linux/i);if(!e)return{name:"",version:""};let t=e[0],i=(e[1]||"").replace(/_/g,".");return/Windows/i.test(t)?{name:"Windows",version:{"10.0":"10","6.3":"8.1","6.2":"8","6.1":"7","6.0":"Vista","5.1":"XP"}[i]||i}:/Mac OS X/i.test(t)?{name:"macOS",version:i}:/Android/i.test(t)?{name:"Android",version:i}:/iPhone|iPad/i.test(t)?{name:"iOS",version:i}:/CrOS/i.test(t)?{name:"Chrome OS",version:i}:/Linux/i.test(t)?{name:"Linux",version:""}:{name:"",version:""}}function Wt(n){var e;if(/iPad/i.test(n))return{type:"tablet",vendor:"Apple",model:"iPad"};if(/iPhone/i.test(n))return{type:"mobile",vendor:"Apple",model:"iPhone"};if(/iPod/i.test(n))return{type:"mobile",vendor:"Apple",model:"iPod"};if(/Android/i.test(n)){let t=n.match(/Android[\s\d.]+;\s*([^)]+?)(?:\s+Build)/i);return{type:/Mobile/i.test(n)?"mobile":"tablet",model:(e=t==null?void 0:t[1])==null?void 0:e.trim()}}}function Jt(n){let e=k(n,/AppleWebKit\/([\d.]+)/i)||k(n,/Gecko\/([\d.]+)/i)||k(n,/Trident\/([\d.]+)/i)||k(n,/Presto\/([\d.]+)/i);if(!e)return{name:"",version:""};let t=e[0],i=e[1]||"";return/AppleWebKit/i.test(t)?{name:"WebKit",version:i}:/Gecko/i.test(t)?{name:"Gecko",version:i}:/Trident/i.test(t)?{name:"Trident",version:i}:/Presto/i.test(t)?{name:"Presto",version:i}:{name:"",version:""}}function Yt(n){return/x86_64|x64|amd64|Win64/i.test(n)?{architecture:"amd64"}:/ia32|x86/i.test(n)?{architecture:"ia32"}:/aarch64|arm64/i.test(n)?{architecture:"arm64"}:/arm/i.test(n)?{architecture:"arm"}:{architecture:""}}function Xt(){return navigator.webdriver?!0:/bot|crawl|spider|slurp|Googlebot|bingbot|yandex|baidu|duckduck|facebookexternalhit|Twitterbot|linkedinbot|embedly|quora|pinterest|redditbot|Slackbot|Discordbot|WhatsApp|TelegramBot|Applebot/i.test(M)}function Zt(n){return/Chrome|Chromium|Edge|Brave|Opera|Vivaldi|Arc/i.test(n)}function Qt(){return window.matchMedia("(display-mode: standalone)").matches||navigator.standalone===!0}function en(n){return/mac/i.test(n)?navigator.maxTouchPoints>0:!1}function at(){if(typeof window=="undefined")return{userAgent:{name:"",browser:{major:"",name:"",version:""},os:{name:"",version:""},device:void 0,engine:{name:"",version:""},cpu:{architecture:""}},screenResolution:{width:0,height:0},timeZone:"UTC",flags:{isBot:!1,isChromeFamily:!1,isStandalonePWA:!1,isAppleSilicon:!1}};let n=Ht(M),e=qt(M),t=Wt(M),i=Jt(M),o=Yt(M),r;try{r={isBot:Xt(),isChromeFamily:Zt(n.name),isStandalonePWA:Qt(),isAppleSilicon:en(e.name)}}catch(s){r={isBot:!1,isChromeFamily:!1,isStandalonePWA:!1,isAppleSilicon:!1}}return{userAgent:{name:M,browser:n,os:e,device:t,engine:i,cpu:o},screenResolution:Kt(),timeZone:Vt(),flags:r}}function lt(){if(typeof window=="undefined")return{};let n=new URLSearchParams(window.location.search);return{locale:n.get("locale")||void 0,currency:n.get("currency")||void 0,utmSource:n.get("utm_source")||void 0,utmMedium:n.get("utm_medium")||void 0,utmCampaign:n.get("utm_campaign")||void 0,gclid:n.get("gclid")||void 0}}var Ie=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){this.listeners.has(e)&&this.listeners.get(e).delete(t)}async emit(e,t){if(this.listeners.has(e)){let i=Array.from(this.listeners.get(e));await Promise.all(i.map(o=>{try{return Promise.resolve(o(t))}catch(r){return console.error('[EventBus] Error in listener for event "'.concat(e,'":'),r),Promise.resolve()}}))}}clear(){this.listeners.clear()}};be();function ie(n){try{let e=n.split(".");if(e.length!==3)return console.error("Invalid JWT token format"),null;let t=e[1],i=t+"=".repeat((4-t.length%4)%4),o=atob(i),r=JSON.parse(o);return r.exp&&Date.now()>=r.exp*1e3?(console.warn("JWT token is expired"),null):{sessionId:r.sessionId,storeId:r.storeId,accountId:r.accountId,customerId:r.customerId,role:r.role,isValid:!0,isLoading:!1}}catch(e){return console.error("Failed to decode JWT token:",e),null}}function ct(n){try{let e=n.split(".");if(e.length!==3)return!0;let t=e[1],i=t+"=".repeat((4-t.length%4)%4),o=atob(i),r=JSON.parse(o);return r.exp?Date.now()>=r.exp*1e3:!1}catch(e){return console.error("Failed to check token expiration:",e),!0}}se();var H={},tn=["","VITE_","REACT_APP_","NEXT_PUBLIC_"];function F(n,e=tn){var t,i,o;for(let r of e){let s=r?"".concat(r).concat(n):n;if(typeof process!="undefined"&&((t=process==null?void 0:process.env)!=null&&t[s]))return console.log("process.env[".concat(s,"]"),process.env[s]),process.env[s];if(typeof H!="undefined"&&((i=H==null?void 0:H.env)!=null&&i[s]))return console.log("import.meta.env[".concat(s,"]"),H.env[s]),H.env[s];if(typeof window!="undefined"&&((o=window==null?void 0:window.__TAGADA_ENV__)!=null&&o[s]))return console.log("window.__TAGADA_ENV__[".concat(s,"]"),window.__TAGADA_ENV__[s]),window.__TAGADA_ENV__[s]}}var nn=async(n="default")=>{try{if((F("TAGADA_ENV")||F("TAGADA_ENVIRONMENT"))==="production"||!Y(!0))return null;let t=await fetch("/.local.json");if(!t.ok)return null;let i=await t.json(),o={},r=!1;try{let a=await fetch("/config/".concat(n,".tgd.json"));a.ok||(a=await fetch("/config/".concat(n,".json"))),a.ok&&(o=await a.json(),r=!0)}catch(a){}if(!r&&n!=="default"){console.warn("\u26A0\uFE0F Config variant '".concat(n,"' not found, falling back to 'default'"));try{let a=await fetch("/config/default.tgd.json");a.ok||(a=await fetch("/config/default.json")),a.ok&&(o=await a.json(),r=!0,console.log("\u2705 Fallback to 'default' config successful"))}catch(a){}}r||console.warn(n==="default"?"\u26A0\uFE0F No 'default' config found. Create /config/default.tgd.json":"\u26A0\uFE0F Neither '".concat(n,"' nor 'default' config found. Create /config/default.tgd.json"));let s={storeId:i.storeId,accountId:i.accountId,basePath:i.basePath,config:o};return console.log("\u{1F6E0}\uFE0F Using local development plugin config:",s),s}catch(e){return null}},on=async()=>{try{if((F("TAGADA_ENV")||F("TAGADA_ENVIRONMENT"))==="production"||!Y(!0))return null;try{console.log("\u{1F6E0}\uFE0F [V2] Attempting to load /config/funnel.local.json...");let i=await fetch("/config/funnel.local.json");if(i.ok){let o=await i.json();console.log("\u{1F6E0}\uFE0F [V2] \u2705 Loaded local funnel config (NEW format):",o);let{loadLocalFunnelConfig:r}=await Promise.resolve().then(()=>(pe(),rt));if(await r(),o.staticResources){let s={};for(let[a,c]of Object.entries(o.staticResources))s[a]={id:c};return s}return null}}catch(i){console.log("\u{1F6E0}\uFE0F [V2] funnel.local.json not found, trying legacy format...")}console.log("\u{1F6E0}\uFE0F [V2] Attempting to load /config/resources.static.json (legacy)...");let e=await fetch("/config/resources.static.json");if(!e.ok)return console.log("\u{1F6E0}\uFE0F [V2] No local static resources found"),null;let t=await e.json();return console.log("\u{1F6E0}\uFE0F [V2] \u2705 Loaded legacy static resources:",t),t}catch(n){return console.error("\u{1F6E0}\uFE0F [V2] \u274C Error loading static resources:",n),null}},we=n=>{if(typeof document=="undefined")return;let e=document.querySelector('meta[name="'.concat(n,'"]'));return(e==null?void 0:e.getAttribute("content"))||void 0},rn=()=>{if(typeof window!="undefined"&&window.__TAGADA_PLUGIN_CONFIG__)return window.__TAGADA_PLUGIN_CONFIG__;try{let n=we("x-plugin-config");if(n)return JSON.parse(decodeURIComponent(n))}catch(n){}return{}};var sn=async()=>{try{if(typeof document=="undefined")return null;let n=we("x-plugin-store-id"),e=we("x-plugin-account-id");if(!n)return null;let t=we("x-plugin-base-path")||"/",i=rn();e||console.warn("\u26A0\uFE0F Plugin config: Account ID not found in meta tags");let o={storeId:n,accountId:e,basePath:t,config:i};return console.log("\u{1F680} [HIGHEST PRIORITY] Plugin config loaded from meta tags (runtime injected config):",{storeId:n,accountId:e,basePath:t,configKeys:Object.keys(i),configSize:JSON.stringify(i).length}),o}catch(n){return console.warn("\u26A0\uFE0F Error loading production config from meta tags:",n),null}},dt=async(n="default",e)=>{var s,a;console.log("\u{1F527} [V2] loadPluginConfig called with variant:",n);let t=await on(),i=await sn();if(i){let c=b(h({},i),{staticResources:t!=null?t:void 0});return console.log("\u2705 [V2] Using INJECTED config from meta tags (HIGHEST PRIORITY)"),c}if(e){let c={storeId:e.storeId,accountId:e.accountId,basePath:(s=e.basePath)!=null?s:"/",config:(a=e.config)!=null?a:{},staticResources:t!=null?t:void 0};return console.log("\u2705 [V2] Using raw config parameter (PRIORITY 2)"),c}let o=await ln();if(o){let c=b(h({},o),{staticResources:t!=null?t:void 0});return console.log("\u2705 [V2] Using environment variables config (PRIORITY 3 - build time)"),c}let r=await nn(n);if(r){let c=b(h({},r),{staticResources:t!=null?t:void 0});return console.log("\u2705 [V2] Using local dev config files (PRIORITY 4)"),c}return console.warn("\u26A0\uFE0F [V2] No plugin config found - using defaults"),{basePath:"/",config:{},staticResources:t!=null?t:void 0}};async function an(n="default",e){try{if(!Y())return null;if(e)return e;let t=["/config/".concat(n,".config.json"),"/config/".concat(n,".tgd.json"),"/config/".concat(n,".json")];for(let i of t)try{let o=await fetch(i);if(o.ok)return await o.json()}catch(o){continue}return console.warn("\u26A0\uFE0F [loadLocalConfig] No config found for '".concat(n,"'")),null}catch(t){return console.error("[loadLocalConfig] Error loading config:",t),null}}async function ln(){try{if(!Y())return;let n=F("TAGADA_STORE_ID"),e=F("TAGADA_ACCOUNT_ID"),t=F("TAGADA_BASE_PATH"),i=F("TAGADA_CONFIG_NAME");if(!n||!e)return;let o=await an(i);if(!o)return;let r={storeId:n,accountId:e,basePath:t||"/",config:o};return console.log("\u{1F6E0}\uFE0F [createRawPluginConfig] Using environment variables (build-time config):",{hasStoreId:!!r.storeId,hasAccountId:!!r.accountId,basePath:r.basePath,hasConfig:!!r.config}),r}catch(n){console.error("[createRawPluginConfig] Error creating config:",n);return}}ue();j();j();var Ae=new Map,Pe=new Set;function cn(){return typeof window=="undefined"?null:new URLSearchParams(window.location.search).get("authCode")}async function ut(n,e,t,i=!1){if(Pe.has(n))throw i&&console.log("[AuthHandoff] Code already resolved, skipping duplicate request"),new Error("Auth code already resolved");let o=Ae.get(n);if(o)return i&&console.log("[AuthHandoff] Resolution already in progress, waiting for existing request"),o;i&&console.log("[AuthHandoff] Resolving authCode:",n.substring(0,15)+"...");let r=(async()=>{try{let s=await fetch("".concat(t,"/api/v1/cms/auth/resolve-handoff"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:n,storeId:e})});if(!s.ok){let c=await s.json().catch(()=>({message:"Unknown error"}));throw new Error(c.message||"Failed to resolve auth handoff: ".concat(s.status))}let a=await s.json();return i&&console.log("[AuthHandoff] \u2705 Resolved successfully:",{customerId:a.customer.id,role:a.customer.role,hasContext:Object.keys(a.context).length>0}),i&&console.log("[AuthHandoff] Storing new token (overriding existing)"),x(a.token),dn(i),Pe.add(n),a}catch(s){throw console.error("[AuthHandoff] \u274C Failed to resolve:",s),s}finally{Ae.delete(n)}})();return Ae.set(n,r),r}function dn(n=!1){if(typeof window=="undefined")return;let e=new URL(window.location.href);e.searchParams.has("authCode")&&(e.searchParams.delete("authCode"),window.history.replaceState({},"",e.pathname+e.search+e.hash),n&&console.log("[AuthHandoff] Cleaned authCode from URL"))}function ft(){let n=cn();return!(!n||!n.startsWith("ah_")||Pe.has(n))}var ve=class{constructor(e={}){this.bus=new Ie;this.eventDispatcher=new $;this.tokenPromise=null;this.tokenResolver=null;this.isInitializingSession=!1;this.lastSessionInitError=null;this.sessionInitRetryCount=0;this.MAX_SESSION_INIT_RETRIES=3;var a,c,p,m;this.config=e,this.instanceId=Math.random().toString(36).substr(2,9),this.boundHandleStorageChange=this.handleStorageChange.bind(this),this.boundHandlePageshow=l=>{if(l.persisted)if(this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Page restored from BFcache (back button), re-initializing funnel...")),this.funnel&&this.state.session&&this.state.store){this.funnel.resetInitialization();let f=this.getAccountId(),d=new URLSearchParams(typeof window!="undefined"?window.location.search:"").get("funnelId")||void 0;this.funnel.autoInitialize({customerId:this.state.session.customerId,sessionId:this.state.session.sessionId},{id:this.state.store.id,accountId:f},d).catch(w=>{console.error("[TagadaClient] Funnel re-initialization failed:",w)})}else this.sessionInitRetryCount=0,this.initialize()},console.log("[TagadaClient ".concat(this.instanceId,"] Initializing...")),console.log("[TagadaClient ".concat(this.instanceId,"] Config:"),{debugMode:e.debugMode,hasRawPluginConfig:!!e.rawPluginConfig,rawPluginConfig:e.rawPluginConfig,features:e.features}),Ge(this.config.debugMode)&&this.config.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Preview mode active - state cleared"));let i=this.resolveEnvironment(),o=Oe(i);e.customApiConfig&&(o=b(h(h({},o),e.customApiConfig),{apiConfig:h(h({},o.apiConfig),e.customApiConfig.apiConfig)}),this.config.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Applied custom API config:"),o.apiConfig.baseUrl)),this.state={auth:{isAuthenticated:!1,isLoading:!1,customer:null,session:null},session:null,customer:null,locale:{locale:"en-US",language:"en",region:"US",messages:{}},currency:{code:"USD",symbol:"$",name:"US Dollar"},store:null,environment:o,isLoading:!0,isInitialized:!1,isSessionInitialized:!1,pluginConfig:{basePath:"/",config:{}},pluginConfigLoading:!0,debugMode:(a=e.debugMode)!=null?a:i!=="production",token:null},console.log("[TagadaClient ".concat(this.instanceId,"] Initial state:"),{pluginConfigLoading:this.state.pluginConfigLoading,hasRawPluginConfig:!!e.rawPluginConfig}),this.apiClient=new Ce({baseURL:o.apiConfig.baseUrl});let r=(c=e.features)==null?void 0:c.funnel;if(r!==!1){let l=typeof r=="object"?r:{};this.funnel=new ne({apiClient:this.apiClient,debugMode:this.state.debugMode,pluginConfig:this.state.pluginConfig,environment:this.state.environment,autoRedirect:l.autoRedirect,funnelId:(p=e.rawPluginConfig)==null?void 0:p.funnelId,stepId:(m=e.rawPluginConfig)==null?void 0:m.stepId})}this.apiClient.setTokenProvider(this.waitForToken.bind(this)),typeof window!="undefined"&&(window.addEventListener("storage",this.boundHandleStorageChange),window.addEventListener("pageshow",this.boundHandlePageshow)),this.setupConfigHotReload(),this.initialize()}destroy(){typeof window!="undefined"&&(window.removeEventListener("storage",this.boundHandleStorageChange),window.removeEventListener("pageshow",this.boundHandlePageshow)),this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Destroyed")),this.eventDispatcher.clear(),this.bus.clear()}handleStorageChange(){if(X()===this.state.token){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Token unchanged (ignoring event)"));return}if(this.isInitializingSession){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Session initialization in progress, skipping storage change"));return}if(this.sessionInitRetryCount>=this.MAX_SESSION_INIT_RETRIES&&this.lastSessionInitError){this.state.debugMode&&console.error("[TagadaClient ".concat(this.instanceId,"] Max session init retries reached, giving up"),this.lastSessionInitError);return}this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Storage changed, re-initializing token...")),this.initializeToken()}subscribe(e){return this.eventDispatcher.subscribe(e)}getState(){return this.state}updateState(e){this.state=h(h({},this.state),e),this.eventDispatcher.notify(this.state)}resolveEnvironment(){return this.config.environment?this.config.environment:J()}async initialize(){try{await this.initializePluginConfig(),this.state.pluginConfig.storeId?await this.initializeToken():(console.warn("[TagadaClient] No store ID found in plugin config. Skipping token initialization."),this.updateState({isLoading:!1,isInitialized:!0}))}catch(e){console.error("[TagadaClient] Initialization failed:",e),this.updateState({isLoading:!1,isInitialized:!0})}}async initializePluginConfig(){if(console.log("[TagadaClient ".concat(this.instanceId,"] initializePluginConfig called"),{pluginConfigLoading:this.state.pluginConfigLoading,hasRawPluginConfig:!!this.config.rawPluginConfig}),!this.state.pluginConfigLoading){console.log("[TagadaClient ".concat(this.instanceId,"] Plugin config already loading or loaded, skipping..."));return}try{let e=this.config.localConfig||"default";console.log("[TagadaClient ".concat(this.instanceId,"] Loading plugin config with variant: ").concat(e));let t=await dt(e,this.config.rawPluginConfig);console.log("[TagadaClient ".concat(this.instanceId,"] Plugin config loaded:"),t),this.updateState({pluginConfig:t,pluginConfigLoading:!1}),this.funnel&&this.funnel.setConfig({pluginConfig:t,environment:this.state.environment})}catch(e){console.error("[TagadaClient] Failed to load plugin config:",e),this.updateState({pluginConfig:{basePath:"/",config:{}},pluginConfigLoading:!1})}}async initializeToken(){var e;if(ft()){let t=this.state.pluginConfig.storeId;if(!t)return console.error("[TagadaClient] Cannot resolve authCode: storeId not found in config"),this.fallbackToNormalFlow();console.log("[TagadaClient ".concat(this.instanceId,"] \u{1F510} Cross-domain auth detected, resolving..."));try{let i=new URLSearchParams(window.location.search).get("authCode");if(!i)return this.fallbackToNormalFlow();let o=await ut(i,t,this.state.environment.apiConfig.baseUrl,this.state.debugMode);console.log("[TagadaClient ".concat(this.instanceId,"] \u2705 Auth handoff resolved:"),{customerId:o.customer.id,role:o.customer.role,hasContext:Object.keys(o.context).length>0}),this.setToken(o.token);let r=ie(o.token);r?(this.updateState({session:r}),await this.initializeSession(r),(e=o.context)!=null&&e.funnelSessionId&&this.funnel&&this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Restoring funnel session from handoff context:"),o.context.funnelSessionId)):(console.error("[TagadaClient] Failed to decode token from handoff"),this.updateState({isInitialized:!0,isLoading:!1}));return}catch(i){console.error("[TagadaClient ".concat(this.instanceId,"] \u274C Auth handoff failed, falling back to normal flow:"),i)}}await this.fallbackToNormalFlow()}async fallbackToNormalFlow(){let t=new URLSearchParams(typeof window!="undefined"?window.location.search:"").get("token");t&&(this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] \u{1F512} URL token detected, setting immediately to prevent race condition")),this.apiClient.updateToken(t),x(t));let i=X();console.log("[TagadaClient ".concat(this.instanceId,"] Initializing token (normal flow)..."),{hasExistingToken:!!i,hasQueryToken:!!t,storeId:this.state.pluginConfig.storeId});let o=null,r=!1;if(t?(o=t,r=!0):i&&!ct(i)&&(o=i),o){this.setToken(o),r&&(this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Persisting query token to storage...")),x(o));let s=ie(o);s?(this.updateState({session:s}),await this.initializeSession(s)):(console.error("[TagadaClient] Failed to decode token"),this.updateState({isInitialized:!0,isLoading:!1}))}else{let s=this.state.pluginConfig.storeId;console.log("[TagadaClient ".concat(this.instanceId,"] No existing token, creating anonymous token..."),{hasStoreId:!!s,storeId:s}),s?await this.createAnonymousToken(s):(console.warn("[TagadaClient ".concat(this.instanceId,"] No storeId in plugin config, skipping anonymous token creation")),this.updateState({isInitialized:!0,isLoading:!1}))}}setToken(e){this.apiClient.updateToken(e),this.updateState({token:e}),this.tokenResolver&&(this.tokenResolver(e),this.tokenPromise=null,this.tokenResolver=null)}waitForToken(){return this.apiClient.getCurrentToken()?Promise.resolve(this.apiClient.getCurrentToken()):(this.tokenPromise||(this.tokenPromise=new Promise(e=>{this.tokenResolver=e})),this.tokenPromise)}async createAnonymousToken(e){if(typeof window!="undefined"){let i=new URLSearchParams(window.location.search).get("token");if(i){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] \u{1F512} URL has token, skipping anonymous token creation")),this.setToken(i),x(i);let o=ie(i);o&&(this.updateState({session:o}),await this.initializeSession(o));return}}if(this.isInitializingSession){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Session initialization in progress, skipping anonymous token creation"));return}try{let t=ee();this.state.debugMode&&console.log("[TagadaClient] Creating anonymous token for store:",e,{draft:t});let i=await this.apiClient.post("/api/v1/cms/session/anonymous",{storeId:e,role:"anonymous",draft:t},{skipAuth:!0});this.setToken(i.token),x(i.token);let o=ie(i.token);o&&(this.updateState({session:o}),await this.initializeSession(o)),this.updateState({isSessionInitialized:!0})}catch(t){console.error("[TagadaClient] Failed to create anonymous token:",t),this.updateState({isInitialized:!0,isLoading:!1})}}async initializeSession(e){var t,i,o,r,s,a,c,p,m,l,f;if(this.isInitializingSession){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Session initialization already in progress, skipping"));return}this.isInitializingSession=!0;try{this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Initializing session..."),{sessionId:e.sessionId});let u=await at(),d=lt(),w=st(),g=ee(),I=new URLSearchParams(window.location.search).get("draft");I!==null&&Ee(I==="true");let R={storeId:e.storeId,accountId:e.accountId,customerId:e.customerId,role:e.role,browserLocale:w,queryLocale:d.locale,queryCurrency:d.currency,utmSource:d.utmSource,utmMedium:d.utmMedium,utmCampaign:d.utmCampaign,gclid:d.gclid,browser:u.userAgent.browser.name,browserVersion:u.userAgent.browser.version,os:u.userAgent.os.name,osVersion:u.userAgent.os.version,deviceType:(t=u.userAgent.device)==null?void 0:t.type,deviceModel:(i=u.userAgent.device)==null?void 0:i.model,deviceVendor:(o=u.userAgent.device)==null?void 0:o.vendor,userAgent:u.userAgent.name,engineName:u.userAgent.engine.name,engineVersion:u.userAgent.engine.version,cpuArchitecture:u.userAgent.cpu.architecture,isBot:(s=(r=u.flags)==null?void 0:r.isBot)!=null?s:!1,isChromeFamily:(c=(a=u.flags)==null?void 0:a.isChromeFamily)!=null?c:!1,isStandalonePWA:(m=(p=u.flags)==null?void 0:p.isStandalonePWA)!=null?m:!1,isAppleSilicon:(f=(l=u.flags)==null?void 0:l.isAppleSilicon)!=null?f:!1,screenWidth:u.screenResolution.width,screenHeight:u.screenResolution.height,timeZone:u.timeZone,draft:g,fetchMessages:!1},y=await this.apiClient.post("/api/v1/cms/session/v2/init",R);this.lastSessionInitError=null,this.sessionInitRetryCount=0,this.updateSessionState(y,e),this.updateState({isInitialized:!0,isSessionInitialized:!0,isLoading:!1}),this.state.debugMode&&console.log("[TagadaClient] Session initialized successfully")}catch(u){this.lastSessionInitError=u,this.sessionInitRetryCount++,console.error("[TagadaClient] Error initializing session (attempt ".concat(this.sessionInitRetryCount,"/").concat(this.MAX_SESSION_INIT_RETRIES,"):"),u),this.updateState({isInitialized:!0,isLoading:!1})}finally{this.isInitializingSession=!1}}updateSessionState(e,t){var s,a,c,p,m,l,f,u,d,w;if(e.store){let g=e.store,I=b(h({},e.store),{accountId:g.accountId||((s=this.state.pluginConfig)==null?void 0:s.accountId)||t.accountId||"",presentmentCurrencies:g.presentmentCurrencies||[e.store.currency||"USD"],chargeCurrencies:g.chargeCurrencies||[e.store.currency||"USD"]});this.updateState({store:I})}if(e.locale){let g={locale:e.locale,language:e.locale.split("-")[0],region:(a=e.locale.split("-")[1])!=null?a:"US",messages:(c=e.messages)!=null?c:{}};this.updateState({locale:g})}if(e.store){let g={code:e.store.currency,symbol:this.getCurrencySymbol(e.store.currency),name:this.getCurrencyName(e.store.currency)};this.updateState({currency:g})}let i={isAuthenticated:(m=(p=e.customer)==null?void 0:p.isAuthenticated)!=null?m:!1,isLoading:!1,customer:(l=e.customer)!=null?l:null,session:t};this.updateState({customer:(f=e.customer)!=null?f:null,auth:i});let o=(u=this.config.features)==null?void 0:u.funnel,r=typeof o=="object"&&o.skipAutoInit;if(this.funnel&&!r&&t.customerId&&((d=e.store)!=null&&d.id)){let g=e.store.accountId||((w=this.state.pluginConfig)==null?void 0:w.accountId)||t.accountId||"";if(g){let R=new URLSearchParams(typeof window!="undefined"?window.location.search:"").get("funnelId")||void 0;this.state.debugMode&&console.log("[TagadaClient] Auto-initializing funnel...",{customerId:t.customerId,storeId:e.store.id,accountId:g,funnelId:R||"auto-detect"}),this.funnel.autoInitialize({customerId:t.customerId,sessionId:t.sessionId},{id:e.store.id,accountId:g},R).catch(y=>{console.error("[TagadaClient] Funnel auto-initialization failed:",y)})}else console.warn("[TagadaClient] Cannot auto-initialize funnel: accountId is missing")}}getCurrencySymbol(e){return{USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$"}[e]||e}getCurrencyName(e){return{USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar"}[e]||e}getAccountId(){var e,t,i;return((e=this.state.store)==null?void 0:e.accountId)||((t=this.state.pluginConfig)==null?void 0:t.accountId)||((i=this.state.session)==null?void 0:i.accountId)||""}updatePluginConfig(e){this.state.debugMode&&console.log("[TagadaClient] Hot-reloading config:",e);let t=h(h({},this.state.pluginConfig.config),e);this.updateState({pluginConfig:b(h({},this.state.pluginConfig),{config:t})}),this.bus.emit("CONFIG_UPDATED",t),this.state.debugMode&&console.log("[TagadaClient] Config updated successfully")}setupConfigHotReload(){if(typeof window=="undefined")return;let e=t=>{var i,o;if(((i=t.data)==null?void 0:i.type)==="TAGADAPAY_CONFIG_UPDATE"){let{config:r}=t.data;this.state.debugMode&&console.log("[TagadaClient] Received config update from parent:",r),this.updatePluginConfig(r)}else if(((o=t.data)==null?void 0:o.type)==="APPLY_STYLES_TO_ELEMENT"){let{elementId:r,styles:s}=t.data;this.state.debugMode&&console.log("[TagadaClient] Received style application request:",{elementId:r,styles:s}),this.applyStylesToElement(r,s)}};window.addEventListener("message",e),this.state.debugMode&&console.log("[TagadaClient] Config hot-reload and style manipulation listeners enabled")}applyStylesToElement(e,t){if(typeof document=="undefined")return;let i="tagada-editor-highlight",o=document.getElementById(i);o&&o.remove();let r=l=>{var y;let u=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]).has(l.tagName.toLowerCase()),d=l;if(u){let T=l.parentElement;if((T==null?void 0:T.getAttribute("data-tagada-highlight-wrapper"))==="true"&&T instanceof HTMLElement)d=T;else{let v=document.createElement("div");v.setAttribute("data-tagada-highlight-wrapper","true");let oe=window.getComputedStyle(l),z=oe.display;if(z==="inline"?v.style.display="inline-block":v.style.display=z,v.style.position="relative",z==="inline"||z.includes("inline")){let D=oe.verticalAlign;D&&D!=="baseline"&&(v.style.verticalAlign=D)}["width","height","minWidth","minHeight","maxWidth","maxHeight","flex","flexGrow","flexShrink","flexBasis","gridColumn","gridRow","gridColumnStart","gridColumnEnd","gridRowStart","gridRowEnd","gridArea","alignSelf","justifySelf","boxSizing","gap","rowGap","columnGap","order","aspectRatio"].forEach(D=>{let W=D.replace(/([A-Z])/g,"-$1").toLowerCase(),A=oe.getPropertyValue(W);A&&A.trim()!==""&&(D==="flex"&&A!=="none"&&A!=="0 1 auto"?v.style.flex=A:D==="boxSizing"?v.style.boxSizing=A:v.style.setProperty(W,A))}),l.style&&["width","height","min-width","min-height","max-width","max-height","flex","flex-grow","flex-shrink","flex-basis","grid-column","grid-row","grid-column-start","grid-column-end","grid-row-start","grid-row-end","grid-area","align-self","justify-self","box-sizing","gap","row-gap","column-gap","order","aspect-ratio"].forEach(W=>{let A=l.style.getPropertyValue(W);A&&v.style.setProperty(W,A)}),(y=l.parentNode)==null||y.insertBefore(v,l),v.appendChild(l),d=v}}let w=getComputedStyle(u?l:d);(d.style.position==="static"||!d.style.position)&&(d.style.position="relative");let g=document.createElement("div");g.id=i,g.style.position="absolute",g.style.inset="0",g.style.pointerEvents="none",g.style.zIndex="9999",g.style.boxSizing="border-box",g.style.background="none",g.style.border="none",g.style.outline="none",g.style.margin="0",g.style.padding="0";let I=w.borderRadius;I&&(g.style.borderRadius=I),d.appendChild(g);let R=t||{boxShadow:"0 0 0 2px rgb(239 68 68)"};if(Object.entries(R).forEach(([T,q])=>{let v=T.includes("-")?T.replace(/-([a-z])/g,(oe,z)=>z.toUpperCase()):T;T.includes("-")?g.style.setProperty(T,q):g.style[v]=q}),l.scrollIntoView({behavior:"smooth",block:"center"}),this.state.debugMode){let T=Object.entries(R).map(([q,v])=>"".concat(q,": ").concat(v)).join("; ");console.log("[TagadaClient] Applied styles to highlight div of element #".concat(e,":"),T)}},s=5,a=1e3,c=0,p=l=>{let f=window.getComputedStyle(l);return f.display==="none"||f.visibility==="hidden"||f.opacity==="0"||l.hidden||l.offsetWidth===0||l.offsetHeight===0},m=()=>{let l=document.querySelectorAll('[editor-id~="'.concat(e,'"]'));if(l.length===0){if(c+=1,c>=s){this.state.debugMode&&console.warn('[TagadaClient] Element with editor-id containing "'.concat(e,'" not found after ').concat(s," attempts"));return}this.state.debugMode&&console.warn('[TagadaClient] Element with editor-id containing "'.concat(e,'" not found (attempt ').concat(c,"/").concat(s,"), retrying in ").concat(a/1e3,"s")),setTimeout(m,a);return}let f=null;if(l.length===1)f=l[0];else{for(let u=0;u<l.length;u++)if(!p(l[u])){f=l[u];break}f||(f=l[0])}f&&r(f)};m()}};pe();function un(){if(typeof window=="undefined"||typeof document=="undefined")return[];let n=P();return n!=null&&n.scripts?n.scripts.filter(e=>e.enabled):[]}function fn(n,e){let t=n.position||"body-end",i="tagada-stepconfig-script-".concat(e);if(document.getElementById(i))return;let o=n.content.trim(),r=o.match(/^<script[^>]*>([\s\S]*)<\/script>$/i);if(r&&(o=r[1].trim()),!o)return;let s="(function() {\n try {\n // Script: "+n.name+"\n"+o+'\n } catch (error) {\n console.error("[TagadaPay] StepConfig script error:", error);\n }\n})();',a=document.createElement("script");switch(a.id=i,a.setAttribute("data-tagada-stepconfig-script","true"),a.setAttribute("data-script-name",n.name),a.textContent=s,t){case"head-start":document.head.firstChild?document.head.insertBefore(a,document.head.firstChild):document.head.appendChild(a);break;case"head-end":document.head.appendChild(a);break;case"body-start":document.body.firstChild?document.body.insertBefore(a,document.body.firstChild):document.body.appendChild(a);break;case"body-end":default:document.body.appendChild(a);break}}function gt(){let n=un();n.length!==0&&n.forEach((e,t)=>{fn(e,t)})}if(typeof window!="undefined"&&typeof document!="undefined"){let n=()=>{document.body?gt():document.addEventListener("DOMContentLoaded",gt,{once:!0})};"requestIdleCallback"in window?window.requestIdleCallback(n,{timeout:100}):setTimeout(n,0)}function pt(n={}){return new ve(n)}j();var _e="1.0.0";function mt(n){return typeof window=="undefined"?null:new URLSearchParams(window.location.search).get(n)}function S(n,...e){n&&console.log("[TagadaTracker]",...e)}function ht(...n){console.warn("[TagadaTracker]",...n)}function gn(n){if(!n.storeId||typeof n.storeId!="string")throw new Error("TagadaTracker: storeId is required and must be a non-empty string.");if(!n.accountId||typeof n.accountId!="string")throw new Error("TagadaTracker: accountId is required and must be a non-empty string.");if(!n.stepId||typeof n.stepId!="string")throw new Error("TagadaTracker: stepId is required and must be a non-empty string.");if(n.apiBaseUrl)try{new URL(n.apiBaseUrl)}catch(e){throw new Error('TagadaTracker: apiBaseUrl is not a valid URL: "'.concat(n.apiBaseUrl,'"'))}}async function pn(n,e,t){let i;for(let o=0;o<=e;o++)try{return await n()}catch(r){if(i=r instanceof Error?r:new Error(String(r)),o<e){let s=Math.min(1e3*2**o,8e3);S(t,"Retry ".concat(o+1,"/").concat(e," in ").concat(s,"ms...")),await new Promise(a=>setTimeout(a,s))}}throw i}var Se=class{constructor(){this.config=null;this.client=null;this.initialized=!1;this.initializing=!1;this.unsubscribe=null;this.version=_e}async init(e){var i,o;if(this.initialized)return S(e.debug||!1,"Already initialized \u2014 returning existing session."),this.getSession();if(this.initializing)return S(e.debug||!1,"Initialization in progress \u2014 skipping duplicate call."),null;this.initializing=!0,this.config=h({debug:!1},e);let t=this.config.debug;try{gn(this.config)}catch(r){this.initializing=!1;let s=r instanceof Error?r:new Error(String(r));if(this.config.onError)return this.config.onError(s),null;throw s}S(t,"\u{1F680} Initializing external tracker v".concat(_e),{storeId:e.storeId,accountId:e.accountId,stepId:e.stepId,funnelId:e.funnelId});try{let r=mt("token");r&&(x(r),S(t,"\u{1F511} Bootstrapped token from URL")),this.client=pt({debugMode:t,features:{funnel:{skipAutoInit:!0}},rawPluginConfig:{storeId:this.config.storeId,accountId:this.config.accountId},customApiConfig:this.config.apiBaseUrl?{apiConfig:{baseUrl:this.config.apiBaseUrl.trim()}}:void 0}),await this.waitForClientReady();let s=await pn(()=>this.initializeFunnel(),2,t);S(t,"\u2705 Session initialized:",s),this.initialized=!0;let a=this.getSession();return a&&((o=(i=this.config).onReady)==null||o.call(i,a)),a}catch(r){let s=r instanceof Error?r:new Error(String(r));if(S(t,"\u274C Initialization failed:",s),this.config.onError)return this.config.onError(s),null;throw s}finally{this.initializing=!1}}getSession(){var t,i;if(!((i=(t=this.client)==null?void 0:t.funnel)!=null&&i.state.context))return null;let e=this.client.funnel.state.context;return{sessionId:e.sessionId,customerId:e.customerId,storeId:e.storeId,funnelId:e.funnelId,currentStepId:e.currentStepId,cmsToken:this.client.state.token||void 0}}isReady(){var e,t;return this.initialized&&!!((t=(e=this.client)==null?void 0:e.funnel)!=null&&t.state.context)}async navigate(e){if(!this.isReady())throw new Error("TagadaTracker: not initialized. Call init() first.");S(this.config.debug,"\u{1F680} Navigating:",e);let t=e.autoRedirect!==!1;try{let i=await this.client.funnel.navigate({type:e.eventType,data:e.eventData||{}},{autoRedirect:!1});return i!=null&&i.url?(S(this.config.debug,"\u2705 Navigation result:",i.url),t&&typeof window!="undefined"&&(window.location.href=e.returnUrl||i.url),{url:i.url}):null}catch(i){throw S(this.config.debug,"\u274C Navigation failed:",i),i}}async trackEvent(e){if(!this.isReady()){ht("trackEvent called before init \u2014 event dropped:",e.name);return}S(this.config.debug,"\u{1F4CA} Tracking event:",e.name,e.data);try{await this.client.funnel.navigate({type:e.name,data:e.data||{}},{autoRedirect:!1})}catch(t){S(this.config.debug,"\u26A0\uFE0F Event tracking failed (non-critical):",e.name)}}getCustomerId(){var e,t,i,o,r;return((t=(e=this.client)==null?void 0:e.state.auth.customer)==null?void 0:t.id)||((r=(o=(i=this.client)==null?void 0:i.funnel)==null?void 0:o.state.context)==null?void 0:r.customerId)||null}getFunnelSessionId(){var e,t,i;return((i=(t=(e=this.client)==null?void 0:e.funnel)==null?void 0:t.state.context)==null?void 0:i.sessionId)||null}buildUrl(e,t){let i=this.getSession();if(!i)return e;let o=new URL(e,typeof window!="undefined"?window.location.origin:void 0);return o.searchParams.set("funnelSessionId",i.sessionId),i.cmsToken&&o.searchParams.set("token",i.cmsToken),i.funnelId&&o.searchParams.set("funnelId",i.funnelId),o.searchParams.set("storeId",i.storeId),t&&Object.entries(t).forEach(([r,s])=>{o.searchParams.set(r,s)}),o.toString()}getClient(){return this.client}async reset(e){var o,r;if(!this.client||!this.config)throw new Error("TagadaTracker: not initialized. Call init() first.");S(this.config.debug,"\u{1F504} Resetting to step:",e),this.config.stepId=e;let t=await this.initializeFunnel(),i=this.getSession();return i&&((r=(o=this.config).onReady)==null||r.call(o,i)),i}destroy(){var e,t;this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.client&&((t=(e=this.client).destroy)==null||t.call(e)),this.client=null,this.config=null,this.initialized=!1,this.initializing=!1,S(!1,"\u{1F5D1}\uFE0F Tracker destroyed")}async waitForClientReady(){if(this.client)return new Promise(e=>{var o;if((o=this.client)!=null&&o.state.isInitialized){e();return}let t=!1,i=setTimeout(()=>{var r;t||(t=!0,S(((r=this.config)==null?void 0:r.debug)||!1,"\u23F1\uFE0F Client ready timeout \u2014 proceeding"),e())},1e4);this.unsubscribe=this.client.subscribe(()=>{var r;!t&&((r=this.client)!=null&&r.state.isInitialized)&&(t=!0,clearTimeout(i),e())})})}async initializeFunnel(){var s,a,c;if(!((s=this.client)!=null&&s.funnel))return null;let e=(a=this.client.state.auth.customer)==null?void 0:a.id,t=(c=this.client.state.auth.session)==null?void 0:c.sessionId;!e&&!t&&ht("No auth session available \u2014 funnel init may fail.");let i={customerId:e||"anon_placeholder",sessionId:t||"sess_placeholder"},o={id:this.config.storeId,accountId:this.config.accountId},r=this.config.stepId;return S(this.config.debug,"\u{1F50D} Initializing funnel at step:",r),this.client.funnel.initialize(i,o,this.config.funnelId||mt("funnelId")||void 0,r)}},yt=new Se;typeof window!="undefined"&&(window.TagadaTracker=yt);return bt(mn);})();
7
7
  // Expose TagadaTracker globally (if not already done in bundle)
8
8
  if (typeof window !== 'undefined' && TagadaTrackerBundle && TagadaTrackerBundle.TagadaTracker) {
9
9
  window.TagadaTracker = TagadaTrackerBundle.TagadaTracker;