@tagadapay/plugin-sdk 3.1.24 → 3.1.25

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 (39) hide show
  1. package/dist/external-tracker.js +243 -2871
  2. package/dist/external-tracker.min.js +2 -2
  3. package/dist/external-tracker.min.js.map +4 -4
  4. package/dist/react/hooks/useCheckout.js +7 -2
  5. package/dist/tagada-react-sdk-minimal.min.js +2 -2
  6. package/dist/tagada-react-sdk-minimal.min.js.map +3 -3
  7. package/dist/tagada-react-sdk.js +340 -173
  8. package/dist/tagada-react-sdk.min.js +2 -2
  9. package/dist/tagada-react-sdk.min.js.map +3 -3
  10. package/dist/tagada-sdk.js +776 -3327
  11. package/dist/tagada-sdk.min.js +2 -2
  12. package/dist/tagada-sdk.min.js.map +4 -4
  13. package/dist/v2/core/client.js +1 -0
  14. package/dist/v2/core/funnelClient.d.ts +8 -0
  15. package/dist/v2/core/funnelClient.js +1 -1
  16. package/dist/v2/core/resources/apiClient.d.ts +18 -14
  17. package/dist/v2/core/resources/apiClient.js +151 -109
  18. package/dist/v2/core/resources/checkout.d.ts +1 -1
  19. package/dist/v2/core/resources/index.d.ts +1 -1
  20. package/dist/v2/core/resources/index.js +1 -1
  21. package/dist/v2/core/resources/offers.js +4 -4
  22. package/dist/v2/core/resources/payments.d.ts +1 -0
  23. package/dist/v2/core/utils/currency.d.ts +3 -0
  24. package/dist/v2/core/utils/currency.js +40 -2
  25. package/dist/v2/core/utils/deviceInfo.d.ts +1 -0
  26. package/dist/v2/core/utils/deviceInfo.js +1 -0
  27. package/dist/v2/core/utils/previewMode.js +12 -0
  28. package/dist/v2/react/components/ApplePayButton.js +39 -16
  29. package/dist/v2/react/components/StripeExpressButton.js +1 -2
  30. package/dist/v2/react/hooks/payment-actions/useAirwallexRadarAction.js +1 -0
  31. package/dist/v2/react/hooks/useApiQuery.d.ts +1 -1
  32. package/dist/v2/react/hooks/useApiQuery.js +1 -1
  33. package/dist/v2/react/hooks/useCheckoutQuery.js +6 -2
  34. package/dist/v2/react/hooks/usePreviewOffer.js +1 -1
  35. package/dist/v2/react/providers/ExpressPaymentMethodsProvider.d.ts +7 -0
  36. package/dist/v2/react/providers/ExpressPaymentMethodsProvider.js +97 -9
  37. package/dist/v2/react/providers/TagadaProvider.js +1 -1
  38. package/dist/v2/standalone/payment-service.js +1 -0
  39. package/package.json +1 -1
@@ -1,9 +1,9 @@
1
1
  /**
2
- * TagadaPay External Tracker v3.1.24
2
+ * TagadaPay External Tracker v3.1.25
3
3
  * CDN Bundle - Standalone tracking for external pages
4
4
  * @license MIT
5
5
  */
6
- "use strict";var TagadaTrackerBundle=(()=>{var Ve=Object.defineProperty,jo=Object.defineProperties,zo=Object.getOwnPropertyDescriptor,$o=Object.getOwnPropertyDescriptors,Ho=Object.getOwnPropertyNames,gn=Object.getOwnPropertySymbols;var mn=Object.prototype.hasOwnProperty,qo=Object.prototype.propertyIsEnumerable;var ae=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Vo=t=>{throw TypeError(t)};var pn=(t,e,n)=>e in t?Ve(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,S=(t,e)=>{for(var n in e||(e={}))mn.call(e,n)&&pn(t,n,e[n]);if(gn)for(var n of gn(e))qo.call(e,n)&&pn(t,n,e[n]);return t},N=(t,e)=>jo(t,$o(e));var Y=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ke=(t,e)=>{for(var n in e)Ve(t,n,{get:e[n],enumerable:!0})},Ko=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ho(e))!mn.call(t,i)&&i!==n&&Ve(t,i,{get:()=>e[i],enumerable:!(o=zo(e,i))||o.enumerable});return t};var Wo=t=>Ko(Ve({},"__esModule",{value:!0}),t);var te=function(t,e){this[0]=t,this[1]=e},Rt=(t,e,n)=>{var o=(s,a,c,u)=>{try{var d=n[s](a),g=(a=d.value)instanceof te,y=d.done;Promise.resolve(g?a[0]:a).then(m=>g?o(s==="return"?s:"next",a[1]?{done:m.done,value:m.value}:m,c,u):c({value:m,done:y})).catch(m=>o("throw",m,c,u))}catch(m){u(m)}},i=s=>r[s]=a=>new Promise((c,u)=>o(s,a,c,u)),r={};return n=n.apply(t,e),r[ae("asyncIterator")]=()=>r,i("next"),i("throw"),i("return"),r},At=t=>{var e=t[ae("asyncIterator")],n=!1,o,i={};return e==null?(e=t[ae("iterator")](),o=r=>i[r]=s=>e[r](s)):(e=e.call(t),o=r=>i[r]=s=>{if(n){if(n=!1,r==="throw")throw s;return s}return n=!0,{done:!1,value:new te(new Promise(a=>{var c=e[r](s);c instanceof Object||Vo("Object expected"),a(c)}),1)}}),i[ae("iterator")]=()=>i,o("next"),"throw"in e?o("throw"):i.throw=r=>{throw r},"return"in e&&o("return"),i},hn=(t,e,n)=>(e=t[ae("asyncIterator")])?e.call(t):(t=t[ae("iterator")](),e={},n=(o,i)=>(i=t[o])&&(e[o]=r=>new Promise((s,a,c)=>(r=i.call(t,r),c=r.done,Promise.resolve(r.value).then(u=>s({value:u,done:c}),a)))),n("next"),n("return"),e);function wn(t){var o;if(typeof document=="undefined")return null;let n="; ".concat(document.cookie).split("; ".concat(t,"="));return n.length===2&&((o=n.pop())==null?void 0:o.split(";").shift())||null}function Cn(t="local"){let e=yn[t];if(!e)return console.warn("Unknown environment: ".concat(t,". Falling back to local.")),{environment:"local",apiConfig:yn.local};let n=null;if(typeof window!="undefined"&&(n=new URLSearchParams(window.location.search).get("tagadaClientBaseUrl"),!n))try{n=localStorage.getItem("tgd_client_base_url")||wn("tgd_client_base_url")}catch(i){}return n?(console.log("[SDK] Using custom API base URL override: ".concat(n)),{environment:t,apiConfig:N(S({},e),{baseUrl:n})}):{environment:t,apiConfig:e}}function Te(){var i;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")||wn("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 n=window.location.hostname,o=window.location.href;if(console.log('[SDK] detectEnvironment() - hostname: "'.concat(n,'"')),n==="localhost"||n.startsWith("127.")||n.startsWith("192.168.")||n.startsWith("10.")||n.includes(".local")||n===""||n==="0.0.0.0"||n.includes("ngrok-free.dev")||n.includes("ngrok-free.app")||n.includes("ngrok.io")||n.includes("ngrok.app")||n.includes(".loclx.io")){if(console.log("[SDK] detectEnvironment() - returning LOCAL"),typeof window!="undefined"&&((i=window==null?void 0:window.__TAGADA_ENV__)!=null&&i.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 n==="app.tagadapay.com"||n.includes("tagadapay.com")||n.includes("yourproductiondomain.com")?"production":n==="app.tagadapay.dev"||n.includes("tagadapay.dev")||n.includes("vercel.app")||n.includes("netlify.app")||n.includes("surge.sh")||n.includes("github.io")||n.includes("herokuapp.com")||n.includes("railway.app")||o.includes("?env=dev")||o.includes("?dev=true")||o.includes("#dev")?"development":(console.warn("[SDK] Unknown domain: ".concat(n,", defaulting to production")),"production")}function Ee(t=!1){return Te()!=="local"?!1:t&&typeof window!="undefined"?!window.location.hostname.includes(".cdn."):!0}var yn,We=Y(()=>{"use strict";yn={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 Ge,Sn=Y(()=>{"use strict";Ge=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,n){return this.apiClient.patch("/api/v1/funnel/context/".concat(e),n)}async endSession(e){return this.apiClient.delete("/api/v1/funnel/session/".concat(e))}async getSession(e,n,o){let i=new URLSearchParams;n&&i.append("currentUrl",n),o&&i.append("includeDebugData","true");let r="/api/v1/funnel/session/".concat(e).concat(i.toString()?"?".concat(i):"");return this.apiClient.get(r)}}});var le,kt=Y(()=>{"use strict";le=class{constructor(){this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){this.listeners.forEach(n=>{try{n(e)}catch(o){console.error("Error in event listener:",o)}})}clear(){this.listeners.clear()}}});function L(t){if(typeof window!="undefined")try{let n=localStorage.getItem(Je)!==t;localStorage.setItem(Je,t),n&&window.dispatchEvent(new Event("storage"))}catch(e){console.error("Failed to save token to localStorage:",e)}}function xe(){if(typeof window!="undefined")try{return localStorage.getItem(Je)}catch(t){return console.error("Failed to get token from localStorage:",t),null}return null}function ce(){if(typeof window!="undefined")try{localStorage.removeItem(Je)}catch(t){console.error("Failed to clear token from localStorage:",t)}}var Je,ue=Y(()=>{"use strict";Je="cms_token"});function bn(t){typeof document!="undefined"&&(document.cookie="".concat(Pt,"=").concat(t,"; path=/; max-age=2592000; SameSite=Lax"))}function In(){if(typeof document=="undefined")return;let t=document.cookie.split("; ").find(e=>e.startsWith("".concat(Pt,"=")));return t?t.split("=")[1]:void 0}function Xe(){typeof document!="undefined"&&(document.cookie="".concat(Pt,"=; path=/; max-age=0"))}var Pt,Ye=Y(()=>{"use strict";Pt="tgd-funnel-session-id"});function de(t){if(typeof window=="undefined")return null;try{return localStorage.getItem(t)}catch(e){return null}}function Ze(t,e){if(typeof window!="undefined")try{localStorage.setItem(t,e)}catch(n){}}function ve(t){var o;if(typeof document=="undefined")return null;let n=document.cookie.split(";").find(i=>i.trim().startsWith("".concat(t,"=")));return n?(o=n.split("=")[1])==null?void 0:o.trim():null}function _t(t,e,n=86400){if(typeof document!="undefined"){if(t==="tgd_draft"||t==="tgd-draft"){console.warn("\u{1F6E1}\uFE0F [SDK] Blocked attempt to set ".concat(t," as cookie - this should only be in localStorage"));return}document.cookie="".concat(t,"=").concat(e,"; path=/; max-age=").concat(n)}}function En(t){typeof document!="undefined"&&(document.cookie="".concat(t,"=; path=/; max-age=0"))}function ne(){if(typeof window=="undefined")return{};let t=new URLSearchParams(window.location.search),e,n=t.get("draft");if(n!==null)e=n==="true";else{let C=de(x.DRAFT);C!==null&&(e=C==="true")}let o,i=t.get("funnelTracking");if(i!==null)o=i!=="false";else{let C=de(x.FUNNEL_TRACKING)||ve(x.FUNNEL_TRACKING);C!==null&&(o=C!=="false")}let r=t.get("token")||xe()||null,s=t.get("funnelSessionId")||null,a=t.get("funnelId")||null,c,u=t.get("funnelEnv");u&&(u==="staging"||u==="production")&&(c=u);let d=t.get("forceReset")==="true",g,y=t.get("tagadaClientEnv");if(y&&(y==="production"||y==="development"||y==="local"))g=y;else{let C=de(x.CLIENT_ENV)||ve(x.CLIENT_ENV);C&&(C==="production"||C==="development"||C==="local")&&(g=C)}let m,f=t.get("tagadaClientBaseUrl");if(f)m=f;else{let C=de(x.CLIENT_BASE_URL)||ve(x.CLIENT_BASE_URL);C&&(m=C)}let h,p=t.get("currency");if(p)h=p;else{let C=de(x.CURRENCY)||ve(x.CURRENCY);C&&(h=C)}let b,E=t.get("locale");if(E)b=E;else{let C=de(x.LOCALE)||ve(x.LOCALE);C&&(b=C)}return{forceReset:d,token:r,funnelSessionId:s,funnelId:a,draft:e,funnelTracking:o,funnelEnv:c,tagadaClientEnv:g,tagadaClientBaseUrl:m,currency:h,locale:b}}function Re(){var e;return(e=ne().draft)!=null?e:!1}function Ft(t){if(typeof window!="undefined")if(t)Ze(x.DRAFT,"true");else try{localStorage.removeItem(x.DRAFT)}catch(e){}}function xn(t=!1){let e=null;typeof window!="undefined"&&(e=new URLSearchParams(window.location.search).get("token"));let n=ne(),o=n.forceReset||!1;if(!o&&!n.token)return Tn(),!1;t&&(console.log("[SDK] Detected params:",n),console.log("[SDK] URL token (direct read):",e?e.substring(0,20)+"...":"none")),o&&(t&&console.log("[SDK] Force reset: Clearing all stored state"),ce(),Xe(),typeof window!="undefined"&&window.localStorage&&Object.keys(localStorage).forEach(s=>{(s.startsWith("tagadapay_")||s.startsWith("tgd_"))&&(t&&console.log("[SDK] Clearing localStorage: ".concat(s)),localStorage.removeItem(s))}));let i=e||n.token;return i!=null?(t&&console.log("[SDK] Setting token from URL:",i.substring(0,20)+"..."),i===""||i==="null"?ce():(L(i),t&&console.log("[SDK] \u2705 Token set in localStorage immediately after clear"))):o&&(t&&console.log("[SDK] Force reset mode (no token in URL)"),ce()),Tn(),n.funnelSessionId&&t&&console.log("[SDK] Using funnelSessionId from URL:",n.funnelSessionId),o}function Tn(){if(typeof window=="undefined")return;let t=new URLSearchParams(window.location.search),e=t.get("draft");e!==null&&Ft(e==="true");let n=t.get("funnelTracking");n!==null&&Go(n!=="false");let o=t.get("tagadaClientEnv");o&&(o==="production"||o==="development"||o==="local")&&Jo(o);let i=t.get("tagadaClientBaseUrl");i&&Xo(i)}function Go(t){if(typeof window=="undefined")return;let e=t?"true":"false";Ze(x.FUNNEL_TRACKING,e),_t(x.FUNNEL_TRACKING,e,86400)}function Jo(t){typeof window!="undefined"&&(Ze(x.CLIENT_ENV,t),_t(x.CLIENT_ENV,t,86400))}function vn(){if(typeof window!="undefined")try{localStorage.removeItem(x.CLIENT_ENV),En(x.CLIENT_ENV)}catch(t){}}function Xo(t){typeof window!="undefined"&&(Ze(x.CLIENT_BASE_URL,t),_t(x.CLIENT_BASE_URL,t,86400))}function Rn(){if(typeof window!="undefined")try{localStorage.removeItem(x.CLIENT_BASE_URL),En(x.CLIENT_BASE_URL)}catch(t){}}function An(){var e;return(e=ne().funnelTracking)!=null?e:!0}var x,Qe=Y(()=>{"use strict";ue();Ye();x={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 kn={};Ke(kn,{injectPreviewModeIndicator:()=>Zo,isIndicatorInjected:()=>ei,removePreviewModeIndicator:()=>Qo});function Nt(t){if(typeof window=="undefined"||typeof document=="undefined")return;let e=window.location.hostname,n=e.split("."),o=["",e,"."+e];for(let a=1;a<n.length;a++){let c=n.slice(a).join(".");o.push(c),o.push("."+c)}let i=window.location.pathname.split("/").filter(a=>a),r=["/"],s="";i.forEach(a=>{s+="/"+a,r.push(s)}),o.forEach(a=>{r.forEach(c=>{let u="".concat(t,"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=").concat(c),d=a?"; domain=".concat(a):"";document.cookie=u+d,document.cookie=u+d+"; secure",document.cookie=u+d+"; SameSite=None; secure",document.cookie=u+d+"; SameSite=Lax",document.cookie=u+d+"; SameSite=Strict"})})}function Yo(){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)}ce(),Xe(),vn(),Rn(),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=>Nt(r)),["tgd-draft","tgd_draft","tgd.draft","tgddraft"].forEach(r=>Nt(r)),document.cookie&&document.cookie.split(";").forEach(s=>{let a=s.split("=")[0].trim();if(!a)return;let c=window.location.hostname,u=c.split("."),d=["",c,"."+c];for(let f=1;f<u.length;f++){let h=u.slice(f).join(".");d.push(h),d.push("."+h)}let g=window.location.pathname.split("/").filter(f=>f),y=["/"],m="";g.forEach(f=>{m+="/"+f,y.push(m)}),d.forEach(f=>{y.forEach(h=>{let p="".concat(a,"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=").concat(h),b=f?"; domain=".concat(f):"";document.cookie=p+b,document.cookie=p+b+"; secure",document.cookie=p+b+"; SameSite=None; secure",document.cookie=p+b+"; SameSite=Lax",document.cookie=p+b+"; SameSite=Strict",document.cookie=p+b+"; secure; SameSite=None",document.cookie=p+b+"; secure; SameSite=Lax",document.cookie=p+b+"; secure; SameSite=Strict"})})}),setTimeout(()=>{window.localStorage&&localStorage.length>0&&localStorage.clear(),Nt("tgd_draft"),typeof window.stop=="function"&&window.stop(),window.location.replace(e.href)},10)}function Zo(){if(et||typeof window=="undefined"||typeof document=="undefined")return;let t=ne(),e=Re(),n=!An(),o=!!(t.tagadaClientEnv||t.tagadaClientBaseUrl);if(!e&&!n&&!o)return;let i=document.createElement("div");i.id="tgd-preview-indicator",i.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 '),n&&(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 '),t.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(t.funnelEnv,"\n </span>\n </div>\n ")),t.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(t.tagadaClientEnv,"\n </span>\n </div>\n ")),t.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(t.tagadaClientBaseUrl,"\n </div>\n </div>\n ")),t.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(t.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 u=!1,d=()=>{u=!0,s.style.display="block",a.style.display="block"},g=()=>{u=!1,setTimeout(()=>{u||(s.style.display="none",a.style.display="none")},100)};r.addEventListener("mouseenter",d),r.addEventListener("mouseleave",g),a.addEventListener("mouseenter",d),a.addEventListener("mouseleave",g),s.addEventListener("mouseenter",d),s.addEventListener("mouseleave",g);let y=s.querySelector("#tgd-leave-preview");y&&(y.addEventListener("mouseenter",()=>{y.style.opacity="0.8"}),y.addEventListener("mouseleave",()=>{y.style.opacity="1"}),y.addEventListener("click",m=>{m.stopPropagation(),Yo()})),i.appendChild(r),i.appendChild(a),i.appendChild(s),document.body.appendChild(i),fe=i,et=!0}function Qo(){fe&&fe.parentNode&&(fe.parentNode.removeChild(fe),fe=null,et=!1)}function ei(){return et}var fe,et,Pn=Y(()=>{"use strict";Qe();ue();Ye();fe=null,et=!1});var zn={};Ke(zn,{FunnelClient:()=>ke,TrackingProvider:()=>On,findMethod:()=>Un,getAssignedOrderBumpOfferIds:()=>ui,getAssignedPaymentFlowId:()=>Bn,getAssignedPixels:()=>ci,getAssignedResources:()=>jn,getAssignedScripts:()=>li,getAssignedStaticResources:()=>ai,getAssignedStepConfig:()=>V,getAssignedUpsellOfferIds:()=>di,getEnabledMethods:()=>Dn,getExpressMethods:()=>Ln,getExpressMethodsByProcessor:()=>ti,getLocalFunnelConfig:()=>Mn,isMethodEnabled:()=>ni,loadLocalFunnelConfig:()=>ri});function Dn(t){return t?Object.values(t).filter(e=>e.enabled):[]}function Ln(t){return Dn(t).filter(e=>e.express)}function ti(t){let e={};for(let n of Ln(t)){let o=n.processorId||n.integrationId||n.provider;e[o]||(e[o]=[]),e[o].push(n)}return e}function Un(t,e){if(t){for(let n of Object.values(t))if(n.method===e&&n.enabled)return n}}function ni(t,e){return!!Un(t,e)}function oi(){if(typeof window!="undefined"){if(window.__TGD_FUNNEL_ID__)return window.__TGD_FUNNEL_ID__;if(typeof document!="undefined"){let t=document.querySelector('meta[name="x-funnel-id"]');return(t==null?void 0:t.getAttribute("content"))||void 0}}}function tt(){if(typeof window!="undefined"){if(window.__TGD_FUNNEL_VARIANT_ID__)return window.__TGD_FUNNEL_VARIANT_ID__;if(typeof document!="undefined"){let t=document.querySelector('meta[name="x-funnel-variant-id"]');return(t==null?void 0:t.getAttribute("content"))||void 0}}}function Ae(){if(typeof window!="undefined"){if(window.__TGD_FUNNEL_STEP_ID__)return window.__TGD_FUNNEL_STEP_ID__;if(typeof document!="undefined"){let t=document.querySelector('meta[name="x-funnel-step-id"]');return(t==null?void 0:t.getAttribute("content"))||void 0}}}function Fn(t){if(!t||typeof t!="string")return;let e=t.trim();if(!e)return;let n=[()=>JSON.parse(e),()=>JSON.parse(decodeURIComponent(e)),()=>JSON.parse(decodeURIComponent(decodeURIComponent(e)))];for(let o of n)try{let i=o();if(i&&typeof i=="object")return i}catch(i){}typeof console!="undefined"&&console.warn("[SDK] Failed to parse stepConfig:",e.substring(0,100))}function ii(){if(typeof window=="undefined")return!1;let t=window.location.hostname;return t==="localhost"||t==="127.0.0.1"||t.endsWith(".localhost")&&!t.includes(".cdn.")}async function ri(){if(!ii())return null;if(U!==void 0)return U;if(Ot)return await new Promise(t=>setTimeout(t,100)),U!=null?U:null;Ot=!0;try{console.log("\u{1F6E0}\uFE0F [SDK] Loading local funnel config from /config/funnel.local.json...");let t=await fetch("/config/funnel.local.json");if(!t.ok)return console.log("\u{1F6E0}\uFE0F [SDK] funnel.local.json not found (this is fine in production)"),U=null,null;let e=await t.json();return console.log("\u{1F6E0}\uFE0F [SDK] \u2705 Loaded local funnel config:",e),U=e,e}catch(t){return console.log("\u{1F6E0}\uFE0F [SDK] funnel.local.json not available:",t),U=null,null}finally{Ot=!1}}function Mn(){return U!=null?U:null}function si(t){let e=S(S({},t.staticResources),t.resources);return{payment:t.paymentFlowId?{paymentFlowId:t.paymentFlowId}:void 0,resources:Object.keys(e).length>0?e:void 0,scripts:t.scripts,pixels:t.pixels,orderBumps:t.orderBumps,upsellOffers:t.upsellOffers}}function V(){if(typeof window=="undefined")return;let t=Mn();if(t)return console.log("\u{1F6E0}\uFE0F [SDK] Using local funnel.local.json (overrides injected)"),si(t);let e=window.__TGD_STEP_CONFIG__;if(e){let n=Fn(e);if(n)return n}if(typeof document!="undefined"){let n=document.querySelector('meta[name="x-step-config"]'),o=n==null?void 0:n.getAttribute("content");if(o){let i=Fn(o);if(i)return i}}}function Bn(){var n,o;let t=V(),e=(n=t==null?void 0:t.paymentSetupConfig)==null?void 0:n.card;if(e!=null&&e.paymentFlowId)return e.paymentFlowId;if((o=t==null?void 0:t.payment)!=null&&o.paymentFlowId)return t.payment.paymentFlowId;if(typeof window!="undefined"){if(window.__TGD_PAYMENT_FLOW_ID__)return window.__TGD_PAYMENT_FLOW_ID__;if(typeof document!="undefined"){let i=document.querySelector('meta[name="x-payment-flow-id"]');return(i==null?void 0:i.getAttribute("content"))||void 0}}}function jn(){let t=V(),e=t==null?void 0:t.staticResources,n=t==null?void 0:t.resources;if(!(!e&&!n))return S(S({},e),n)}function ai(){return jn()}function li(t){let e=V();if(!(e!=null&&e.scripts))return;let n=e.scripts.filter(o=>o.enabled);return t&&(n=n.filter(o=>o.position===t||!o.position&&t==="head-end")),n.length>0?n:void 0}function Nn(t){let e="containerId"in t?"containerId":"pixelId",n=t[e];if(!n||!n.includes(";")&&!n.includes(","))return[t];let o=n.split(/[;,]/).map(i=>i.trim()).filter(i=>i.length>0);return o.length<=1?[t]:o.map(i=>N(S({},t),{[e]:i}))}function ci(){let t=V(),e=t==null?void 0:t.pixels;if(!e||typeof e!="object")return;let n={};for(let[o,i]of Object.entries(e))i&&(Array.isArray(i)?n[o]=i.flatMap(r=>Nn(r)):typeof i=="object"&&(n[o]=Nn(i)));return Object.keys(n).length>0?n:void 0}function ui(){let t=V();if(t!=null&&t.orderBumps&&t.orderBumps.mode==="custom")return t.orderBumps.enabledOfferIds}function di(){let t=V();if(t!=null&&t.upsellOffers&&t.upsellOffers.mode==="custom")return t.upsellOffers.enabledUpsellIds}var _n,On,U,Ot,ke,nt=Y(()=>{"use strict";We();Sn();kt();Qe();Ye();_n=()=>Promise.resolve().then(()=>(Pn(),kn)).then(t=>t.injectPreviewModeIndicator()),On=(r=>(r.FACEBOOK="facebook",r.TIKTOK="tiktok",r.SNAPCHAT="snapchat",r.PINTEREST="pinterest",r.GTM="gtm",r))(On||{});Ot=!1;ke=class{constructor(e){this.eventDispatcher=new le;this.isInitializing=!1;this.initializationAttempted=!1;this.config=e,this.resource=new Ge(e.apiClient),this.state={context:null,isLoading:!1,isInitialized:!1,isNavigating:!1,error:null,sessionError:null}}setConfig(e){this.config=S(S({},this.config),e)}subscribe(e){return this.eventDispatcher.subscribe(e)}getState(){return this.state}getDetectedSessionId(){var o;if((o=this.state.context)!=null&&o.sessionId)return this.state.context.sessionId;if(typeof window=="undefined")return null;let n=new URLSearchParams(window.location.search).get("funnelSessionId");return n||In()||null}resetInitialization(){this.initializationAttempted=!1,this.isInitializing=!1,this.updateState({context:null,isInitialized:!1})}async autoInitialize(e,n,o){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 i=this.getDetectedSessionId(),a=new URLSearchParams(typeof window!="undefined"?window.location.search:"").get("funnelId")||o,c=oi(),u=tt(),d=Ae(),g=ne(),y=this.config.funnelId||c||a,m=this.config.stepId||d,f=typeof window!="undefined"?new URLSearchParams(window.location.search):null,h=f==null?void 0:f.get("funnelEnv");this.config.debugMode&&console.log("\u{1F680} [FunnelClient] Auto-initializing...",{existingSessionId:i,effectiveFunnelId:y,funnelVariantId:u,funnelStepId:m,draft:g.draft,funnelTracking:g.funnelTracking,funnelEnv:h,tagadaClientEnv:g.tagadaClientEnv,tagadaClientBaseUrl:g.tagadaClientBaseUrl,source:{funnelId:this.config.funnelId?"config":c?"injected":a?"url/prop":"none",stepId:this.config.stepId?"config":d?"injected":"none"}});let p=await this.resource.initialize({cmsSession:{customerId:e.customerId,sessionId:e.sessionId,storeId:n.id,accountId:n.accountId},funnelId:y,existingSessionId:i||void 0,currentUrl:typeof window!="undefined"?window.location.href:void 0,funnelVariantId:u,funnelStepId:m,draft:g.draft,funnelTracking:g.funnelTracking,funnelEnv:h||void 0,tagadaClientEnv:g.tagadaClientEnv,tagadaClientBaseUrl:g.tagadaClientBaseUrl,currency:g.currency,locale:g.locale});if(p.success&&p.context){let b=this.enrichContext(p.context);return this.handleSessionSuccess(b),_n(),b}else throw new Error(p.error||"Failed to initialize funnel session")}catch(i){let r=i instanceof Error?i:new Error(String(i));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,n,o,i){this.updateState({isLoading:!0,error:null});try{let r=tt(),s=Ae();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:n.id,accountId:n.accountId},funnelId:o,entryStepId:i,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),_n(),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,n){var o,i,r,s,a,c;if(n!=null&&n.waitForSession&&!((o=this.state.context)!=null&&o.sessionId)){this.config.debugMode&&console.log("\u23F3 [FunnelClient] Waiting for session before navigation...");let u=5e3,d=Date.now();for(;!((i=this.state.context)!=null&&i.sessionId)&&Date.now()-d<u;)await new Promise(g=>setTimeout(g,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 u=tt(),d=Ae(),g=typeof window!="undefined"?window.location.href:void 0;!d&&this.config.stepId&&(d=this.config.stepId,this.config.debugMode&&console.log("\u{1F50D} [FunnelClient.navigate] Using stepId from config (no injection):",d)),!u&&this.config.variantId&&(u=this.config.variantId,this.config.debugMode&&console.log("\u{1F50D} [FunnelClient.navigate] Using variantId from config (no injection):",u)),this.config.debugMode&&console.log("\u{1F50D} [FunnelClient.navigate] Sending to backend:",{sessionId:this.state.context.sessionId,currentUrl:g,funnelStepId:d||"(not found)",funnelVariantId:u||"(not found)",hasInjectedStepId:!!Ae(),hasInjectedVariantId:!!tt(),usedConfigFallback:!Ae()&&!!this.config.stepId,customerTags:(n==null?void 0:n.customerTags)||"(none)",deviceId:(n==null?void 0:n.deviceId)||"(none)"});let y=(n==null?void 0:n.fireAndForget)||!1,m=await this.resource.navigate({sessionId:this.state.context.sessionId,event:e,currentUrl:g,funnelStepId:d,funnelVariantId:u,fireAndForget:y,customerTags:n==null?void 0:n.customerTags,deviceId:n==null?void 0:n.deviceId});if(!m.success||!m.result)throw new Error(m.error||"Navigation failed");let f=m.result;if(f.queued)return this.updateState({isNavigating:!1,isLoading:!1}),f.sessionId&&f.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(f.sessionId)),this.state.context&&(this.state.context.sessionId=f.sessionId)),this.config.debugMode&&console.log("\u{1F525} [FunnelClient] Navigation queued (fire-and-forget mode)"),f;let h=(n==null?void 0:n.autoRedirect)!==void 0?n.autoRedirect:this.config.autoRedirect!==!1;return this.updateState({isNavigating:!1,isLoading:!1}),h&&(f!=null&&f.url)&&typeof window!="undefined"&&(this.config.debugMode&&console.log("\u{1F680} [FunnelClient] Auto-redirecting to:",f.url,"(skipped session refresh - next page will initialize)"),window.location.href=f.url),f}catch(u){let d=u instanceof Error?u:new Error(String(u));throw this.updateState({error:d,isNavigating:!1,isLoading:!1}),d}}async goToStep(e,n){return this.navigate({type:"direct_navigation",data:{targetStepId:e}},n)}async refreshSession(){var e;if((e=this.state.context)!=null&&e.sessionId)try{let n=await this.resource.getSession(this.state.context.sessionId);if(n.success&&n.context){let o=this.enrichContext(n.context);return this.updateState({context:o,sessionError:null}),o}}catch(n){this.updateState({sessionError:n instanceof Error?n:new Error(String(n))})}}async updateContext(e){var n;if(!((n=this.state.context)!=null&&n.sessionId))throw new Error("No active session");this.updateState({isLoading:!0});try{let o=await this.resource.updateContext(this.state.context.sessionId,{contextUpdates:e});if(o.success)await this.refreshSession();else throw new Error(o.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=S(S({},this.state),e),this.eventDispatcher.notify(this.state)}handleSessionSuccess(e){bn(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)||Te())!=="local")return e;let o=((a=this.config.pluginConfig)==null?void 0:a.staticResources)||{};if(Object.keys(o).length===0)return e;let i=e.static||{};return Object.keys(o).every(c=>i[c]===o[c])&&Object.keys(i).length===Object.keys(o).length?e:N(S({},e),{static:S(S({},o),i)})}}});var Yr={};Ke(Yr,{TRACKER_VERSION:()=>ln,TagadaExternalTracker:()=>xt,TagadaTracker:()=>Mo});We();nt();function Pe(t,e){return function(){return t.apply(e,arguments)}}var{toString:fi}=Object.prototype,{getPrototypeOf:Lt}=Object,{iterator:it,toStringTag:Hn}=Symbol,rt=(t=>e=>{let n=fi.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),M=t=>(t=t.toLowerCase(),e=>rt(e)===t),st=t=>e=>typeof e===t,{isArray:pe}=Array,ge=st("undefined");function _e(t){return t!==null&&!ge(t)&&t.constructor!==null&&!ge(t.constructor)&&O(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var qn=M("ArrayBuffer");function gi(t){let e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&qn(t.buffer),e}var pi=st("string"),O=st("function"),Vn=st("number"),Fe=t=>t!==null&&typeof t=="object",mi=t=>t===!0||t===!1,ot=t=>{if(rt(t)!=="object")return!1;let e=Lt(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Hn in t)&&!(it in t)},hi=t=>{if(!Fe(t)||_e(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch(e){return!1}},yi=M("Date"),wi=M("File"),Ci=M("Blob"),Si=M("FileList"),bi=t=>Fe(t)&&O(t.pipe),Ii=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||O(t.append)&&((e=rt(t))==="formdata"||e==="object"&&O(t.toString)&&t.toString()==="[object FormData]"))},Ti=M("URLSearchParams"),[Ei,xi,vi,Ri]=["ReadableStream","Request","Response","Headers"].map(M),Ai=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ne(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t=="undefined")return;let o,i;if(typeof t!="object"&&(t=[t]),pe(t))for(o=0,i=t.length;o<i;o++)e.call(null,t[o],o,t);else{if(_e(t))return;let r=n?Object.getOwnPropertyNames(t):Object.keys(t),s=r.length,a;for(o=0;o<s;o++)a=r[o],e.call(null,t[a],a,t)}}function Kn(t,e){if(_e(t))return null;e=e.toLowerCase();let n=Object.keys(t),o=n.length,i;for(;o-- >0;)if(i=n[o],e===i.toLowerCase())return i;return null}var oe=typeof globalThis!="undefined"?globalThis:typeof self!="undefined"?self:typeof window!="undefined"?window:global,Wn=t=>!ge(t)&&t!==oe;function Dt(){let{caseless:t,skipUndefined:e}=Wn(this)&&this||{},n={},o=(i,r)=>{let s=t&&Kn(n,r)||r;ot(n[s])&&ot(i)?n[s]=Dt(n[s],i):ot(i)?n[s]=Dt({},i):pe(i)?n[s]=i.slice():(!e||!ge(i))&&(n[s]=i)};for(let i=0,r=arguments.length;i<r;i++)arguments[i]&&Ne(arguments[i],o);return n}var ki=(t,e,n,{allOwnKeys:o}={})=>(Ne(e,(i,r)=>{n&&O(i)?t[r]=Pe(i,n):t[r]=i},{allOwnKeys:o}),t),Pi=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),_i=(t,e,n,o)=>{t.prototype=Object.create(e.prototype,o),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},Fi=(t,e,n,o)=>{let i,r,s,a={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),r=i.length;r-- >0;)s=i[r],(!o||o(s,t,e))&&!a[s]&&(e[s]=t[s],a[s]=!0);t=n!==!1&&Lt(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},Ni=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;let o=t.indexOf(e,n);return o!==-1&&o===n},Oi=t=>{if(!t)return null;if(pe(t))return t;let e=t.length;if(!Vn(e))return null;let n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},Di=(t=>e=>t&&e instanceof t)(typeof Uint8Array!="undefined"&&Lt(Uint8Array)),Li=(t,e)=>{let o=(t&&t[it]).call(t),i;for(;(i=o.next())&&!i.done;){let r=i.value;e.call(t,r[0],r[1])}},Ui=(t,e)=>{let n,o=[];for(;(n=t.exec(e))!==null;)o.push(n);return o},Mi=M("HTMLFormElement"),Bi=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,o,i){return o.toUpperCase()+i}),$n=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),ji=M("RegExp"),Gn=(t,e)=>{let n=Object.getOwnPropertyDescriptors(t),o={};Ne(n,(i,r)=>{let s;(s=e(i,r,t))!==!1&&(o[r]=s||i)}),Object.defineProperties(t,o)},zi=t=>{Gn(t,(e,n)=>{if(O(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;let o=t[n];if(O(o)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},$i=(t,e)=>{let n={},o=i=>{i.forEach(r=>{n[r]=!0})};return pe(t)?o(t):o(String(t).split(e)),n},Hi=()=>{},qi=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function Vi(t){return!!(t&&O(t.append)&&t[Hn]==="FormData"&&t[it])}var Ki=t=>{let e=new Array(10),n=(o,i)=>{if(Fe(o)){if(e.indexOf(o)>=0)return;if(_e(o))return o;if(!("toJSON"in o)){e[i]=o;let r=pe(o)?[]:{};return Ne(o,(s,a)=>{let c=n(s,i+1);!ge(c)&&(r[a]=c)}),e[i]=void 0,r}}return o};return n(t,0)},Wi=M("AsyncFunction"),Gi=t=>t&&(Fe(t)||O(t))&&O(t.then)&&O(t.catch),Jn=((t,e)=>t?setImmediate:e?((n,o)=>(oe.addEventListener("message",({source:i,data:r})=>{i===oe&&r===n&&o.length&&o.shift()()},!1),i=>{o.push(i),oe.postMessage(n,"*")}))("axios@".concat(Math.random()),[]):n=>setTimeout(n))(typeof setImmediate=="function",O(oe.postMessage)),Ji=typeof queueMicrotask!="undefined"?queueMicrotask.bind(oe):typeof process!="undefined"&&process.nextTick||Jn,Xi=t=>t!=null&&O(t[it]),l={isArray:pe,isArrayBuffer:qn,isBuffer:_e,isFormData:Ii,isArrayBufferView:gi,isString:pi,isNumber:Vn,isBoolean:mi,isObject:Fe,isPlainObject:ot,isEmptyObject:hi,isReadableStream:Ei,isRequest:xi,isResponse:vi,isHeaders:Ri,isUndefined:ge,isDate:yi,isFile:wi,isBlob:Ci,isRegExp:ji,isFunction:O,isStream:bi,isURLSearchParams:Ti,isTypedArray:Di,isFileList:Si,forEach:Ne,merge:Dt,extend:ki,trim:Ai,stripBOM:Pi,inherits:_i,toFlatObject:Fi,kindOf:rt,kindOfTest:M,endsWith:Ni,toArray:Oi,forEachEntry:Li,matchAll:Ui,isHTMLForm:Mi,hasOwnProperty:$n,hasOwnProp:$n,reduceDescriptors:Gn,freezeMethods:zi,toObjectSet:$i,toCamelCase:Bi,noop:Hi,toFiniteNumber:qi,findKey:Kn,global:oe,isContextDefined:Wn,isSpecCompliantForm:Vi,toJSONObject:Ki,isAsyncFn:Wi,isThenable:Gi,setImmediate:Jn,asap:Ji,isIterable:Xi};function me(t,e,n,o,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),n&&(this.config=n),o&&(this.request=o),i&&(this.response=i,this.status=i.status?i.status:null)}l.inherits(me,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:l.toJSONObject(this.config),code:this.code,status:this.status}}});var Xn=me.prototype,Yn={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{Yn[t]={value:t}});Object.defineProperties(me,Yn);Object.defineProperty(Xn,"isAxiosError",{value:!0});me.from=(t,e,n,o,i,r)=>{let s=Object.create(Xn);l.toFlatObject(t,s,function(d){return d!==Error.prototype},u=>u!=="isAxiosError");let a=t&&t.message?t.message:"Error",c=e==null&&t?t.code:e;return me.call(s,a,c,n,o,i),t&&s.cause==null&&Object.defineProperty(s,"cause",{value:t,configurable:!0}),s.name=t&&t.name||"Error",r&&Object.assign(s,r),s};var w=me;var at=null;function Ut(t){return l.isPlainObject(t)||l.isArray(t)}function Qn(t){return l.endsWith(t,"[]")?t.slice(0,-2):t}function Zn(t,e,n){return t?t.concat(e).map(function(i,r){return i=Qn(i),!n&&r?"["+i+"]":i}).join(n?".":""):e}function Yi(t){return l.isArray(t)&&!t.some(Ut)}var Zi=l.toFlatObject(l,{},null,function(e){return/^is[A-Z]/.test(e)});function Qi(t,e,n){if(!l.isObject(t))throw new TypeError("target must be an object");e=e||new(at||FormData),n=l.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(h,p){return!l.isUndefined(p[h])});let o=n.metaTokens,i=n.visitor||d,r=n.dots,s=n.indexes,c=(n.Blob||typeof Blob!="undefined"&&Blob)&&l.isSpecCompliantForm(e);if(!l.isFunction(i))throw new TypeError("visitor must be a function");function u(f){if(f===null)return"";if(l.isDate(f))return f.toISOString();if(l.isBoolean(f))return f.toString();if(!c&&l.isBlob(f))throw new w("Blob is not supported. Use a Buffer instead.");return l.isArrayBuffer(f)||l.isTypedArray(f)?c&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function d(f,h,p){let b=f;if(f&&!p&&typeof f=="object"){if(l.endsWith(h,"{}"))h=o?h:h.slice(0,-2),f=JSON.stringify(f);else if(l.isArray(f)&&Yi(f)||(l.isFileList(f)||l.endsWith(h,"[]"))&&(b=l.toArray(f)))return h=Qn(h),b.forEach(function(C,I){!(l.isUndefined(C)||C===null)&&e.append(s===!0?Zn([h],I,r):s===null?h:h+"[]",u(C))}),!1}return Ut(f)?!0:(e.append(Zn(p,h,r),u(f)),!1)}let g=[],y=Object.assign(Zi,{defaultVisitor:d,convertValue:u,isVisitable:Ut});function m(f,h){if(!l.isUndefined(f)){if(g.indexOf(f)!==-1)throw Error("Circular reference detected in "+h.join("."));g.push(f),l.forEach(f,function(b,E){(!(l.isUndefined(b)||b===null)&&i.call(e,b,l.isString(E)?E.trim():E,h,y))===!0&&m(b,h?h.concat(E):[E])}),g.pop()}}if(!l.isObject(t))throw new TypeError("data must be an object");return m(t),e}var Z=Qi;function eo(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(o){return e[o]})}function to(t,e){this._pairs=[],t&&Z(t,this,e)}var no=to.prototype;no.append=function(e,n){this._pairs.push([e,n])};no.toString=function(e){let n=e?function(o){return e.call(this,o,eo)}:eo;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};var lt=to;function er(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Oe(t,e,n){if(!e)return t;let o=n&&n.encode||er;l.isFunction(n)&&(n={serialize:n});let i=n&&n.serialize,r;if(i?r=i(e,n):r=l.isURLSearchParams(e)?e.toString():new lt(e,n).toString(o),r){let s=t.indexOf("#");s!==-1&&(t=t.slice(0,s)),t+=(t.indexOf("?")===-1?"?":"&")+r}return t}var Mt=class{constructor(){this.handlers=[]}use(e,n,o){return this.handlers.push({fulfilled:e,rejected:n,synchronous:o?o.synchronous:!1,runWhen:o?o.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){l.forEach(this.handlers,function(o){o!==null&&e(o)})}},Bt=Mt;var ct={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var oo=typeof URLSearchParams!="undefined"?URLSearchParams:lt;var io=typeof FormData!="undefined"?FormData:null;var ro=typeof Blob!="undefined"?Blob:null;var so={isBrowser:!0,classes:{URLSearchParams:oo,FormData:io,Blob:ro},protocols:["http","https","file","blob","url","data"]};var $t={};Ke($t,{hasBrowserEnv:()=>zt,hasStandardBrowserEnv:()=>tr,hasStandardBrowserWebWorkerEnv:()=>nr,navigator:()=>jt,origin:()=>or});var zt=typeof window!="undefined"&&typeof document!="undefined",jt=typeof navigator=="object"&&navigator||void 0,tr=zt&&(!jt||["ReactNative","NativeScript","NS"].indexOf(jt.product)<0),nr=typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",or=zt&&window.location.href||"http://localhost";var v=S(S({},$t),so);function Ht(t,e){return Z(t,new v.classes.URLSearchParams,S({visitor:function(n,o,i,r){return v.isNode&&l.isBuffer(n)?(this.append(o,n.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},e))}function ir(t){return l.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function rr(t){let e={},n=Object.keys(t),o,i=n.length,r;for(o=0;o<i;o++)r=n[o],e[r]=t[r];return e}function sr(t){function e(n,o,i,r){let s=n[r++];if(s==="__proto__")return!0;let a=Number.isFinite(+s),c=r>=n.length;return s=!s&&l.isArray(i)?i.length:s,c?(l.hasOwnProp(i,s)?i[s]=[i[s],o]:i[s]=o,!a):((!i[s]||!l.isObject(i[s]))&&(i[s]=[]),e(n,o,i[s],r)&&l.isArray(i[s])&&(i[s]=rr(i[s])),!a)}if(l.isFormData(t)&&l.isFunction(t.entries)){let n={};return l.forEachEntry(t,(o,i)=>{e(ir(o),i,n,0)}),n}return null}var ut=sr;function ar(t,e,n){if(l.isString(t))try{return(e||JSON.parse)(t),l.trim(t)}catch(o){if(o.name!=="SyntaxError")throw o}return(n||JSON.stringify)(t)}var qt={transitional:ct,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){let o=n.getContentType()||"",i=o.indexOf("application/json")>-1,r=l.isObject(e);if(r&&l.isHTMLForm(e)&&(e=new FormData(e)),l.isFormData(e))return i?JSON.stringify(ut(e)):e;if(l.isArrayBuffer(e)||l.isBuffer(e)||l.isStream(e)||l.isFile(e)||l.isBlob(e)||l.isReadableStream(e))return e;if(l.isArrayBufferView(e))return e.buffer;if(l.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(r){if(o.indexOf("application/x-www-form-urlencoded")>-1)return Ht(e,this.formSerializer).toString();if((a=l.isFileList(e))||o.indexOf("multipart/form-data")>-1){let c=this.env&&this.env.FormData;return Z(a?{"files[]":e}:e,c&&new c,this.formSerializer)}}return r||i?(n.setContentType("application/json",!1),ar(e)):e}],transformResponse:[function(e){let n=this.transitional||qt.transitional,o=n&&n.forcedJSONParsing,i=this.responseType==="json";if(l.isResponse(e)||l.isReadableStream(e))return e;if(e&&l.isString(e)&&(o&&!this.responseType||i)){let s=!(n&&n.silentJSONParsing)&&i;try{return JSON.parse(e,this.parseReviver)}catch(a){if(s)throw a.name==="SyntaxError"?w.from(a,w.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:v.classes.FormData,Blob:v.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};l.forEach(["delete","get","head","post","put","patch"],t=>{qt.headers[t]={}});var he=qt;var lr=l.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),ao=t=>{let e={},n,o,i;return t&&t.split("\n").forEach(function(s){i=s.indexOf(":"),n=s.substring(0,i).trim().toLowerCase(),o=s.substring(i+1).trim(),!(!n||e[n]&&lr[n])&&(n==="set-cookie"?e[n]?e[n].push(o):e[n]=[o]:e[n]=e[n]?e[n]+", "+o:o)}),e};var lo=Symbol("internals");function De(t){return t&&String(t).trim().toLowerCase()}function dt(t){return t===!1||t==null?t:l.isArray(t)?t.map(dt):String(t)}function cr(t){let e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,o;for(;o=n.exec(t);)e[o[1]]=o[2];return e}var ur=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function Vt(t,e,n,o,i){if(l.isFunction(o))return o.call(this,e,n);if(i&&(e=n),!!l.isString(e)){if(l.isString(o))return e.indexOf(o)!==-1;if(l.isRegExp(o))return o.test(e)}}function dr(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,o)=>n.toUpperCase()+o)}function fr(t,e){let n=l.toCamelCase(" "+e);["get","set","has"].forEach(o=>{Object.defineProperty(t,o+n,{value:function(i,r,s){return this[o].call(this,e,i,r,s)},configurable:!0})})}var ye=class{constructor(e){e&&this.set(e)}set(e,n,o){let i=this;function r(a,c,u){let d=De(c);if(!d)throw new Error("header name must be a non-empty string");let g=l.findKey(i,d);(!g||i[g]===void 0||u===!0||u===void 0&&i[g]!==!1)&&(i[g||c]=dt(a))}let s=(a,c)=>l.forEach(a,(u,d)=>r(u,d,c));if(l.isPlainObject(e)||e instanceof this.constructor)s(e,n);else if(l.isString(e)&&(e=e.trim())&&!ur(e))s(ao(e),n);else if(l.isObject(e)&&l.isIterable(e)){let a={},c,u;for(let d of e){if(!l.isArray(d))throw TypeError("Object iterator must return a key-value pair");a[u=d[0]]=(c=a[u])?l.isArray(c)?[...c,d[1]]:[c,d[1]]:d[1]}s(a,n)}else e!=null&&r(n,e,o);return this}get(e,n){if(e=De(e),e){let o=l.findKey(this,e);if(o){let i=this[o];if(!n)return i;if(n===!0)return cr(i);if(l.isFunction(n))return n.call(this,i,o);if(l.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=De(e),e){let o=l.findKey(this,e);return!!(o&&this[o]!==void 0&&(!n||Vt(this,this[o],o,n)))}return!1}delete(e,n){let o=this,i=!1;function r(s){if(s=De(s),s){let a=l.findKey(o,s);a&&(!n||Vt(o,o[a],a,n))&&(delete o[a],i=!0)}}return l.isArray(e)?e.forEach(r):r(e),i}clear(e){let n=Object.keys(this),o=n.length,i=!1;for(;o--;){let r=n[o];(!e||Vt(this,this[r],r,e,!0))&&(delete this[r],i=!0)}return i}normalize(e){let n=this,o={};return l.forEach(this,(i,r)=>{let s=l.findKey(o,r);if(s){n[s]=dt(i),delete n[r];return}let a=e?dr(r):String(r).trim();a!==r&&delete n[r],n[a]=dt(i),o[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let n=Object.create(null);return l.forEach(this,(o,i)=>{o!=null&&o!==!1&&(n[i]=e&&l.isArray(o)?o.join(", "):o)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){let o=new this(e);return n.forEach(i=>o.set(i)),o}static accessor(e){let o=(this[lo]=this[lo]={accessors:{}}).accessors,i=this.prototype;function r(s){let a=De(s);o[a]||(fr(i,s),o[a]=!0)}return l.isArray(e)?e.forEach(r):r(e),this}};ye.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);l.reduceDescriptors(ye.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(o){this[n]=o}}});l.freezeMethods(ye);var A=ye;function Le(t,e){let n=this||he,o=e||n,i=A.from(o.headers),r=o.data;return l.forEach(t,function(a){r=a.call(n,r,i.normalize(),e?e.status:void 0)}),i.normalize(),r}function Ue(t){return!!(t&&t.__CANCEL__)}function co(t,e,n){w.call(this,t==null?"canceled":t,w.ERR_CANCELED,e,n),this.name="CanceledError"}l.inherits(co,w,{__CANCEL__:!0});var H=co;function Me(t,e,n){let o=n.config.validateStatus;!n.status||!o||o(n.status)?t(n):e(new w("Request failed with status code "+n.status,[w.ERR_BAD_REQUEST,w.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Kt(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function gr(t,e){t=t||10;let n=new Array(t),o=new Array(t),i=0,r=0,s;return e=e!==void 0?e:1e3,function(c){let u=Date.now(),d=o[r];s||(s=u),n[i]=c,o[i]=u;let g=r,y=0;for(;g!==i;)y+=n[g++],g=g%t;if(i=(i+1)%t,i===r&&(r=(r+1)%t),u-s<e)return;let m=d&&u-d;return m?Math.round(y*1e3/m):void 0}}var uo=gr;function pr(t,e){let n=0,o=1e3/e,i,r,s=(u,d=Date.now())=>{n=d,i=null,r&&(clearTimeout(r),r=null),t(...u)};return[(...u)=>{let d=Date.now(),g=d-n;g>=o?s(u,d):(i=u,r||(r=setTimeout(()=>{r=null,s(i)},o-g)))},()=>i&&s(i)]}var fo=pr;var we=(t,e,n=3)=>{let o=0,i=uo(50,250);return fo(r=>{let s=r.loaded,a=r.lengthComputable?r.total:void 0,c=s-o,u=i(c),d=s<=a;o=s;let g={loaded:s,total:a,progress:a?s/a:void 0,bytes:c,rate:u||void 0,estimated:u&&a&&d?(a-s)/u:void 0,event:r,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(g)},n)},Wt=(t,e)=>{let n=t!=null;return[o=>e[0]({lengthComputable:n,total:t,loaded:o}),e[1]]},Gt=t=>(...e)=>l.asap(()=>t(...e));var go=v.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,v.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(v.origin),v.navigator&&/(msie|trident)/i.test(v.navigator.userAgent)):()=>!0;var po=v.hasStandardBrowserEnv?{write(t,e,n,o,i,r,s){if(typeof document=="undefined")return;let a=["".concat(t,"=").concat(encodeURIComponent(e))];l.isNumber(n)&&a.push("expires=".concat(new Date(n).toUTCString())),l.isString(o)&&a.push("path=".concat(o)),l.isString(i)&&a.push("domain=".concat(i)),r===!0&&a.push("secure"),l.isString(s)&&a.push("SameSite=".concat(s)),document.cookie=a.join("; ")},read(t){if(typeof document=="undefined")return null;let e=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return e?decodeURIComponent(e[1]):null},remove(t){this.write(t,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function Jt(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Xt(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function Be(t,e,n){let o=!Jt(e);return t&&(o||n==!1)?Xt(t,e):e}var mo=t=>t instanceof A?S({},t):t;function B(t,e){e=e||{};let n={};function o(u,d,g,y){return l.isPlainObject(u)&&l.isPlainObject(d)?l.merge.call({caseless:y},u,d):l.isPlainObject(d)?l.merge({},d):l.isArray(d)?d.slice():d}function i(u,d,g,y){if(l.isUndefined(d)){if(!l.isUndefined(u))return o(void 0,u,g,y)}else return o(u,d,g,y)}function r(u,d){if(!l.isUndefined(d))return o(void 0,d)}function s(u,d){if(l.isUndefined(d)){if(!l.isUndefined(u))return o(void 0,u)}else return o(void 0,d)}function a(u,d,g){if(g in e)return o(u,d);if(g in t)return o(void 0,u)}let c={url:r,method:r,data:r,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(u,d,g)=>i(mo(u),mo(d),g,!0)};return l.forEach(Object.keys(S(S({},t),e)),function(d){let g=c[d]||i,y=g(t[d],e[d],d);l.isUndefined(y)&&g!==a||(n[d]=y)}),n}var ft=t=>{let e=B({},t),{data:n,withXSRFToken:o,xsrfHeaderName:i,xsrfCookieName:r,headers:s,auth:a}=e;if(e.headers=s=A.from(s),e.url=Oe(Be(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&s.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),l.isFormData(n)){if(v.hasStandardBrowserEnv||v.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(l.isFunction(n.getHeaders)){let c=n.getHeaders(),u=["content-type","content-length"];Object.entries(c).forEach(([d,g])=>{u.includes(d.toLowerCase())&&s.set(d,g)})}}if(v.hasStandardBrowserEnv&&(o&&l.isFunction(o)&&(o=o(e)),o||o!==!1&&go(e.url))){let c=i&&r&&po.read(r);c&&s.set(i,c)}return e};var mr=typeof XMLHttpRequest!="undefined",ho=mr&&function(t){return new Promise(function(n,o){let i=ft(t),r=i.data,s=A.from(i.headers).normalize(),{responseType:a,onUploadProgress:c,onDownloadProgress:u}=i,d,g,y,m,f;function h(){m&&m(),f&&f(),i.cancelToken&&i.cancelToken.unsubscribe(d),i.signal&&i.signal.removeEventListener("abort",d)}let p=new XMLHttpRequest;p.open(i.method.toUpperCase(),i.url,!0),p.timeout=i.timeout;function b(){if(!p)return;let C=A.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),k={data:!a||a==="text"||a==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:C,config:t,request:p};Me(function(P){n(P),h()},function(P){o(P),h()},k),p=null}"onloadend"in p?p.onloadend=b:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(b)},p.onabort=function(){p&&(o(new w("Request aborted",w.ECONNABORTED,t,p)),p=null)},p.onerror=function(I){let k=I&&I.message?I.message:"Network Error",T=new w(k,w.ERR_NETWORK,t,p);T.event=I||null,o(T),p=null},p.ontimeout=function(){let I=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",k=i.transitional||ct;i.timeoutErrorMessage&&(I=i.timeoutErrorMessage),o(new w(I,k.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,t,p)),p=null},r===void 0&&s.setContentType(null),"setRequestHeader"in p&&l.forEach(s.toJSON(),function(I,k){p.setRequestHeader(k,I)}),l.isUndefined(i.withCredentials)||(p.withCredentials=!!i.withCredentials),a&&a!=="json"&&(p.responseType=i.responseType),u&&([y,f]=we(u,!0),p.addEventListener("progress",y)),c&&p.upload&&([g,m]=we(c),p.upload.addEventListener("progress",g),p.upload.addEventListener("loadend",m)),(i.cancelToken||i.signal)&&(d=C=>{p&&(o(!C||C.type?new H(null,t,p):C),p.abort(),p=null)},i.cancelToken&&i.cancelToken.subscribe(d),i.signal&&(i.signal.aborted?d():i.signal.addEventListener("abort",d)));let E=Kt(i.url);if(E&&v.protocols.indexOf(E)===-1){o(new w("Unsupported protocol "+E+":",w.ERR_BAD_REQUEST,t));return}p.send(r||null)})};var hr=(t,e)=>{let{length:n}=t=t?t.filter(Boolean):[];if(e||n){let o=new AbortController,i,r=function(u){if(!i){i=!0,a();let d=u instanceof Error?u:this.reason;o.abort(d instanceof w?d:new H(d instanceof Error?d.message:d))}},s=e&&setTimeout(()=>{s=null,r(new w("timeout ".concat(e," of ms exceeded"),w.ETIMEDOUT))},e),a=()=>{t&&(s&&clearTimeout(s),s=null,t.forEach(u=>{u.unsubscribe?u.unsubscribe(r):u.removeEventListener("abort",r)}),t=null)};t.forEach(u=>u.addEventListener("abort",r));let{signal:c}=o;return c.unsubscribe=()=>l.asap(a),c}},yo=hr;var yr=function*(t,e){let n=t.byteLength;if(!e||n<e){yield t;return}let o=0,i;for(;o<n;)i=o+e,yield t.slice(o,i),o=i},wr=function(t,e){return Rt(this,null,function*(){try{for(var n=hn(Cr(t)),o,i,r;o=!(i=yield new te(n.next())).done;o=!1){let s=i.value;yield*At(yr(s,e))}}catch(i){r=[i]}finally{try{o&&(i=n.return)&&(yield new te(i.call(n)))}finally{if(r)throw r[0]}}})},Cr=function(t){return Rt(this,null,function*(){if(t[Symbol.asyncIterator]){yield*At(t);return}let e=t.getReader();try{for(;;){let{done:n,value:o}=yield new te(e.read());if(n)break;yield o}}finally{yield new te(e.cancel())}})},Yt=(t,e,n,o)=>{let i=wr(t,e),r=0,s,a=c=>{s||(s=!0,o&&o(c))};return new ReadableStream({async pull(c){try{let{done:u,value:d}=await i.next();if(u){a(),c.close();return}let g=d.byteLength;if(n){let y=r+=g;n(y)}c.enqueue(new Uint8Array(d))}catch(u){throw a(u),u}},cancel(c){return a(c),i.return()}},{highWaterMark:2})};var wo=64*1024,{isFunction:gt}=l,Sr=(({Request:t,Response:e})=>({Request:t,Response:e}))(l.global),{ReadableStream:Co,TextEncoder:So}=l.global,bo=(t,...e)=>{try{return!!t(...e)}catch(n){return!1}},br=t=>{t=l.merge.call({skipUndefined:!0},Sr,t);let{fetch:e,Request:n,Response:o}=t,i=e?gt(e):typeof fetch=="function",r=gt(n),s=gt(o);if(!i)return!1;let a=i&&gt(Co),c=i&&(typeof So=="function"?(f=>h=>f.encode(h))(new So):async f=>new Uint8Array(await new n(f).arrayBuffer())),u=r&&a&&bo(()=>{let f=!1,h=new n(v.origin,{body:new Co,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!h}),d=s&&a&&bo(()=>l.isReadableStream(new o("").body)),g={stream:d&&(f=>f.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!g[f]&&(g[f]=(h,p)=>{let b=h&&h[f];if(b)return b.call(h);throw new w("Response type '".concat(f,"' is not supported"),w.ERR_NOT_SUPPORT,p)})});let y=async f=>{if(f==null)return 0;if(l.isBlob(f))return f.size;if(l.isSpecCompliantForm(f))return(await new n(v.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(l.isArrayBufferView(f)||l.isArrayBuffer(f))return f.byteLength;if(l.isURLSearchParams(f)&&(f=f+""),l.isString(f))return(await c(f)).byteLength},m=async(f,h)=>{let p=l.toFiniteNumber(f.getContentLength());return p==null?y(h):p};return async f=>{let{url:h,method:p,data:b,signal:E,cancelToken:C,timeout:I,onDownloadProgress:k,onUploadProgress:T,responseType:P,headers:z,withCredentials:be="same-origin",fetchOptions:D}=ft(f),G=e||fetch;P=P?(P+"").toLowerCase():"text";let F=yo([E,C&&C.toAbortSignal()],I),Ie=null,ee=F&&F.unsubscribe&&(()=>{F.unsubscribe()}),cn;try{if(T&&u&&p!=="get"&&p!=="head"&&(cn=await m(z,b))!==0){let X=new n(h,{method:"POST",body:b,duplex:"half"}),se;if(l.isFormData(b)&&(se=X.headers.get("content-type"))&&z.setContentType(se),X.body){let[vt,qe]=Wt(cn,we(Gt(T)));b=Yt(X.body,wo,vt,qe)}}l.isString(be)||(be=be?"include":"omit");let $=r&&"credentials"in n.prototype,un=N(S({},D),{signal:F,method:p.toUpperCase(),headers:z.normalize().toJSON(),body:b,duplex:"half",credentials:$?be:void 0});Ie=r&&new n(h,un);let J=await(r?G(Ie,D):G(h,un)),dn=d&&(P==="stream"||P==="response");if(d&&(k||dn&&ee)){let X={};["status","statusText","headers"].forEach(fn=>{X[fn]=J[fn]});let se=l.toFiniteNumber(J.headers.get("content-length")),[vt,qe]=k&&Wt(se,we(Gt(k),!0))||[];J=new o(Yt(J.body,wo,vt,()=>{qe&&qe(),ee&&ee()}),X)}P=P||"text";let Bo=await g[l.findKey(g,P)||"text"](J,f);return!dn&&ee&&ee(),await new Promise((X,se)=>{Me(X,se,{data:Bo,headers:A.from(J.headers),status:J.status,statusText:J.statusText,config:f,request:Ie})})}catch($){throw ee&&ee(),$&&$.name==="TypeError"&&/Load failed|fetch/i.test($.message)?Object.assign(new w("Network Error",w.ERR_NETWORK,f,Ie),{cause:$.cause||$}):w.from($,$&&$.code,f,Ie)}}},Ir=new Map,Zt=t=>{let e=t&&t.env||{},{fetch:n,Request:o,Response:i}=e,r=[o,i,n],s=r.length,a=s,c,u,d=Ir;for(;a--;)c=r[a],u=d.get(c),u===void 0&&d.set(c,u=a?new Map:br(e)),d=u;return u},Pl=Zt();var Qt={http:at,xhr:ho,fetch:{get:Zt}};l.forEach(Qt,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch(n){}Object.defineProperty(t,"adapterName",{value:e})}});var Io=t=>"- ".concat(t),Er=t=>l.isFunction(t)||t===null||t===!1;function xr(t,e){t=l.isArray(t)?t:[t];let{length:n}=t,o,i,r={};for(let s=0;s<n;s++){o=t[s];let a;if(i=o,!Er(o)&&(i=Qt[(a=String(o)).toLowerCase()],i===void 0))throw new w("Unknown adapter '".concat(a,"'"));if(i&&(l.isFunction(i)||(i=i.get(e))))break;r[a||"#"+s]=i}if(!i){let s=Object.entries(r).map(([c,u])=>"adapter ".concat(c," ")+(u===!1?"is not supported by the environment":"is not available in the build")),a=n?s.length>1?"since :\n"+s.map(Io).join("\n"):" "+Io(s[0]):"as no adapter specified";throw new w("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return i}var pt={getAdapter:xr,adapters:Qt};function en(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new H(null,t)}function mt(t){return en(t),t.headers=A.from(t.headers),t.data=Le.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),pt.getAdapter(t.adapter||he.adapter,t)(t).then(function(o){return en(t),o.data=Le.call(t,t.transformResponse,o),o.headers=A.from(o.headers),o},function(o){return Ue(o)||(en(t),o&&o.response&&(o.response.data=Le.call(t,t.transformResponse,o.response),o.response.headers=A.from(o.response.headers))),Promise.reject(o)})}var ht="1.13.2";var yt={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{yt[t]=function(o){return typeof o===t||"a"+(e<1?"n ":" ")+t}});var To={};yt.transitional=function(e,n,o){function i(r,s){return"[Axios v"+ht+"] Transitional option '"+r+"'"+s+(o?". "+o:"")}return(r,s,a)=>{if(e===!1)throw new w(i(s," has been removed"+(n?" in "+n:"")),w.ERR_DEPRECATED);return n&&!To[s]&&(To[s]=!0,console.warn(i(s," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(r,s,a):!0}};yt.spelling=function(e){return(n,o)=>(console.warn("".concat(o," is likely a misspelling of ").concat(e)),!0)};function vr(t,e,n){if(typeof t!="object")throw new w("options must be an object",w.ERR_BAD_OPTION_VALUE);let o=Object.keys(t),i=o.length;for(;i-- >0;){let r=o[i],s=e[r];if(s){let a=t[r],c=a===void 0||s(a,r,t);if(c!==!0)throw new w("option "+r+" must be "+c,w.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new w("Unknown option "+r,w.ERR_BAD_OPTION)}}var je={assertOptions:vr,validators:yt};var q=je.validators,Ce=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Bt,response:new Bt}}async request(e,n){try{return await this._request(e,n)}catch(o){if(o instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;let r=i.stack?i.stack.replace(/^.+\n/,""):"";try{o.stack?r&&!String(o.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(o.stack+="\n"+r):o.stack=r}catch(s){}}throw o}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=B(this.defaults,n);let{transitional:o,paramsSerializer:i,headers:r}=n;o!==void 0&&je.assertOptions(o,{silentJSONParsing:q.transitional(q.boolean),forcedJSONParsing:q.transitional(q.boolean),clarifyTimeoutError:q.transitional(q.boolean)},!1),i!=null&&(l.isFunction(i)?n.paramsSerializer={serialize:i}:je.assertOptions(i,{encode:q.function,serialize:q.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),je.assertOptions(n,{baseUrl:q.spelling("baseURL"),withXsrfToken:q.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=r&&l.merge(r.common,r[n.method]);r&&l.forEach(["delete","get","head","post","put","patch","common"],f=>{delete r[f]}),n.headers=A.concat(s,r);let a=[],c=!0;this.interceptors.request.forEach(function(h){typeof h.runWhen=="function"&&h.runWhen(n)===!1||(c=c&&h.synchronous,a.unshift(h.fulfilled,h.rejected))});let u=[];this.interceptors.response.forEach(function(h){u.push(h.fulfilled,h.rejected)});let d,g=0,y;if(!c){let f=[mt.bind(this),void 0];for(f.unshift(...a),f.push(...u),y=f.length,d=Promise.resolve(n);g<y;)d=d.then(f[g++],f[g++]);return d}y=a.length;let m=n;for(;g<y;){let f=a[g++],h=a[g++];try{m=f(m)}catch(p){h.call(this,p);break}}try{d=mt.call(this,m)}catch(f){return Promise.reject(f)}for(g=0,y=u.length;g<y;)d=d.then(u[g++],u[g++]);return d}getUri(e){e=B(this.defaults,e);let n=Be(e.baseURL,e.url,e.allowAbsoluteUrls);return Oe(n,e.params,e.paramsSerializer)}};l.forEach(["delete","get","head","options"],function(e){Ce.prototype[e]=function(n,o){return this.request(B(o||{},{method:e,url:n,data:(o||{}).data}))}});l.forEach(["post","put","patch"],function(e){function n(o){return function(r,s,a){return this.request(B(a||{},{method:e,headers:o?{"Content-Type":"multipart/form-data"}:{},url:r,data:s}))}}Ce.prototype[e]=n(),Ce.prototype[e+"Form"]=n(!0)});var ze=Ce;var tn=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(r){n=r});let o=this;this.promise.then(i=>{if(!o._listeners)return;let r=o._listeners.length;for(;r-- >0;)o._listeners[r](i);o._listeners=null}),this.promise.then=i=>{let r,s=new Promise(a=>{o.subscribe(a),r=a}).then(i);return s.cancel=function(){o.unsubscribe(r)},s},e(function(r,s,a){o.reason||(o.reason=new H(r,s,a),n(o.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){let e=new AbortController,n=o=>{e.abort(o)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},Eo=tn;function nn(t){return function(n){return t.apply(null,n)}}function on(t){return l.isObject(t)&&t.isAxiosError===!0}var rn={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(rn).forEach(([t,e])=>{rn[e]=t});var xo=rn;function vo(t){let e=new ze(t),n=Pe(ze.prototype.request,e);return l.extend(n,ze.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return vo(B(t,i))},n}var R=vo(he);R.Axios=ze;R.CanceledError=H;R.CancelToken=Eo;R.isCancel=Ue;R.VERSION=ht;R.toFormData=Z;R.AxiosError=w;R.Cancel=R.CanceledError;R.all=function(e){return Promise.all(e)};R.spread=nn;R.isAxiosError=on;R.mergeConfig=B;R.AxiosHeaders=A;R.formToJSON=t=>ut(l.isHTMLForm(t)?new FormData(t):t);R.getAdapter=pt.getAdapter;R.HttpStatusCode=xo;R.default=R;var $e=R;var{Axios:Ac,AxiosError:kc,CanceledError:Pc,isCancel:_c,CancelToken:Fc,VERSION:Nc,all:Oc,Cancel:Dc,isAxiosError:Lc,spread:Uc,toFormData:Mc,AxiosHeaders:Bc,HttpStatusCode:jc,formToJSON:zc,getAdapter:$c,mergeConfig:Hc}=$e;var K={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"},Q=class extends Error{constructor(e,n){var o;super(e),this.name="TagadaError",this.code=n.code,this.statusCode=n.statusCode,this.retryable=(o=n.retryable)!=null?o:!1,this.details=n.details,Object.setPrototypeOf(this,new.target.prototype)}},ie=class extends Q{constructor(e,n,o){var i,r;super(e,{code:(i=o==null?void 0:o.code)!=null?i:K.API_ERROR,statusCode:n,retryable:(r=o==null?void 0:o.retryable)!=null?r:n>=500,details:o==null?void 0:o.details}),this.name="TagadaApiError"}},wt=class extends Q{constructor(e="Network request failed"){super(e,{code:K.NETWORK_ERROR,retryable:!0}),this.name="TagadaNetworkError"}},Ct=class extends Q{constructor(e="Authentication required",n=401){super(e,{code:K.AUTH_REQUIRED,statusCode:n,retryable:!1}),this.name="TagadaAuthError"}};var St=class extends Q{constructor(e){super(e,{code:K.CIRCUIT_BREAKER,retryable:!1}),this.name="TagadaCircuitBreakerError"}};var bt=class{constructor(e){this.currentToken=null;this.tokenProvider=null;this.requestHistory=new Map;this.WINDOW_MS=5e3;this.MAX_REQUESTS=30;this.axios=$e.create({baseURL:e.baseURL,timeout:e.timeout||6e4,headers:S({"Content-Type":"application/json"},e.headers)}),typeof setInterval!="undefined"&&setInterval(()=>this.cleanupHistory(),1e4),this.axios.interceptors.request.use(async n=>{var o,i;if(n.url)try{this.checkRequestLimit("".concat((o=n.method)==null?void 0:o.toUpperCase(),":").concat(n.url))}catch(r){return console.error("[SDK] \u{1F6D1} Request blocked by Circuit Breaker:",r),Promise.reject(r)}if(!n.skipAuth&&!this.currentToken&&this.tokenProvider)try{console.log("[SDK] Waiting for token...");let r=await this.tokenProvider();r&&(this.updateToken(r),n.headers["x-cms-token"]=r)}catch(r){console.error("[SDK] Failed to get token from provider:",r)}return!n.skipAuth&&this.currentToken&&(n.headers["x-cms-token"]=this.currentToken),console.log("[SDK] Making ".concat((i=n.method)==null?void 0:i.toUpperCase()," request to: ").concat(n.baseURL||"").concat(n.url)),n},n=>(console.error("[SDK] Request error:",n),Promise.reject(n instanceof Error?n:new Error(String(n))))),this.axios.interceptors.response.use(n=>n,n=>(console.error("[SDK] Response error:",n.message),n instanceof Q?Promise.reject(n):$e.isAxiosError(n)?Promise.reject(this.toTagadaError(n)):Promise.reject(n instanceof Error?n:new Error(String(n)))))}setTokenProvider(e){this.tokenProvider=e}async get(e,n){return(await this.axios.get(e,n)).data}async post(e,n,o){return(await this.axios.post(e,n,o)).data}async put(e,n,o){return(await this.axios.put(e,n,o)).data}async patch(e,n,o){return(await this.axios.patch(e,n,o)).data}async delete(e,n){return(await this.axios.delete(e,n)).data}setHeader(e,n){this.axios.defaults.headers.common[e]=n}removeHeader(e){delete this.axios.defaults.headers.common[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.axios.defaults.baseURL=e.baseURL),e.timeout&&(this.axios.defaults.timeout=e.timeout),e.headers&&Object.assign(this.axios.defaults.headers.common,e.headers),console.log("[SDK] ApiClient configuration updated")}checkRequestLimit(e){let n=Date.now(),o=this.requestHistory.get(e);if(!o){this.requestHistory.set(e,{count:1,firstRequestTime:n});return}if(n-o.firstRequestTime>this.WINDOW_MS){this.requestHistory.set(e,{count:1,firstRequestTime:n});return}if(o.count++,o.count>this.MAX_REQUESTS)throw new St("Circuit Breaker: Too many requests to ".concat(e," (").concat(o.count," in ").concat(this.WINDOW_MS,"ms)"))}cleanupHistory(){let e=Date.now();for(let[n,o]of this.requestHistory.entries())e-o.firstRequestTime>this.WINDOW_MS&&this.requestHistory.delete(n)}toTagadaError(e){var r,s,a,c,u;let n=(r=e.response)==null?void 0:r.status,o=(s=e.response)==null?void 0:s.data,i=(c=(a=o==null?void 0:o.message)!=null?a:o==null?void 0:o.error)!=null?c:e.message;return e.response?n===401||n===403?new Ct(i,n):n===429?new ie(i,429,{code:K.RATE_LIMITED,retryable:!0}):n===404?new ie(i,404,{code:K.NOT_FOUND,retryable:!1}):new ie(i,n!=null?n:0,{code:(u=o==null?void 0:o.code)!=null?u:K.API_ERROR,details:o,retryable:(n!=null?n:0)>=500}):e.code==="ECONNABORTED"?new ie("Request timed out",0,{code:K.TIMEOUT,retryable:!0}):new wt(i)}};function Rr(){return{width:window.screen.width,height:window.screen.height}}function Ar(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){return"UTC"}}function Ro(){try{return navigator.language||"en-US"}catch(t){return"en-US"}}var re=typeof navigator!="undefined"?navigator.userAgent:"";function j(t,...e){for(let n of e){let o=t.match(n);if(o)return o}return null}function kr(t){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[n,o]of e){let i=t.match(n);if(i){let r=i[1]||"";return{name:o,version:r,major:r.split(".")[0]||""}}}return{name:"",version:"",major:""}}function Pr(t){let e=j(t,/Windows NT ([\d.]+)/i)||j(t,/Mac OS X ([\d_.]+)/i)||j(t,/Android ([\d.]+)/i)||j(t,/iPhone OS ([\d_]+)/i)||j(t,/iPad.*OS ([\d_]+)/i)||j(t,/CrOS[\w ]*\/([\d.]+)/i)||j(t,/Linux/i);if(!e)return{name:"",version:""};let n=e[0],o=(e[1]||"").replace(/_/g,".");return/Windows/i.test(n)?{name:"Windows",version:{"10.0":"10","6.3":"8.1","6.2":"8","6.1":"7","6.0":"Vista","5.1":"XP"}[o]||o}:/Mac OS X/i.test(n)?{name:"macOS",version:o}:/Android/i.test(n)?{name:"Android",version:o}:/iPhone|iPad/i.test(n)?{name:"iOS",version:o}:/CrOS/i.test(n)?{name:"Chrome OS",version:o}:/Linux/i.test(n)?{name:"Linux",version:""}:{name:"",version:""}}function _r(t){var e;if(/iPad/i.test(t))return{type:"tablet",vendor:"Apple",model:"iPad"};if(/iPhone/i.test(t))return{type:"mobile",vendor:"Apple",model:"iPhone"};if(/iPod/i.test(t))return{type:"mobile",vendor:"Apple",model:"iPod"};if(/Android/i.test(t)){let n=t.match(/Android[\s\d.]+;\s*([^)]+?)(?:\s+Build)/i);return{type:/Mobile/i.test(t)?"mobile":"tablet",model:(e=n==null?void 0:n[1])==null?void 0:e.trim()}}}function Fr(t){let e=j(t,/AppleWebKit\/([\d.]+)/i)||j(t,/Gecko\/([\d.]+)/i)||j(t,/Trident\/([\d.]+)/i)||j(t,/Presto\/([\d.]+)/i);if(!e)return{name:"",version:""};let n=e[0],o=e[1]||"";return/AppleWebKit/i.test(n)?{name:"WebKit",version:o}:/Gecko/i.test(n)?{name:"Gecko",version:o}:/Trident/i.test(n)?{name:"Trident",version:o}:/Presto/i.test(n)?{name:"Presto",version:o}:{name:"",version:""}}function Nr(t){return/x86_64|x64|amd64|Win64/i.test(t)?{architecture:"amd64"}:/ia32|x86/i.test(t)?{architecture:"ia32"}:/aarch64|arm64/i.test(t)?{architecture:"arm64"}:/arm/i.test(t)?{architecture:"arm"}:{architecture:""}}function Or(){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(re)}function Dr(t){return/Chrome|Chromium|Edge|Brave|Opera|Vivaldi|Arc/i.test(t)}function Lr(){return window.matchMedia("(display-mode: standalone)").matches||navigator.standalone===!0}function Ur(t){return/mac/i.test(t)?navigator.maxTouchPoints>0:!1}function Ao(){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 t=kr(re),e=Pr(re),n=_r(re),o=Fr(re),i=Nr(re),r;try{r={isBot:Or(),isChromeFamily:Dr(t.name),isStandalonePWA:Lr(),isAppleSilicon:Ur(e.name)}}catch(s){r={isBot:!1,isChromeFamily:!1,isStandalonePWA:!1,isAppleSilicon:!1}}return{userAgent:{name:re,browser:t,os:e,device:n,engine:o,cpu:i},screenResolution:Rr(),timeZone:Ar(),flags:r}}function ko(){if(typeof window=="undefined")return{};let t=new URLSearchParams(window.location.search);return{locale:t.get("locale")||void 0,currency:t.get("currency")||void 0,utmSource:t.get("utm_source")||void 0,utmMedium:t.get("utm_medium")||void 0,utmCampaign:t.get("utm_campaign")||void 0}}var It=class{constructor(){this.listeners=new Map}on(e,n){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(n),()=>this.off(e,n)}off(e,n){this.listeners.has(e)&&this.listeners.get(e).delete(n)}async emit(e,n){if(this.listeners.has(e)){let o=Array.from(this.listeners.get(e));await Promise.all(o.map(i=>{try{return Promise.resolve(i(n))}catch(r){return console.error('[EventBus] Error in listener for event "'.concat(e,'":'),r),Promise.resolve()}}))}}clear(){this.listeners.clear()}};kt();function He(t){try{let e=t.split(".");if(e.length!==3)return console.error("Invalid JWT token format"),null;let n=e[1],o=n+"=".repeat((4-n.length%4)%4),i=atob(o),r=JSON.parse(i);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 Po(t){try{let e=t.split(".");if(e.length!==3)return!0;let n=e[1],o=n+"=".repeat((4-n.length%4)%4),i=atob(o),r=JSON.parse(i);return r.exp?Date.now()>=r.exp*1e3:!1}catch(e){return console.error("Failed to check token expiration:",e),!0}}We();var Se={},Mr=["","VITE_","REACT_APP_","NEXT_PUBLIC_"];function W(t,e=Mr){var n,o,i;for(let r of e){let s=r?"".concat(r).concat(t):t;if(typeof process!="undefined"&&((n=process==null?void 0:process.env)!=null&&n[s]))return console.log("process.env[".concat(s,"]"),process.env[s]),process.env[s];if(typeof Se!="undefined"&&((o=Se==null?void 0:Se.env)!=null&&o[s]))return console.log("import.meta.env[".concat(s,"]"),Se.env[s]),Se.env[s];if(typeof window!="undefined"&&((i=window==null?void 0:window.__TAGADA_ENV__)!=null&&i[s]))return console.log("window.__TAGADA_ENV__[".concat(s,"]"),window.__TAGADA_ENV__[s]),window.__TAGADA_ENV__[s]}}var Br=async(t="default")=>{try{if((W("TAGADA_ENV")||W("TAGADA_ENVIRONMENT"))==="production"||!Ee(!0))return null;let n=await fetch("/.local.json");if(!n.ok)return null;let o=await n.json(),i={},r=!1;try{let a=await fetch("/config/".concat(t,".tgd.json"));a.ok||(a=await fetch("/config/".concat(t,".json"))),a.ok&&(i=await a.json(),r=!0)}catch(a){}if(!r&&t!=="default"){console.warn("\u26A0\uFE0F Config variant '".concat(t,"' 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&&(i=await a.json(),r=!0,console.log("\u2705 Fallback to 'default' config successful"))}catch(a){}}r||console.warn(t==="default"?"\u26A0\uFE0F No 'default' config found. Create /config/default.tgd.json":"\u26A0\uFE0F Neither '".concat(t,"' nor 'default' config found. Create /config/default.tgd.json"));let s={storeId:o.storeId,accountId:o.accountId,basePath:o.basePath,config:i};return console.log("\u{1F6E0}\uFE0F Using local development plugin config:",s),s}catch(e){return null}},jr=async()=>{try{if((W("TAGADA_ENV")||W("TAGADA_ENVIRONMENT"))==="production"||!Ee(!0))return null;try{console.log("\u{1F6E0}\uFE0F [V2] Attempting to load /config/funnel.local.json...");let o=await fetch("/config/funnel.local.json");if(o.ok){let i=await o.json();console.log("\u{1F6E0}\uFE0F [V2] \u2705 Loaded local funnel config (NEW format):",i);let{loadLocalFunnelConfig:r}=await Promise.resolve().then(()=>(nt(),zn));if(await r(),i.staticResources){let s={};for(let[a,c]of Object.entries(i.staticResources))s[a]={id:c};return s}return null}}catch(o){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 n=await e.json();return console.log("\u{1F6E0}\uFE0F [V2] \u2705 Loaded legacy static resources:",n),n}catch(t){return console.error("\u{1F6E0}\uFE0F [V2] \u274C Error loading static resources:",t),null}},Tt=t=>{if(typeof document=="undefined")return;let e=document.querySelector('meta[name="'.concat(t,'"]'));return(e==null?void 0:e.getAttribute("content"))||void 0},zr=()=>{if(typeof window!="undefined"&&window.__TAGADA_PLUGIN_CONFIG__)return window.__TAGADA_PLUGIN_CONFIG__;try{let t=Tt("x-plugin-config");if(t)return JSON.parse(decodeURIComponent(t))}catch(t){}return{}};var $r=async()=>{try{if(typeof document=="undefined")return null;let t=Tt("x-plugin-store-id"),e=Tt("x-plugin-account-id");if(!t)return null;let n=Tt("x-plugin-base-path")||"/",o=zr();e||console.warn("\u26A0\uFE0F Plugin config: Account ID not found in meta tags");let i={storeId:t,accountId:e,basePath:n,config:o};return console.log("\u{1F680} [HIGHEST PRIORITY] Plugin config loaded from meta tags (runtime injected config):",{storeId:t,accountId:e,basePath:n,configKeys:Object.keys(o),configSize:JSON.stringify(o).length}),i}catch(t){return console.warn("\u26A0\uFE0F Error loading production config from meta tags:",t),null}},_o=async(t="default",e)=>{var s,a;console.log("\u{1F527} [V2] loadPluginConfig called with variant:",t);let n=await jr(),o=await $r();if(o){let c=N(S({},o),{staticResources:n!=null?n: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:n!=null?n:void 0};return console.log("\u2705 [V2] Using raw config parameter (PRIORITY 2)"),c}let i=await qr();if(i){let c=N(S({},i),{staticResources:n!=null?n:void 0});return console.log("\u2705 [V2] Using environment variables config (PRIORITY 3 - build time)"),c}let r=await Br(t);if(r){let c=N(S({},r),{staticResources:n!=null?n: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:n!=null?n:void 0}};async function Hr(t="default",e){try{if(!Ee())return null;if(e)return e;let n=["/config/".concat(t,".config.json"),"/config/".concat(t,".tgd.json"),"/config/".concat(t,".json")];for(let o of n)try{let i=await fetch(o);if(i.ok)return await i.json()}catch(i){continue}return console.warn("\u26A0\uFE0F [loadLocalConfig] No config found for '".concat(t,"'")),null}catch(n){return console.error("[loadLocalConfig] Error loading config:",n),null}}async function qr(){try{if(!Ee())return;let t=W("TAGADA_STORE_ID"),e=W("TAGADA_ACCOUNT_ID"),n=W("TAGADA_BASE_PATH"),o=W("TAGADA_CONFIG_NAME");if(!t||!e)return;let i=await Hr(o);if(!i)return;let r={storeId:t,accountId:e,basePath:n||"/",config:i};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(t){console.error("[createRawPluginConfig] Error creating config:",t);return}}Qe();ue();ue();var sn=new Map,an=new Set;function Vr(){return typeof window=="undefined"?null:new URLSearchParams(window.location.search).get("authCode")}async function Fo(t,e,n,o=!1){if(an.has(t))throw o&&console.log("[AuthHandoff] Code already resolved, skipping duplicate request"),new Error("Auth code already resolved");let i=sn.get(t);if(i)return o&&console.log("[AuthHandoff] Resolution already in progress, waiting for existing request"),i;o&&console.log("[AuthHandoff] Resolving authCode:",t.substring(0,15)+"...");let r=(async()=>{try{let s=await fetch("".concat(n,"/api/v1/cms/auth/resolve-handoff"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,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 o&&console.log("[AuthHandoff] \u2705 Resolved successfully:",{customerId:a.customer.id,role:a.customer.role,hasContext:Object.keys(a.context).length>0}),o&&console.log("[AuthHandoff] Storing new token (overriding existing)"),L(a.token),Kr(o),an.add(t),a}catch(s){throw console.error("[AuthHandoff] \u274C Failed to resolve:",s),s}finally{sn.delete(t)}})();return sn.set(t,r),r}function Kr(t=!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),t&&console.log("[AuthHandoff] Cleaned authCode from URL"))}function No(){let t=Vr();return!(!t||!t.startsWith("ah_")||an.has(t))}var Et=class{constructor(e={}){this.bus=new It;this.eventDispatcher=new le;this.tokenPromise=null;this.tokenResolver=null;this.isInitializingSession=!1;this.lastSessionInitError=null;this.sessionInitRetryCount=0;this.MAX_SESSION_INIT_RETRIES=3;var a,c,u,d;this.config=e,this.instanceId=Math.random().toString(36).substr(2,9),this.boundHandleStorageChange=this.handleStorageChange.bind(this),this.boundHandlePageshow=g=>{if(g.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 y=this.getAccountId(),f=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:y},f).catch(h=>{console.error("[TagadaClient] Funnel re-initialization failed:",h)})}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}),xn(this.config.debugMode)&&this.config.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Preview mode active - state cleared"));let o=this.resolveEnvironment(),i=Cn(o);e.customApiConfig&&(i=N(S(S({},i),e.customApiConfig),{apiConfig:S(S({},i.apiConfig),e.customApiConfig.apiConfig)}),this.config.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Applied custom API config:"),i.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:i,isLoading:!0,isInitialized:!1,isSessionInitialized:!1,pluginConfig:{basePath:"/",config:{}},pluginConfigLoading:!0,debugMode:(a=e.debugMode)!=null?a:o!=="production",token:null},console.log("[TagadaClient ".concat(this.instanceId,"] Initial state:"),{pluginConfigLoading:this.state.pluginConfigLoading,hasRawPluginConfig:!!e.rawPluginConfig}),this.apiClient=new bt({baseURL:i.apiConfig.baseUrl});let r=(c=e.features)==null?void 0:c.funnel;if(r!==!1){let g=typeof r=="object"?r:{};this.funnel=new ke({apiClient:this.apiClient,debugMode:this.state.debugMode,pluginConfig:this.state.pluginConfig,environment:this.state.environment,autoRedirect:g.autoRedirect,funnelId:(u=e.rawPluginConfig)==null?void 0:u.funnelId,stepId:(d=e.rawPluginConfig)==null?void 0:d.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(xe()===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=S(S({},this.state),e),this.eventDispatcher.notify(this.state)}resolveEnvironment(){return this.config.environment?this.config.environment:Te()}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 n=await _o(e,this.config.rawPluginConfig);console.log("[TagadaClient ".concat(this.instanceId,"] Plugin config loaded:"),n),this.updateState({pluginConfig:n,pluginConfigLoading:!1}),this.funnel&&this.funnel.setConfig({pluginConfig:n,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(No()){let n=this.state.pluginConfig.storeId;if(!n)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 o=new URLSearchParams(window.location.search).get("authCode");if(!o)return this.fallbackToNormalFlow();let i=await Fo(o,n,this.state.environment.apiConfig.baseUrl,this.state.debugMode);console.log("[TagadaClient ".concat(this.instanceId,"] \u2705 Auth handoff resolved:"),{customerId:i.customer.id,role:i.customer.role,hasContext:Object.keys(i.context).length>0}),this.setToken(i.token);let r=He(i.token);r?(this.updateState({session:r}),await this.initializeSession(r),(e=i.context)!=null&&e.funnelSessionId&&this.funnel&&this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Restoring funnel session from handoff context:"),i.context.funnelSessionId)):(console.error("[TagadaClient] Failed to decode token from handoff"),this.updateState({isInitialized:!0,isLoading:!1}));return}catch(o){console.error("[TagadaClient ".concat(this.instanceId,"] \u274C Auth handoff failed, falling back to normal flow:"),o)}}await this.fallbackToNormalFlow()}async fallbackToNormalFlow(){let n=new URLSearchParams(typeof window!="undefined"?window.location.search:"").get("token");n&&(this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] \u{1F512} URL token detected, setting immediately to prevent race condition")),this.apiClient.updateToken(n),L(n));let o=xe();console.log("[TagadaClient ".concat(this.instanceId,"] Initializing token (normal flow)..."),{hasExistingToken:!!o,hasQueryToken:!!n,storeId:this.state.pluginConfig.storeId});let i=null,r=!1;if(n?(i=n,r=!0):o&&!Po(o)&&(i=o),i){this.setToken(i),r&&(this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Persisting query token to storage...")),L(i));let s=He(i);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 o=new URLSearchParams(window.location.search).get("token");if(o){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] \u{1F512} URL has token, skipping anonymous token creation")),this.setToken(o),L(o);let i=He(o);i&&(this.updateState({session:i}),await this.initializeSession(i));return}}if(this.isInitializingSession){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Session initialization in progress, skipping anonymous token creation"));return}try{let n=Re();this.state.debugMode&&console.log("[TagadaClient] Creating anonymous token for store:",e,{draft:n});let o=await this.apiClient.post("/api/v1/cms/session/anonymous",{storeId:e,role:"anonymous",draft:n},{skipAuth:!0});this.setToken(o.token),L(o.token);let i=He(o.token);i&&(this.updateState({session:i}),await this.initializeSession(i)),this.updateState({isSessionInitialized:!0})}catch(n){console.error("[TagadaClient] Failed to create anonymous token:",n),this.updateState({isInitialized:!0,isLoading:!1})}}async initializeSession(e){var n,o,i,r,s,a,c,u,d,g,y;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 m=await Ao(),f=ko(),h=Ro(),p=Re(),b=new URLSearchParams(window.location.search).get("draft");b!==null&&Ft(b==="true");let E={storeId:e.storeId,accountId:e.accountId,customerId:e.customerId,role:e.role,browserLocale:h,queryLocale:f.locale,queryCurrency:f.currency,utmSource:f.utmSource,utmMedium:f.utmMedium,utmCampaign:f.utmCampaign,browser:m.userAgent.browser.name,browserVersion:m.userAgent.browser.version,os:m.userAgent.os.name,osVersion:m.userAgent.os.version,deviceType:(n=m.userAgent.device)==null?void 0:n.type,deviceModel:(o=m.userAgent.device)==null?void 0:o.model,deviceVendor:(i=m.userAgent.device)==null?void 0:i.vendor,userAgent:m.userAgent.name,engineName:m.userAgent.engine.name,engineVersion:m.userAgent.engine.version,cpuArchitecture:m.userAgent.cpu.architecture,isBot:(s=(r=m.flags)==null?void 0:r.isBot)!=null?s:!1,isChromeFamily:(c=(a=m.flags)==null?void 0:a.isChromeFamily)!=null?c:!1,isStandalonePWA:(d=(u=m.flags)==null?void 0:u.isStandalonePWA)!=null?d:!1,isAppleSilicon:(y=(g=m.flags)==null?void 0:g.isAppleSilicon)!=null?y:!1,screenWidth:m.screenResolution.width,screenHeight:m.screenResolution.height,timeZone:m.timeZone,draft:p,fetchMessages:!1},C=await this.apiClient.post("/api/v1/cms/session/v2/init",E);this.lastSessionInitError=null,this.sessionInitRetryCount=0,this.updateSessionState(C,e),this.updateState({isInitialized:!0,isSessionInitialized:!0,isLoading:!1}),this.state.debugMode&&console.log("[TagadaClient] Session initialized successfully")}catch(m){this.lastSessionInitError=m,this.sessionInitRetryCount++,console.error("[TagadaClient] Error initializing session (attempt ".concat(this.sessionInitRetryCount,"/").concat(this.MAX_SESSION_INIT_RETRIES,"):"),m),this.updateState({isInitialized:!0,isLoading:!1})}finally{this.isInitializingSession=!1}}updateSessionState(e,n){var s,a,c,u,d,g,y,m,f,h;if(e.store){let p=e.store,b=N(S({},e.store),{accountId:p.accountId||((s=this.state.pluginConfig)==null?void 0:s.accountId)||n.accountId||"",presentmentCurrencies:p.presentmentCurrencies||[e.store.currency||"USD"],chargeCurrencies:p.chargeCurrencies||[e.store.currency||"USD"]});this.updateState({store:b})}if(e.locale){let p={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:p})}if(e.store){let p={code:e.store.currency,symbol:this.getCurrencySymbol(e.store.currency),name:this.getCurrencyName(e.store.currency)};this.updateState({currency:p})}let o={isAuthenticated:(d=(u=e.customer)==null?void 0:u.isAuthenticated)!=null?d:!1,isLoading:!1,customer:(g=e.customer)!=null?g:null,session:n};this.updateState({customer:(y=e.customer)!=null?y:null,auth:o});let i=(m=this.config.features)==null?void 0:m.funnel,r=typeof i=="object"&&i.skipAutoInit;if(this.funnel&&!r&&n.customerId&&((f=e.store)!=null&&f.id)){let p=e.store.accountId||((h=this.state.pluginConfig)==null?void 0:h.accountId)||n.accountId||"";if(p){let E=new URLSearchParams(typeof window!="undefined"?window.location.search:"").get("funnelId")||void 0;this.state.debugMode&&console.log("[TagadaClient] Auto-initializing funnel...",{customerId:n.customerId,storeId:e.store.id,accountId:p,funnelId:E||"auto-detect"}),this.funnel.autoInitialize({customerId:n.customerId,sessionId:n.sessionId},{id:e.store.id,accountId:p},E).catch(C=>{console.error("[TagadaClient] Funnel auto-initialization failed:",C)})}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,n,o;return((e=this.state.store)==null?void 0:e.accountId)||((n=this.state.pluginConfig)==null?void 0:n.accountId)||((o=this.state.session)==null?void 0:o.accountId)||""}updatePluginConfig(e){this.state.debugMode&&console.log("[TagadaClient] Hot-reloading config:",e);let n=S(S({},this.state.pluginConfig.config),e);this.updateState({pluginConfig:N(S({},this.state.pluginConfig),{config:n})}),this.bus.emit("CONFIG_UPDATED",n),this.state.debugMode&&console.log("[TagadaClient] Config updated successfully")}setupConfigHotReload(){if(typeof window=="undefined")return;let e=n=>{var o,i;if(((o=n.data)==null?void 0:o.type)==="TAGADAPAY_CONFIG_UPDATE"){let{config:r}=n.data;this.state.debugMode&&console.log("[TagadaClient] Received config update from parent:",r),this.updatePluginConfig(r)}else if(((i=n.data)==null?void 0:i.type)==="APPLY_STYLES_TO_ELEMENT"){let{elementId:r,styles:s}=n.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,n){if(typeof document=="undefined")return;let o="tagada-editor-highlight",i=document.getElementById(o);i&&i.remove();let r=g=>{var C;let m=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]).has(g.tagName.toLowerCase()),f=g;if(m){let I=g.parentElement;if((I==null?void 0:I.getAttribute("data-tagada-highlight-wrapper"))==="true"&&I instanceof HTMLElement)f=I;else{let T=document.createElement("div");T.setAttribute("data-tagada-highlight-wrapper","true");let P=window.getComputedStyle(g),z=P.display;if(z==="inline"?T.style.display="inline-block":T.style.display=z,T.style.position="relative",z==="inline"||z.includes("inline")){let D=P.verticalAlign;D&&D!=="baseline"&&(T.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 G=D.replace(/([A-Z])/g,"-$1").toLowerCase(),F=P.getPropertyValue(G);F&&F.trim()!==""&&(D==="flex"&&F!=="none"&&F!=="0 1 auto"?T.style.flex=F:D==="boxSizing"?T.style.boxSizing=F:T.style.setProperty(G,F))}),g.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(G=>{let F=g.style.getPropertyValue(G);F&&T.style.setProperty(G,F)}),(C=g.parentNode)==null||C.insertBefore(T,g),T.appendChild(g),f=T}}let h=getComputedStyle(m?g:f);(f.style.position==="static"||!f.style.position)&&(f.style.position="relative");let p=document.createElement("div");p.id=o,p.style.position="absolute",p.style.inset="0",p.style.pointerEvents="none",p.style.zIndex="9999",p.style.boxSizing="border-box",p.style.background="none",p.style.border="none",p.style.outline="none",p.style.margin="0",p.style.padding="0";let b=h.borderRadius;b&&(p.style.borderRadius=b),f.appendChild(p);let E=n||{boxShadow:"0 0 0 2px rgb(239 68 68)"};if(Object.entries(E).forEach(([I,k])=>{let T=I.includes("-")?I.replace(/-([a-z])/g,(P,z)=>z.toUpperCase()):I;I.includes("-")?p.style.setProperty(I,k):p.style[T]=k}),g.scrollIntoView({behavior:"smooth",block:"center"}),this.state.debugMode){let I=Object.entries(E).map(([k,T])=>"".concat(k,": ").concat(T)).join("; ");console.log("[TagadaClient] Applied styles to highlight div of element #".concat(e,":"),I)}},s=5,a=1e3,c=0,u=g=>{let y=window.getComputedStyle(g);return y.display==="none"||y.visibility==="hidden"||y.opacity==="0"||g.hidden||g.offsetWidth===0||g.offsetHeight===0},d=()=>{let g=document.querySelectorAll('[editor-id~="'.concat(e,'"]'));if(g.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(d,a);return}let y=null;if(g.length===1)y=g[0];else{for(let m=0;m<g.length;m++)if(!u(g[m])){y=g[m];break}y||(y=g[0])}y&&r(y)};d()}};nt();function Wr(){if(typeof window=="undefined"||typeof document=="undefined")return[];let t=V();return t!=null&&t.scripts?t.scripts.filter(e=>e.enabled):[]}function Gr(t,e){let n=t.position||"body-end",o="tagada-stepconfig-script-".concat(e);if(document.getElementById(o))return;let i=t.content.trim(),r=i.match(/^<script[^>]*>([\s\S]*)<\/script>$/i);if(r&&(i=r[1].trim()),!i)return;let s="(function() {\n try {\n // Script: "+t.name+"\n"+i+'\n } catch (error) {\n console.error("[TagadaPay] StepConfig script error:", error);\n }\n})();',a=document.createElement("script");switch(a.id=o,a.setAttribute("data-tagada-stepconfig-script","true"),a.setAttribute("data-script-name",t.name),a.textContent=s,n){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 Oo(){let t=Wr();t.length!==0&&t.forEach((e,n)=>{Gr(e,n)})}if(typeof window!="undefined"&&typeof document!="undefined"){let t=()=>{document.body?Oo():document.addEventListener("DOMContentLoaded",Oo,{once:!0})};"requestIdleCallback"in window?window.requestIdleCallback(t,{timeout:100}):setTimeout(t,0)}function Do(t={}){return new Et(t)}ue();var ln="1.0.0";function Lo(t){return typeof window=="undefined"?null:new URLSearchParams(window.location.search).get(t)}function _(t,...e){t&&console.log("[TagadaTracker]",...e)}function Uo(...t){console.warn("[TagadaTracker]",...t)}function Jr(t){if(!t.storeId||typeof t.storeId!="string")throw new Error("TagadaTracker: storeId is required and must be a non-empty string.");if(!t.accountId||typeof t.accountId!="string")throw new Error("TagadaTracker: accountId is required and must be a non-empty string.");if(!t.stepId||typeof t.stepId!="string")throw new Error("TagadaTracker: stepId is required and must be a non-empty string.");if(t.apiBaseUrl)try{new URL(t.apiBaseUrl)}catch(e){throw new Error('TagadaTracker: apiBaseUrl is not a valid URL: "'.concat(t.apiBaseUrl,'"'))}}async function Xr(t,e,n){let o;for(let i=0;i<=e;i++)try{return await t()}catch(r){if(o=r instanceof Error?r:new Error(String(r)),i<e){let s=Math.min(1e3*2**i,8e3);_(n,"Retry ".concat(i+1,"/").concat(e," in ").concat(s,"ms...")),await new Promise(a=>setTimeout(a,s))}}throw o}var xt=class{constructor(){this.config=null;this.client=null;this.initialized=!1;this.initializing=!1;this.unsubscribe=null;this.version=ln}async init(e){var o,i;if(this.initialized)return _(e.debug||!1,"Already initialized \u2014 returning existing session."),this.getSession();if(this.initializing)return _(e.debug||!1,"Initialization in progress \u2014 skipping duplicate call."),null;this.initializing=!0,this.config=S({debug:!1},e);let n=this.config.debug;try{Jr(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}_(n,"\u{1F680} Initializing external tracker v".concat(ln),{storeId:e.storeId,accountId:e.accountId,stepId:e.stepId,funnelId:e.funnelId});try{let r=Lo("token");r&&(L(r),_(n,"\u{1F511} Bootstrapped token from URL")),this.client=Do({debugMode:n,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 Xr(()=>this.initializeFunnel(),2,n);_(n,"\u2705 Session initialized:",s),this.initialized=!0;let a=this.getSession();return a&&((i=(o=this.config).onReady)==null||i.call(o,a)),a}catch(r){let s=r instanceof Error?r:new Error(String(r));if(_(n,"\u274C Initialization failed:",s),this.config.onError)return this.config.onError(s),null;throw s}finally{this.initializing=!1}}getSession(){var n,o;if(!((o=(n=this.client)==null?void 0:n.funnel)!=null&&o.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,n;return this.initialized&&!!((n=(e=this.client)==null?void 0:e.funnel)!=null&&n.state.context)}async navigate(e){if(!this.isReady())throw new Error("TagadaTracker: not initialized. Call init() first.");_(this.config.debug,"\u{1F680} Navigating:",e);let n=e.autoRedirect!==!1;try{let o=await this.client.funnel.navigate({type:e.eventType,data:e.eventData||{}},{autoRedirect:!1});return o!=null&&o.url?(_(this.config.debug,"\u2705 Navigation result:",o.url),n&&typeof window!="undefined"&&(window.location.href=e.returnUrl||o.url),{url:o.url}):null}catch(o){throw _(this.config.debug,"\u274C Navigation failed:",o),o}}async trackEvent(e){if(!this.isReady()){Uo("trackEvent called before init \u2014 event dropped:",e.name);return}_(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(n){_(this.config.debug,"\u26A0\uFE0F Event tracking failed (non-critical):",e.name)}}getCustomerId(){var e,n,o,i,r;return((n=(e=this.client)==null?void 0:e.state.auth.customer)==null?void 0:n.id)||((r=(i=(o=this.client)==null?void 0:o.funnel)==null?void 0:i.state.context)==null?void 0:r.customerId)||null}getFunnelSessionId(){var e,n,o;return((o=(n=(e=this.client)==null?void 0:e.funnel)==null?void 0:n.state.context)==null?void 0:o.sessionId)||null}buildUrl(e,n){let o=this.getSession();if(!o)return e;let i=new URL(e,typeof window!="undefined"?window.location.origin:void 0);return i.searchParams.set("funnelSessionId",o.sessionId),o.cmsToken&&i.searchParams.set("token",o.cmsToken),o.funnelId&&i.searchParams.set("funnelId",o.funnelId),i.searchParams.set("storeId",o.storeId),n&&Object.entries(n).forEach(([r,s])=>{i.searchParams.set(r,s)}),i.toString()}getClient(){return this.client}async reset(e){var i,r;if(!this.client||!this.config)throw new Error("TagadaTracker: not initialized. Call init() first.");_(this.config.debug,"\u{1F504} Resetting to step:",e),this.config.stepId=e;let n=await this.initializeFunnel(),o=this.getSession();return o&&((r=(i=this.config).onReady)==null||r.call(i,o)),o}destroy(){var e,n;this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.client&&((n=(e=this.client).destroy)==null||n.call(e)),this.client=null,this.config=null,this.initialized=!1,this.initializing=!1,_(!1,"\u{1F5D1}\uFE0F Tracker destroyed")}async waitForClientReady(){if(this.client)return new Promise(e=>{var i;if((i=this.client)!=null&&i.state.isInitialized){e();return}let n=!1,o=setTimeout(()=>{var r;n||(n=!0,_(((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;!n&&((r=this.client)!=null&&r.state.isInitialized)&&(n=!0,clearTimeout(o),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,n=(c=this.client.state.auth.session)==null?void 0:c.sessionId;!e&&!n&&Uo("No auth session available \u2014 funnel init may fail.");let o={customerId:e||"anon_placeholder",sessionId:n||"sess_placeholder"},i={id:this.config.storeId,accountId:this.config.accountId},r=this.config.stepId;return _(this.config.debug,"\u{1F50D} Initializing funnel at step:",r),this.client.funnel.initialize(o,i,this.config.funnelId||Lo("funnelId")||void 0,r)}},Mo=new xt;typeof window!="undefined"&&(window.TagadaTracker=Mo);return Wo(Yr);})();
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);})();
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;