@tagadapay/plugin-sdk 4.0.7 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/external-tracker.js +103 -36
  2. package/dist/external-tracker.min.js +2 -2
  3. package/dist/external-tracker.min.js.map +3 -3
  4. package/dist/react/types.d.ts +2 -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 +148 -28
  8. package/dist/tagada-react-sdk.min.js +2 -2
  9. package/dist/tagada-react-sdk.min.js.map +4 -4
  10. package/dist/tagada-sdk.js +125 -45
  11. package/dist/tagada-sdk.min.js +2 -2
  12. package/dist/tagada-sdk.min.js.map +4 -4
  13. package/dist/v2/core/funnelClient.js +14 -9
  14. package/dist/v2/core/pixelMapping.d.ts +84 -0
  15. package/dist/v2/core/pixelMapping.js +102 -0
  16. package/dist/v2/core/pixelTracker.d.ts +1 -6
  17. package/dist/v2/core/pixelTracker.js +36 -2
  18. package/dist/v2/core/resources/credits.d.ts +13 -0
  19. package/dist/v2/core/resources/credits.js +7 -0
  20. package/dist/v2/core/resources/offers.d.ts +5 -1
  21. package/dist/v2/core/resources/offers.js +3 -2
  22. package/dist/v2/core/resources/payments.d.ts +1 -0
  23. package/dist/v2/core/resources/payments.js +1 -0
  24. package/dist/v2/core/types.d.ts +17 -2
  25. package/dist/v2/core/utils/authHandoff.d.ts +2 -1
  26. package/dist/v2/index.d.ts +3 -1
  27. package/dist/v2/index.js +4 -1
  28. package/dist/v2/react/components/FunnelScriptInjector.js +42 -7
  29. package/dist/v2/react/hooks/useAuth.d.ts +1 -0
  30. package/dist/v2/react/hooks/useAuth.js +1 -0
  31. package/dist/v2/react/hooks/useClubOffers.d.ts +16 -0
  32. package/dist/v2/react/hooks/useClubOffers.js +29 -3
  33. package/dist/v2/react/hooks/useCustomer.d.ts +1 -0
  34. package/dist/v2/react/hooks/useCustomer.js +1 -0
  35. package/dist/v2/react/hooks/useStore.d.ts +5 -0
  36. package/dist/v2/react/hooks/useStore.js +16 -0
  37. package/dist/v2/react/index.d.ts +1 -0
  38. package/dist/v2/react/index.js +1 -0
  39. package/dist/v2/standalone/index.js +134 -46
  40. package/dist/v2/standalone/payment-service.d.ts +2 -1
  41. package/dist/v2/standalone/payment-service.js +6 -4
  42. package/package.json +2 -3
@@ -1,9 +1,9 @@
1
1
  /**
2
- * TagadaPay External Tracker v4.0.7
2
+ * TagadaPay External Tracker v4.1.0
3
3
  * CDN Bundle - Standalone tracking for external pages
4
4
  * @license MIT
5
5
  */
6
- "use strict";var TagadaTrackerBundle=(()=>{var re=Object.defineProperty,It=Object.defineProperties,wt=Object.getOwnPropertyDescriptor,vt=Object.getOwnPropertyDescriptors,St=Object.getOwnPropertyNames,Fe=Object.getOwnPropertySymbols;var Ne=Object.prototype.hasOwnProperty,Tt=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))Tt.call(e,t)&&De(n,t,e[t]);return n},S=(n,e)=>It(n,vt(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})},bt=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of St(e))!Ne.call(n,o)&&o!==t&&re(n,o,{get:()=>e[o],enumerable:!(i=wt(e,o))||i.enumerable});return n};var kt=n=>bt(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:S(h({},e),{baseUrl:t})}):{environment:n,apiConfig:e}}function J(){var o;if(console.log("[SDK] detectEnvironment() called"),typeof window=="undefined")return"local";let e=new URLSearchParams(window.location.search).get("tagadaClientEnv");if(e&&(e==="production"||e==="development"||e==="local"))return console.log("[SDK] Using explicit environment override: ".concat(e)),e;try{let r=localStorage.getItem("tgd_client_env")||Ue("tgd_client_env");if(r&&(r==="production"||r==="development"||r==="local"))return console.log("[SDK] Using persisted environment override: ".concat(r)),r}catch(r){}let t=window.location.hostname,i=window.location.href;if(console.log('[SDK] detectEnvironment() - hostname: "'.concat(t,'"')),t==="localhost"||t.startsWith("127.")||t.startsWith("192.168.")||t.startsWith("10.")||t.includes(".local")||t===""||t==="0.0.0.0"||t.includes("ngrok-free.dev")||t.includes("ngrok-free.app")||t.includes("ngrok.io")||t.includes("ngrok.app")||t.includes(".loclx.io")){if(console.log("[SDK] detectEnvironment() - returning LOCAL"),typeof window!="undefined"&&((o=window==null?void 0:window.__TAGADA_ENV__)!=null&&o.TAGADA_ENVIRONMENT)){let r=window.__TAGADA_ENV__.TAGADA_ENVIRONMENT.toLowerCase();if(r==="production"||r==="development"||r==="local")return console.log("[SDK] Local override detected: ".concat(r)),r}return"local"}return t.includes("tagada.io")||t.includes("tagadapay.com")||t.includes("yourproductiondomain.com")?"production":t.includes("tagada.dev")||t.includes("tagadapay.dev")||t.includes("vercel.app")||t.includes("netlify.app")||t.includes("surge.sh")||t.includes("github.io")||t.includes("herokuapp.com")||t.includes("railway.app")||i.includes("?env=dev")||i.includes("?dev=true")||i.includes("#dev")?"development":(console.warn("[SDK] Unknown domain: ".concat(t,", defaulting to production")),"production")}function Y(n=!1){return J()!=="local"?!1:n&&typeof window!="undefined"?!window.location.hostname.includes(".cdn."):!0}var Le,se=N(()=>{"use strict";Le={production:{baseUrl:"https://api.tagada.io",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionInitAsync:"/api/v1/checkout/session/init-async",sessionStatus:"/api/v1/checkout/session/status",asyncStatus:"/api/public/v1/checkout/async-status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}},development:{baseUrl:"https://api.tagada.dev",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionInitAsync:"/api/v1/checkout/session/init-async",sessionStatus:"/api/v1/checkout/session/status",asyncStatus:"/api/public/v1/checkout/async-status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}},local:{baseUrl:"http://app.localhost:3000",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionInitAsync:"/api/v1/checkout/session/init-async",sessionStatus:"/api/v1/checkout/session/status",asyncStatus:"/api/public/v1/checkout/async-status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}}}});var ae,Me=N(()=>{"use strict";ae=class{constructor(e){this.apiClient=e}async initialize(e){return this.apiClient.post("/api/v1/funnel/initialize",e)}async navigate(e){return this.apiClient.post("/api/v1/funnel/navigate",e)}async updateContext(e,t){return this.apiClient.patch("/api/v1/funnel/context/".concat(e),t)}async endSession(e){return this.apiClient.delete("/api/v1/funnel/session/".concat(e))}async getSession(e,t,i){let o=new URLSearchParams;t&&o.append("currentUrl",t),i&&o.append("includeDebugData","true");let r="/api/v1/funnel/session/".concat(e).concat(o.toString()?"?".concat(o):"");return this.apiClient.get(r)}}});var $,be=N(()=>{"use strict";$=class{constructor(){this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){this.listeners.forEach(t=>{try{t(e)}catch(i){console.error("Error in event listener:",i)}})}clear(){this.listeners.clear()}}});function x(n){if(typeof window!="undefined")try{let t=localStorage.getItem(le)!==n;localStorage.setItem(le,n),t&&window.dispatchEvent(new Event("storage"))}catch(e){console.error("Failed to save token to localStorage:",e)}}function X(){if(typeof window!="undefined")try{return localStorage.getItem(le)}catch(n){return console.error("Failed to get token from localStorage:",n),null}return null}function B(){if(typeof window!="undefined")try{localStorage.removeItem(le)}catch(n){console.error("Failed to clear token from localStorage:",n)}}var le,j=N(()=>{"use strict";le="cms_token"});function ze(n){typeof document!="undefined"&&(document.cookie="".concat(ke,"=").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(ke,"=")));return n?n.split("=")[1]:void 0}function ce(){typeof document!="undefined"&&(document.cookie="".concat(ke,"=; path=/; max-age=0"))}var ke,de=N(()=>{"use strict";ke="tgd-funnel-session-id"});function G(n){if(typeof window=="undefined")return null;try{return localStorage.getItem(n)}catch(e){return null}}function K(n,e){if(typeof window!="undefined")try{localStorage.setItem(n,e)}catch(t){}}function Z(n){var i;if(typeof document=="undefined")return null;let t=document.cookie.split(";").find(o=>o.trim().startsWith("".concat(n,"=")));return t?(i=t.split("=")[1])==null?void 0:i.trim():null}function Q(n,e,t=86400){if(typeof document!="undefined"){if(n==="tgd_draft"||n==="tgd-draft"){console.warn("\u{1F6E1}\uFE0F [SDK] Blocked attempt to set ".concat(n," as cookie - this should only be in localStorage"));return}document.cookie="".concat(n,"=").concat(e,"; path=/; max-age=").concat(t)}}function je(n){typeof document!="undefined"&&(document.cookie="".concat(n,"=; path=/; max-age=0"))}function U(){if(typeof window=="undefined")return{};let n=new URLSearchParams(window.location.search),e,t=n.get("draft");if(t!==null)e=t==="true";else{let y=G(C.DRAFT);y!==null&&(e=y==="true")}let i,o=n.get("funnelTracking");if(o!==null)i=o!=="false";else{let y=G(C.FUNNEL_TRACKING)||Z(C.FUNNEL_TRACKING);y!==null&&(i=y!=="false")}let r=n.get("token")||X()||null,s=n.get("funnelSessionId")||null,a=n.get("funnelId")||null,c,p=n.get("funnelEnv");p&&(p==="staging"||p==="production")&&(c=p);let m=n.get("forceReset")==="true",l,f=n.get("tagadaClientEnv");if(f&&(f==="production"||f==="development"||f==="local"))l=f;else{let y=G(C.CLIENT_ENV)||Z(C.CLIENT_ENV);y&&(y==="production"||y==="development"||y==="local")&&(l=y)}let u,d=n.get("tagadaClientBaseUrl");if(d)u=d;else{let y=G(C.CLIENT_BASE_URL)||Z(C.CLIENT_BASE_URL);y&&(u=y)}let w,g=n.get("currency");if(g)w=g;else{let y=G(C.CURRENCY)||Z(C.CURRENCY);y&&(w=y)}let I,A=n.get("locale");if(A)I=A;else{let y=G(C.LOCALE)||Z(C.LOCALE);y&&(I=y)}return{forceReset:m,token:r,funnelSessionId:s,funnelId:a,draft:e,funnelTracking:i,funnelEnv:c,tagadaClientEnv:l,tagadaClientBaseUrl:u,currency:w,locale:I}}function ee(){var e;return(e=U().draft)!=null?e:!1}function xe(n){if(typeof window!="undefined")if(n)K(C.DRAFT,"true");else try{localStorage.removeItem(C.DRAFT)}catch(e){}}function Ge(n=!1){let e=null;typeof window!="undefined"&&(e=new URLSearchParams(window.location.search).get("token"));let t=U(),i=t.forceReset||!1;if(!i&&!t.token)return Be(),!1;n&&(console.log("[SDK] Detected params:",t),console.log("[SDK] URL token (direct read):",e?e.substring(0,20)+"...":"none")),i&&(n&&console.log("[SDK] Force reset: Clearing all stored state"),B(),ce(),typeof window!="undefined"&&window.localStorage&&Object.keys(localStorage).forEach(s=>{(s.startsWith("tagadapay_")||s.startsWith("tgd_"))&&(n&&console.log("[SDK] Clearing localStorage: ".concat(s)),localStorage.removeItem(s))}));let o=e||t.token;return o!=null?(n&&console.log("[SDK] Setting token from URL:",o.substring(0,20)+"..."),o===""||o==="null"?B():(x(o),n&&console.log("[SDK] \u2705 Token set in localStorage immediately after clear"))):i&&(n&&console.log("[SDK] Force reset mode (no token in URL)"),B()),Be(),t.funnelSessionId&&n&&console.log("[SDK] Using funnelSessionId from URL:",t.funnelSessionId),i}function Be(){if(typeof window=="undefined")return;let n=new URLSearchParams(window.location.search),e=n.get("draft");e!==null&&xe(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&&Rt(o);let r=n.get("currency");r&&(K(C.CURRENCY,r.toUpperCase()),Q(C.CURRENCY,r.toUpperCase(),86400));let s=n.get("locale");s&&(K(C.LOCALE,s),Q(C.LOCALE,s,86400))}function xt(n){if(typeof window=="undefined")return;let e=n?"true":"false";K(C.FUNNEL_TRACKING,e),Q(C.FUNNEL_TRACKING,e,86400)}function Et(n){typeof window!="undefined"&&(K(C.CLIENT_ENV,n),Q(C.CLIENT_ENV,n,86400))}function Ke(){if(typeof window!="undefined")try{localStorage.removeItem(C.CLIENT_ENV),je(C.CLIENT_ENV)}catch(n){}}function Rt(n){typeof window!="undefined"&&(K(C.CLIENT_BASE_URL,n),Q(C.CLIENT_BASE_URL,n,86400))}function Ve(){if(typeof window!="undefined")try{localStorage.removeItem(C.CLIENT_BASE_URL),je(C.CLIENT_BASE_URL)}catch(n){}}function He(){var e;return(e=U().funnelTracking)!=null?e:!0}var C,ue=N(()=>{"use strict";j();de();C={DRAFT:"tgd_draft",FUNNEL_TRACKING:"tgd_funnel_tracking",FORCE_RESET:"tgd_force_reset",CLIENT_ENV:"tgd_client_env",CLIENT_BASE_URL:"tgd_client_base_url",CURRENCY:"tgd_currency",LOCALE:"tgd_locale"}});var qe={};Te(qe,{injectPreviewModeIndicator:()=>Pt,isIndicatorInjected:()=>Ft,removePreviewModeIndicator:()=>_t});function Ee(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 At(){if(typeof window=="undefined"||!confirm("\u{1F6AA} Leave Preview Mode?\n\nThis will clear ALL cookies and localStorage (including Shopify session, cart, and preview settings) and reload the page.\n\nAre you sure?"))return;let e=new URL(window.location.href);["draft","funnelEnv","funnelTracking","tagadaClientEnv","tagadaClientBaseUrl","forceReset","funnelId","funnelSessionId","token"].forEach(r=>e.searchParams.delete(r)),window.history.replaceState({},"",e.href);try{let r=Object.getOwnPropertyDescriptor(Document.prototype,"cookie")||Object.getOwnPropertyDescriptor(HTMLDocument.prototype,"cookie");r&&r.set&&Object.defineProperty(document,"cookie",{configurable:!0,enumerable:!0,get:function(){return r.get?r.get.call(this):""},set:function(s){if(typeof s=="string"){let a=s.toLowerCase();if(a.includes("tgd_draft")||a.includes("tgd-draft")||a.includes("tgd.draft")||a.includes("tgddraft")){if(a.includes("max-age=0")||a.includes("expires=thu, 01 jan 1970")){r.set&&r.set.call(this,s);return}console.warn("\u{1F6E1}\uFE0F [TagadaPay] BLOCKED: tgd_draft should never be a cookie");return}}r.set&&r.set.call(this,s)}})}catch(r){console.warn("[TagadaPay] Could not install cookie blocker:",r)}if(window.localStorage)try{localStorage.removeItem("tgd_draft"),localStorage.removeItem("tgd_funnel_tracking"),localStorage.removeItem("tgd_client_env"),localStorage.removeItem("tgd_client_base_url"),localStorage.removeItem("cms_token")}catch(r){console.warn("[TagadaPay] Failed to clear some localStorage keys:",r)}B(),ce(),Ke(),Ve(),window.localStorage&&localStorage.clear(),window.sessionStorage&&sessionStorage.clear(),["tgd-funnel-session-id","tgd_draft","tgd_funnel_tracking","tgd_client_env","tgd_client_base_url","cms_token","tagadapay_session"].forEach(r=>Ee(r)),["tgd-draft","tgd_draft","tgd.draft","tgddraft"].forEach(r=>Ee(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(),Ee("tgd_draft"),typeof window.stop=="function"&&window.stop(),window.location.replace(e.href)},10)}function Pt(){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(),At()})),o.appendChild(r),o.appendChild(a),o.appendChild(s),document.body.appendChild(o),V=o,fe=!0}function _t(){V&&V.parentNode&&(V.parentNode.removeChild(V),V=null,fe=!1)}function Ft(){return fe}var V,fe,We=N(()=>{"use strict";ue();j();de();V=null,fe=!1});var rt={};Te(rt,{FunnelClient:()=>ne,TrackingProvider:()=>Ze,findMethod:()=>tt,getAssignedCheckoutOfferDefault:()=>Ht,getAssignedCheckoutOfferIds:()=>Vt,getAssignedOrderBumpOfferIds:()=>Gt,getAssignedPaymentFlowId:()=>it,getAssignedPaymentInitiator:()=>zt,getAssignedPixels:()=>jt,getAssignedResources:()=>ot,getAssignedScripts:()=>Bt,getAssignedStaticResources:()=>$t,getAssignedStepConfig:()=>k,getAssignedUpsellOfferIds:()=>Kt,getEnabledMethods:()=>Qe,getExpressMethods:()=>et,getExpressMethodsByProcessor:()=>Dt,getLocalFunnelConfig:()=>nt,isMethodEnabled:()=>Nt,loadLocalFunnelConfig:()=>Ot});function Qe(n){return n?Object.values(n).filter(e=>e.enabled):[]}function et(n){return Qe(n).filter(e=>e.express)}function Dt(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 Nt(n,e){return!!tt(n,e)}function Lt(){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 Ut(){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 Ot(){if(!Ut())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 Mt(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,checkoutOffers:n.checkoutOffers}}function k(){if(typeof window=="undefined")return;let n=nt();if(n)return console.log("\u{1F6E0}\uFE0F [SDK] Using local funnel.local.json (overrides injected)"),Mt(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=k(),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 zt(){let n=k();return n==null?void 0:n.paymentInitiator}function ot(){let n=k(),e=n==null?void 0:n.staticResources,t=n==null?void 0:n.resources;if(!(!e&&!t))return h(h({},e),t)}function $t(){return ot()}function Bt(n){let e=k();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=>S(h({},n),{[e]:o}))}function jt(){let n=k(),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 Gt(){let n=k();if(n!=null&&n.orderBumps&&n.orderBumps.mode==="custom")return n.orderBumps.enabledOfferIds}function Kt(){let n=k();if(n!=null&&n.upsellOffers&&n.upsellOffers.mode==="custom")return n.upsellOffers.enabledUpsellIds}function Vt(){let n=k();if(n!=null&&n.checkoutOffers&&n.checkoutOffers.mode==="custom")return n.checkoutOffers.enabledOfferIds}function Ht(){var e;let n=k();return(e=n==null?void 0:n.checkoutOffers)==null?void 0:e.defaultOfferId}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=Lt(),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:S(h({},e),{static:h(h({},i),o)})}}});var bn={};Te(bn,{TRACKER_VERSION:()=>_e,TagadaExternalTracker:()=>Se,TagadaTracker:()=>Ct});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?qt([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 qt(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 Wt(){return{width:window.screen.width,height:window.screen.height}}function Jt(){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 R(n,...e){for(let t of e){let i=n.match(t);if(i)return i}return null}function Yt(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 Xt(n){let e=R(n,/Windows NT ([\d.]+)/i)||R(n,/Mac OS X ([\d_.]+)/i)||R(n,/Android ([\d.]+)/i)||R(n,/iPhone OS ([\d_]+)/i)||R(n,/iPad.*OS ([\d_]+)/i)||R(n,/CrOS[\w ]*\/([\d.]+)/i)||R(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 Zt(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 Qt(n){let e=R(n,/AppleWebKit\/([\d.]+)/i)||R(n,/Gecko\/([\d.]+)/i)||R(n,/Trident\/([\d.]+)/i)||R(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 en(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 tn(){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 nn(n){return/Chrome|Chromium|Edge|Brave|Opera|Vivaldi|Arc/i.test(n)}function on(){return window.matchMedia("(display-mode: standalone)").matches||navigator.standalone===!0}function rn(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=Yt(M),e=Xt(M),t=Zt(M),i=Qt(M),o=en(M),r;try{r={isBot:tn(),isChromeFamily:nn(n.name),isStandalonePWA:on(),isAppleSilicon:rn(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:Wt(),timeZone:Jt(),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={},sn=["","VITE_","REACT_APP_","NEXT_PUBLIC_"];function F(n,e=sn){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 an=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}},ln=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},cn=()=>{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 dn=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=cn();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 ln(),i=await dn();if(i){let c=S(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 fn();if(o){let c=S(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 an(n);if(r){let c=S(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 un(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 fn(){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 un(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 gn(){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),pn(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 pn(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=gn();return!(!n||!n.startsWith("ah_")||Pe.has(n))}var ve=class{constructor(e={}){this.bus=new Ie;this.eventDispatcher=new $;this.tokenPromise=null;this.tokenResolver=null;this.isInitializingSession=!1;this.lastSessionInitError=null;this.sessionInitRetryCount=0;this.MAX_SESSION_INIT_RETRIES=3;var a,c,p,m;this.config=e,this.instanceId=Math.random().toString(36).substr(2,9),this.boundHandleStorageChange=this.handleStorageChange.bind(this),this.boundHandlePageshow=l=>{if(l.persisted)if(this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Page restored from BFcache (back button), re-initializing funnel...")),this.funnel&&this.state.session&&this.state.store){this.funnel.resetInitialization();let f=this.getAccountId(),d=new URLSearchParams(typeof window!="undefined"?window.location.search:"").get("funnelId")||void 0;this.funnel.autoInitialize({customerId:this.state.session.customerId,sessionId:this.state.session.sessionId},{id:this.state.store.id,accountId:f},d).catch(w=>{console.error("[TagadaClient] Funnel re-initialization failed:",w)})}else this.sessionInitRetryCount=0,this.initialize()},console.log("[TagadaClient ".concat(this.instanceId,"] Initializing...")),console.log("[TagadaClient ".concat(this.instanceId,"] Config:"),{debugMode:e.debugMode,hasRawPluginConfig:!!e.rawPluginConfig,rawPluginConfig:e.rawPluginConfig,features:e.features}),Ge(this.config.debugMode)&&this.config.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Preview mode active - state cleared"));let i=this.resolveEnvironment(),o=Oe(i);e.customApiConfig&&(o=S(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&&xe(I==="true");let A={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",A);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=S(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 A=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:A||"auto-detect"}),this.funnel.autoInitialize({customerId:t.customerId,sessionId:t.sessionId},{id:e.store.id,accountId:g},A).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:S(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 b=l.parentElement;if((b==null?void 0:b.getAttribute("data-tagada-highlight-wrapper"))==="true"&&b instanceof HTMLElement)d=b;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(),P=oe.getPropertyValue(W);P&&P.trim()!==""&&(D==="flex"&&P!=="none"&&P!=="0 1 auto"?v.style.flex=P:D==="boxSizing"?v.style.boxSizing=P:v.style.setProperty(W,P))}),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 P=l.style.getPropertyValue(W);P&&v.style.setProperty(W,P)}),(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 A=t||{boxShadow:"0 0 0 2px rgb(239 68 68)"};if(Object.entries(A).forEach(([b,q])=>{let v=b.includes("-")?b.replace(/-([a-z])/g,(oe,z)=>z.toUpperCase()):b;b.includes("-")?g.style.setProperty(b,q):g.style[v]=q}),l.scrollIntoView({behavior:"smooth",block:"center"}),this.state.debugMode){let b=Object.entries(A).map(([q,v])=>"".concat(q,": ").concat(v)).join("; ");console.log("[TagadaClient] Applied styles to highlight div of element #".concat(e,":"),b)}},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();var mn=Object.freeze(["cf_click_id","cid","rtkclickid","cmc_tid","cmc_id","cmcid","clickid","click_id","gclid","gbraid","wbraid","fbclid","msclkid","ttclid","twclid","li_fat_id","epik","dclid","yclid","irclickid"]),hn=Object.freeze(["cf_click_id","cfclid","rtkclickid-store","_rtkclickid","rtkclickid","_voluum","_voluumclickid","_binom","_binomclickid","_mck","cmcid","skro-click-id","click_id"]);function yn(n){if(typeof document=="undefined"||!document.cookie)return null;let e=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));if(!t)return null;try{return decodeURIComponent(t[1])}catch(i){return t[1]}}function Cn(n,e){if(!n)return null;try{return new URLSearchParams(n).get(e)}catch(t){return null}}function In(){var r,s;let n={},e=null,t=null,i=null,o=typeof window!="undefined"&&(s=(r=window.location)==null?void 0:r.search)!=null?s:"";for(let a of mn){let c=Cn(o,a);c&&(n["url:".concat(a)]=c,e===null&&(e=c,t="url",i=a))}for(let a of hn){let c=yn(a);c&&(n["cookie:".concat(a)]=c,e===null&&(e=c,t="cookie",i=a))}return{clickId:e,source:t,key:i,all:n}}function gt(){var t;if(typeof window=="undefined")return null;let n=In(),e=S(h({},n),{resolvedAt:Date.now()});return window.TagadaPay=S(h({},(t=window.TagadaPay)!=null?t:{}),{tracking:e}),e}function wn(){if(typeof window=="undefined"||typeof document=="undefined")return[];let n=k();return n!=null&&n.scripts?n.scripts.filter(e=>e.enabled):[]}function vn(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 pt(){let n=wn();n.length!==0&&n.forEach((e,t)=>{vn(e,t)})}if(typeof window!="undefined"&&typeof document!="undefined"){try{gt()}catch(e){console.error("[TagadaPay] Failed to publish tracking global:",e)}let n=()=>{document.body?pt():document.addEventListener("DOMContentLoaded",pt,{once:!0})};"requestIdleCallback"in window?window.requestIdleCallback(n,{timeout:100}):setTimeout(n,0)}function mt(n={}){return new ve(n)}j();var _e="1.0.0";function ht(n){return typeof window=="undefined"?null:new URLSearchParams(window.location.search).get(n)}function T(n,...e){n&&console.log("[TagadaTracker]",...e)}function yt(...n){console.warn("[TagadaTracker]",...n)}function Sn(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 Tn(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);T(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 T(e.debug||!1,"Already initialized \u2014 returning existing session."),this.getSession();if(this.initializing)return T(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{Sn(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}T(t,"\u{1F680} Initializing external tracker v".concat(_e),{storeId:e.storeId,accountId:e.accountId,stepId:e.stepId,funnelId:e.funnelId});try{let r=ht("token");r&&(x(r),T(t,"\u{1F511} Bootstrapped token from URL")),this.client=mt({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 Tn(()=>this.initializeFunnel(),2,t);T(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(T(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.");T(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?(T(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 T(this.config.debug,"\u274C Navigation failed:",i),i}}async trackEvent(e){if(!this.isReady()){yt("trackEvent called before init \u2014 event dropped:",e.name);return}T(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){T(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.");T(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,T(!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,T(((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&&yt("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 T(this.config.debug,"\u{1F50D} Initializing funnel at step:",r),this.client.funnel.initialize(i,o,this.config.funnelId||ht("funnelId")||void 0,r)}},Ct=new Se;typeof window!="undefined"&&(window.TagadaTracker=Ct);return kt(bn);})();
6
+ "use strict";var TagadaTrackerBundle=(()=>{var re=Object.defineProperty,St=Object.defineProperties,bt=Object.getOwnPropertyDescriptor,Tt=Object.getOwnPropertyDescriptors,kt=Object.getOwnPropertyNames,De=Object.getOwnPropertySymbols;var Ne=Object.prototype.hasOwnProperty,xt=Object.prototype.propertyIsEnumerable;var Le=(t,e,n)=>e in t?re(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,h=(t,e)=>{for(var n in e||(e={}))Ne.call(e,n)&&Le(t,n,e[n]);if(De)for(var n of De(e))xt.call(e,n)&&Le(t,n,e[n]);return t},v=(t,e)=>St(t,Tt(e));var L=(t,e)=>()=>(t&&(e=t(t=0)),e);var Te=(t,e)=>{for(var n in e)re(t,n,{get:e[n],enumerable:!0})},Et=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kt(e))!Ne.call(t,o)&&o!==n&&re(t,o,{get:()=>e[o],enumerable:!(i=bt(e,o))||i.enumerable});return t};var Rt=t=>Et(re({},"__esModule",{value:!0}),t);function Oe(t){var i;if(typeof document=="undefined")return null;let n="; ".concat(document.cookie).split("; ".concat(t,"="));return n.length===2&&((i=n.pop())==null?void 0:i.split(";").shift())||null}function Me(t="local"){let e=Ue[t];if(!e)return console.warn("Unknown environment: ".concat(t,". Falling back to local.")),{environment:"local",apiConfig:Ue.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")||Oe("tgd_client_base_url")}catch(o){}return n?(console.log("[SDK] Using custom API base URL override: ".concat(n)),{environment:t,apiConfig:v(h({},e),{baseUrl:n})}):{environment:t,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")||Oe("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,i=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"&&((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 n.includes("tagada.io")||n.includes("tagadapay.com")||n.includes("yourproductiondomain.com")?"production":n.includes("tagada.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")||i.includes("?env=dev")||i.includes("?dev=true")||i.includes("#dev")?"development":(console.warn("[SDK] Unknown domain: ".concat(n,", defaulting to production")),"production")}function Y(t=!1){return J()!=="local"?!1:t&&typeof window!="undefined"?!window.location.hostname.includes(".cdn."):!0}var Ue,se=L(()=>{"use strict";Ue={production:{baseUrl:"https://api.tagada.io",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionInitAsync:"/api/v1/checkout/session/init-async",sessionStatus:"/api/v1/checkout/session/status",asyncStatus:"/api/public/v1/checkout/async-status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}},development:{baseUrl:"https://api.tagada.dev",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionInitAsync:"/api/v1/checkout/session/init-async",sessionStatus:"/api/v1/checkout/session/status",asyncStatus:"/api/public/v1/checkout/async-status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}},local:{baseUrl:"http://app.localhost:3000",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionInitAsync:"/api/v1/checkout/session/init-async",sessionStatus:"/api/v1/checkout/session/status",asyncStatus:"/api/public/v1/checkout/async-status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}}}});var ae,ze=L(()=>{"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,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,i){let o=new URLSearchParams;n&&o.append("currentUrl",n),i&&o.append("includeDebugData","true");let r="/api/v1/funnel/session/".concat(e).concat(o.toString()?"?".concat(o):"");return this.apiClient.get(r)}}});var $,ke=L(()=>{"use strict";$=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(i){console.error("Error in event listener:",i)}})}clear(){this.listeners.clear()}}});function x(t){if(typeof window!="undefined")try{let n=localStorage.getItem(le)!==t;localStorage.setItem(le,t),n&&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(t){return console.error("Failed to get token from localStorage:",t),null}return null}function B(){if(typeof window!="undefined")try{localStorage.removeItem(le)}catch(t){console.error("Failed to clear token from localStorage:",t)}}var le,j=L(()=>{"use strict";le="cms_token"});function $e(t){typeof document!="undefined"&&(document.cookie="".concat(xe,"=").concat(t,"; path=/; max-age=2592000; SameSite=Lax"))}function Be(){if(typeof document=="undefined")return;let t=document.cookie.split("; ").find(e=>e.startsWith("".concat(xe,"=")));return t?t.split("=")[1]:void 0}function ce(){typeof document!="undefined"&&(document.cookie="".concat(xe,"=; path=/; max-age=0"))}var xe,de=L(()=>{"use strict";xe="tgd-funnel-session-id"});function G(t){if(typeof window=="undefined")return null;try{return localStorage.getItem(t)}catch(e){return null}}function K(t,e){if(typeof window!="undefined")try{localStorage.setItem(t,e)}catch(n){}}function Z(t){var i;if(typeof document=="undefined")return null;let n=document.cookie.split(";").find(o=>o.trim().startsWith("".concat(t,"=")));return n?(i=n.split("=")[1])==null?void 0:i.trim():null}function Q(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 Ge(t){typeof document!="undefined"&&(document.cookie="".concat(t,"=; path=/; max-age=0"))}function U(){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 y=G(C.DRAFT);y!==null&&(e=y==="true")}let i,o=t.get("funnelTracking");if(o!==null)i=o!=="false";else{let y=G(C.FUNNEL_TRACKING)||Z(C.FUNNEL_TRACKING);y!==null&&(i=y!=="false")}let r=t.get("token")||X()||null,s=t.get("funnelSessionId")||null,a=t.get("funnelId")||null,c,d=t.get("funnelEnv");d&&(d==="staging"||d==="production")&&(c=d);let g=t.get("forceReset")==="true",l,p=t.get("tagadaClientEnv");if(p&&(p==="production"||p==="development"||p==="local"))l=p;else{let y=G(C.CLIENT_ENV)||Z(C.CLIENT_ENV);y&&(y==="production"||y==="development"||y==="local")&&(l=y)}let f,u=t.get("tagadaClientBaseUrl");if(u)f=u;else{let y=G(C.CLIENT_BASE_URL)||Z(C.CLIENT_BASE_URL);y&&(f=y)}let w,m=t.get("currency");if(m)w=m;else{let y=G(C.CURRENCY)||Z(C.CURRENCY);y&&(w=y)}let I,A=t.get("locale");if(A)I=A;else{let y=G(C.LOCALE)||Z(C.LOCALE);y&&(I=y)}return{forceReset:g,token:r,funnelSessionId:s,funnelId:a,draft:e,funnelTracking:i,funnelEnv:c,tagadaClientEnv:l,tagadaClientBaseUrl:f,currency:w,locale:I}}function ee(){var e;return(e=U().draft)!=null?e:!1}function Ee(t){if(typeof window!="undefined")if(t)K(C.DRAFT,"true");else try{localStorage.removeItem(C.DRAFT)}catch(e){}}function Ke(t=!1){let e=null;typeof window!="undefined"&&(e=new URLSearchParams(window.location.search).get("token"));let n=U(),i=n.forceReset||!1;if(!i&&!n.token)return je(),!1;t&&(console.log("[SDK] Detected params:",n),console.log("[SDK] URL token (direct read):",e?e.substring(0,20)+"...":"none")),i&&(t&&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_"))&&(t&&console.log("[SDK] Clearing localStorage: ".concat(s)),localStorage.removeItem(s))}));let o=e||n.token;return o!=null?(t&&console.log("[SDK] Setting token from URL:",o.substring(0,20)+"..."),o===""||o==="null"?B():(x(o),t&&console.log("[SDK] \u2705 Token set in localStorage immediately after clear"))):i&&(t&&console.log("[SDK] Force reset mode (no token in URL)"),B()),je(),n.funnelSessionId&&t&&console.log("[SDK] Using funnelSessionId from URL:",n.funnelSessionId),i}function je(){if(typeof window=="undefined")return;let t=new URLSearchParams(window.location.search),e=t.get("draft");e!==null&&Ee(e==="true");let n=t.get("funnelTracking");n!==null&&At(n!=="false");let i=t.get("tagadaClientEnv");i&&(i==="production"||i==="development"||i==="local")&&Pt(i);let o=t.get("tagadaClientBaseUrl");o&&_t(o);let r=t.get("currency");r&&(K(C.CURRENCY,r.toUpperCase()),Q(C.CURRENCY,r.toUpperCase(),86400));let s=t.get("locale");s&&(K(C.LOCALE,s),Q(C.LOCALE,s,86400))}function At(t){if(typeof window=="undefined")return;let e=t?"true":"false";K(C.FUNNEL_TRACKING,e),Q(C.FUNNEL_TRACKING,e,86400)}function Pt(t){typeof window!="undefined"&&(K(C.CLIENT_ENV,t),Q(C.CLIENT_ENV,t,86400))}function Ve(){if(typeof window!="undefined")try{localStorage.removeItem(C.CLIENT_ENV),Ge(C.CLIENT_ENV)}catch(t){}}function _t(t){typeof window!="undefined"&&(K(C.CLIENT_BASE_URL,t),Q(C.CLIENT_BASE_URL,t,86400))}function He(){if(typeof window!="undefined")try{localStorage.removeItem(C.CLIENT_BASE_URL),Ge(C.CLIENT_BASE_URL)}catch(t){}}function qe(){var e;return(e=U().funnelTracking)!=null?e:!0}var C,ue=L(()=>{"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 We={};Te(We,{injectPreviewModeIndicator:()=>Dt,isIndicatorInjected:()=>Nt,removePreviewModeIndicator:()=>Lt});function Re(t){if(typeof window=="undefined"||typeof document=="undefined")return;let e=window.location.hostname,n=e.split("."),i=["",e,"."+e];for(let a=1;a<n.length;a++){let c=n.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 d="".concat(t,"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=").concat(c),g=a?"; domain=".concat(a):"";document.cookie=d+g,document.cookie=d+g+"; secure",document.cookie=d+g+"; SameSite=None; secure",document.cookie=d+g+"; SameSite=Lax",document.cookie=d+g+"; SameSite=Strict"})})}function Ft(){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(),He(),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=>Re(r)),["tgd-draft","tgd_draft","tgd.draft","tgddraft"].forEach(r=>Re(r)),document.cookie&&document.cookie.split(";").forEach(s=>{let a=s.split("=")[0].trim();if(!a)return;let c=window.location.hostname,d=c.split("."),g=["",c,"."+c];for(let u=1;u<d.length;u++){let w=d.slice(u).join(".");g.push(w),g.push("."+w)}let l=window.location.pathname.split("/").filter(u=>u),p=["/"],f="";l.forEach(u=>{f+="/"+u,p.push(f)}),g.forEach(u=>{p.forEach(w=>{let m="".concat(a,"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=").concat(w),I=u?"; domain=".concat(u):"";document.cookie=m+I,document.cookie=m+I+"; secure",document.cookie=m+I+"; SameSite=None; secure",document.cookie=m+I+"; SameSite=Lax",document.cookie=m+I+"; SameSite=Strict",document.cookie=m+I+"; secure; SameSite=None",document.cookie=m+I+"; secure; SameSite=Lax",document.cookie=m+I+"; secure; SameSite=Strict"})})}),setTimeout(()=>{window.localStorage&&localStorage.length>0&&localStorage.clear(),Re("tgd_draft"),typeof window.stop=="function"&&window.stop(),window.location.replace(e.href)},10)}function Dt(){if(fe||typeof window=="undefined"||typeof document=="undefined")return;let t=U(),e=ee(),n=!qe(),i=!!(t.tagadaClientEnv||t.tagadaClientBaseUrl);if(!e&&!n&&!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 '),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 d=!1,g=()=>{d=!0,s.style.display="block",a.style.display="block"},l=()=>{d=!1,setTimeout(()=>{d||(s.style.display="none",a.style.display="none")},100)};r.addEventListener("mouseenter",g),r.addEventListener("mouseleave",l),a.addEventListener("mouseenter",g),a.addEventListener("mouseleave",l),s.addEventListener("mouseenter",g),s.addEventListener("mouseleave",l);let p=s.querySelector("#tgd-leave-preview");p&&(p.addEventListener("mouseenter",()=>{p.style.opacity="0.8"}),p.addEventListener("mouseleave",()=>{p.style.opacity="1"}),p.addEventListener("click",f=>{f.stopPropagation(),Ft()})),o.appendChild(r),o.appendChild(a),o.appendChild(s),document.body.appendChild(o),V=o,fe=!0}function Lt(){V&&V.parentNode&&(V.parentNode.removeChild(V),V=null,fe=!1)}function Nt(){return fe}var V,fe,Je=L(()=>{"use strict";ue();j();de();V=null,fe=!1});var at={};Te(at,{FunnelClient:()=>ne,TrackingProvider:()=>et,findMethod:()=>it,getAssignedCheckoutOfferDefault:()=>Jt,getAssignedCheckoutOfferIds:()=>Wt,getAssignedOrderBumpOfferIds:()=>Ht,getAssignedPaymentFlowId:()=>rt,getAssignedPaymentInitiator:()=>jt,getAssignedPixels:()=>Vt,getAssignedResources:()=>st,getAssignedScripts:()=>Kt,getAssignedStaticResources:()=>Gt,getAssignedStepConfig:()=>k,getAssignedUpsellOfferIds:()=>qt,getEnabledMethods:()=>tt,getExpressMethods:()=>nt,getExpressMethodsByProcessor:()=>Ut,getLocalFunnelConfig:()=>ot,isMethodEnabled:()=>Ot,loadLocalFunnelConfig:()=>$t});function tt(t){return t?Object.values(t).filter(e=>e.enabled):[]}function nt(t){return tt(t).filter(e=>e.express)}function Ut(t){let e={};for(let n of nt(t)){let i=n.processorId||n.integrationId||n.provider;e[i]||(e[i]=[]),e[i].push(n)}return e}function it(t,e){if(t){for(let n of Object.values(t))if(n.method===e&&n.enabled)return n}}function Ot(t,e){return!!it(t,e)}function Mt(){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 ge(){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 te(){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 Xe(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 i of n)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 zt(){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 $t(){if(!zt())return null;if(E!==void 0)return E;if(Ae)return await new Promise(t=>setTimeout(t,100)),E!=null?E:null;Ae=!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)"),E=null,null;let e=await t.json();return console.log("\u{1F6E0}\uFE0F [SDK] \u2705 Loaded local funnel config:",e),E=e,e}catch(t){return console.log("\u{1F6E0}\uFE0F [SDK] funnel.local.json not available:",t),E=null,null}finally{Ae=!1}}function ot(){return E!=null?E:null}function Bt(t){let e=h(h({},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,checkoutOffers:t.checkoutOffers}}function k(){if(typeof window=="undefined")return;let t=ot();if(t)return console.log("\u{1F6E0}\uFE0F [SDK] Using local funnel.local.json (overrides injected)"),Bt(t);let e=window.__TGD_STEP_CONFIG__;if(e){let n=Xe(e);if(n)return n}if(typeof document!="undefined"){let n=document.querySelector('meta[name="x-step-config"]'),i=n==null?void 0:n.getAttribute("content");if(i){let o=Xe(i);if(o)return o}}}function rt(){var n,i;let t=k(),e=(n=t==null?void 0:t.paymentSetupConfig)==null?void 0:n.card;if(e!=null&&e.paymentFlowId)return e.paymentFlowId;if((i=t==null?void 0:t.payment)!=null&&i.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 o=document.querySelector('meta[name="x-payment-flow-id"]');return(o==null?void 0:o.getAttribute("content"))||void 0}}}function jt(){let t=k();return t==null?void 0:t.paymentInitiator}function st(){let t=k(),e=t==null?void 0:t.staticResources,n=t==null?void 0:t.resources;if(!(!e&&!n))return h(h({},e),n)}function Gt(){return st()}function Kt(t){let e=k();if(!(e!=null&&e.scripts))return;let n=e.scripts.filter(i=>i.enabled);return t&&(n=n.filter(i=>i.position===t||!i.position&&t==="head-end")),n.length>0?n:void 0}function Ze(t){return t?t.split(/[;,]/).map(e=>e.trim()).filter(e=>e.length>0):[]}function Qe(t){if("containerId"in t){let n=Ze(t.containerId);return n.length===0?[t]:n.map(i=>v(h({},t),{containerId:i}))}let e=Ze(t.pixelId);return e.length===0?[t]:e.map(n=>v(h({},t),{pixelId:n}))}function Vt(){let t=k(),e=t==null?void 0:t.pixels;if(!e||typeof e!="object")return;let n={};for(let[i,o]of Object.entries(e))o&&(Array.isArray(o)?n[i]=o.flatMap(r=>Qe(r)):typeof o=="object"&&(n[i]=Qe(o)));return Object.keys(n).length>0?n:void 0}function Ht(){let t=k();if(t!=null&&t.orderBumps&&t.orderBumps.mode==="custom")return t.orderBumps.enabledOfferIds}function qt(){let t=k();if(t!=null&&t.upsellOffers&&t.upsellOffers.mode==="custom")return t.upsellOffers.enabledUpsellIds}function Wt(){let t=k();if(t!=null&&t.checkoutOffers&&t.checkoutOffers.mode==="custom")return t.checkoutOffers.enabledOfferIds}function Jt(){var e;let t=k();return(e=t==null?void 0:t.checkoutOffers)==null?void 0:e.defaultOfferId}var Ye,et,E,Ae,ne,pe=L(()=>{"use strict";se();ze();ke();ue();de();Ye=()=>Promise.resolve().then(()=>(Je(),We)).then(t=>t.injectPreviewModeIndicator()),et=(r=>(r.FACEBOOK="facebook",r.TIKTOK="tiktok",r.SNAPCHAT="snapchat",r.PINTEREST="pinterest",r.GTM="gtm",r))(et||{});Ae=!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 n=new URLSearchParams(window.location.search).get("funnelSessionId");return n||Be()||null}resetInitialization(){this.initializationAttempted=!1,this.isInitializing=!1,this.updateState({context:null,isInitialized:!1})}async autoInitialize(e,n,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=Mt(),d=ge(),g=te(),l=U(),p=this.config.funnelId||c||a,f=this.config.stepId||g,u=typeof window!="undefined"?new URLSearchParams(window.location.search):null,w=u==null?void 0:u.get("funnelEnv");this.config.debugMode&&console.log("\u{1F680} [FunnelClient] Auto-initializing...",{existingSessionId:o,effectiveFunnelId:p,funnelVariantId:d,funnelStepId:f,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":g?"injected":"none"}});let m=await this.resource.initialize({cmsSession:{customerId:e.customerId,sessionId:e.sessionId,storeId:n.id,accountId:n.accountId},funnelId:p,existingSessionId:o||void 0,currentUrl:typeof window!="undefined"?window.location.href:void 0,funnelVariantId:d,funnelStepId:f,draft:l.draft,funnelTracking:l.funnelTracking,funnelEnv:w||void 0,tagadaClientEnv:l.tagadaClientEnv,tagadaClientBaseUrl:l.tagadaClientBaseUrl,currency:l.currency,locale:l.locale});if(m.success&&m.context){let I=this.enrichContext(m.context);return this.handleSessionSuccess(I),Ye(),I}else throw new Error(m.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,n,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:n.id,accountId:n.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),Ye(),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 i,o,r,s,a,c;if(n!=null&&n.waitForSession&&!((i=this.state.context)!=null&&i.sessionId)){this.config.debugMode&&console.log("\u23F3 [FunnelClient] Waiting for session before navigation...");let d=5e3,g=Date.now();for(;!((o=this.state.context)!=null&&o.sessionId)&&Date.now()-g<d;)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 d=ge(),g=te(),l=typeof window!="undefined"?window.location.href:void 0;!g&&this.config.stepId&&(g=this.config.stepId,this.config.debugMode&&console.log("\u{1F50D} [FunnelClient.navigate] Using stepId from config (no injection):",g)),!d&&this.config.variantId&&(d=this.config.variantId,this.config.debugMode&&console.log("\u{1F50D} [FunnelClient.navigate] Using variantId from config (no injection):",d)),this.config.debugMode&&console.log("\u{1F50D} [FunnelClient.navigate] Sending to backend:",{sessionId:this.state.context.sessionId,currentUrl:l,funnelStepId:g||"(not found)",funnelVariantId:d||"(not found)",hasInjectedStepId:!!te(),hasInjectedVariantId:!!ge(),usedConfigFallback:!te()&&!!this.config.stepId,customerTags:(n==null?void 0:n.customerTags)||"(none)",deviceId:(n==null?void 0:n.deviceId)||"(none)"});let p=(n==null?void 0:n.fireAndForget)||!1,f=await this.resource.navigate({sessionId:this.state.context.sessionId,event:e,currentUrl:l,funnelStepId:g,funnelVariantId:d,fireAndForget:p,customerTags:n==null?void 0:n.customerTags,deviceId:n==null?void 0:n.deviceId});if(!f.success||!f.result)throw new Error(f.error||"Navigation failed");let u=f.result;if(u.queued)return this.updateState({isNavigating:!1,isLoading:!1}),u.sessionId&&u.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(u.sessionId)),this.state.context&&(this.state.context.sessionId=u.sessionId)),this.config.debugMode&&console.log("\u{1F525} [FunnelClient] Navigation queued (fire-and-forget mode)"),u;let w=(n==null?void 0:n.autoRedirect)!==void 0?n.autoRedirect:this.config.autoRedirect!==!1;return this.updateState({isNavigating:!1,isLoading:!1}),w&&(u!=null&&u.url)&&typeof window!="undefined"&&(this.config.debugMode&&console.log("\u{1F680} [FunnelClient] Auto-redirecting to:",u.url,"(skipped session refresh - next page will initialize)"),window.location.replace(u.url)),u}catch(d){let g=d instanceof Error?d:new Error(String(d));throw this.updateState({error:g,isNavigating:!1,isLoading:!1}),g}}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 i=this.enrichContext(n.context);return this.updateState({context:i,sessionError:null}),i}}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 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){$e(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:v(h({},e),{static:h(h({},i),o)})}}});var Rn={};Te(Rn,{TRACKER_VERSION:()=>Fe,TagadaExternalTracker:()=>be,TagadaTracker:()=>vt});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"},N=class extends Error{constructor(e,n){var i;super(e),this.name="TagadaError",this.code=n.code,this.statusCode=n.statusCode,this.retryable=(i=n.retryable)!=null?i:!1,this.details=n.details,Object.setPrototypeOf(this,new.target.prototype)}},O=class extends N{constructor(e,n,i){var o,r;super(e,{code:(o=i==null?void 0:i.code)!=null?o:_.API_ERROR,statusCode:n,retryable:(r=i==null?void 0:i.retryable)!=null?r:n>=500,details:i==null?void 0:i.details}),this.name="TagadaApiError"}},me=class extends N{constructor(e="Network request failed"){super(e,{code:_.NETWORK_ERROR,retryable:!0}),this.name="TagadaNetworkError"}},he=class extends N{constructor(e="Authentication required",n=401){super(e,{code:_.AUTH_REQUIRED,statusCode:n,retryable:!1}),this.name="TagadaAuthError"}};var ye=class extends N{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,n){return this.request("GET",e,void 0,n)}async post(e,n,i){return this.request("POST",e,n,i)}async put(e,n,i){return this.request("PUT",e,n,i)}async patch(e,n,i){return this.request("PATCH",e,n,i)}async delete(e,n){return this.request("DELETE",e,void 0,n)}setHeader(e,n){this.defaultHeaders[e]=n}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,n,i,o){let r="".concat(e,":").concat(n);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(n);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,d=setTimeout(()=>c.abort(),this.timeout),g=o!=null&&o.signal?Yt([o.signal,c.signal]):c.signal;try{let l={method:e,headers:s,signal:g};i!==void 0&&(l.body=JSON.stringify(i));let p=await fetch(a,l);if(!p.ok){let u=await this.safeParseJson(p);throw this.toTagadaError(p.status,u,p.statusText)}return await p.json()}catch(l){throw l instanceof N?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(d)}}toTagadaError(e,n,i){var r,s,a;let o=(s=(r=n==null?void 0:n.message)!=null?r:n==null?void 0:n.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=n==null?void 0:n.code)!=null?a:_.API_ERROR,details:n,retryable:e>=500})}async safeParseJson(e){try{return await e.json()}catch(n){return}}checkRequestLimit(e){let n=Date.now(),i=this.requestHistory.get(e);if(!i){this.requestHistory.set(e,{count:1,firstRequestTime:n});return}if(n-i.firstRequestTime>this.WINDOW_MS){this.requestHistory.set(e,{count:1,firstRequestTime:n});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[n,i]of this.requestHistory.entries())e-i.firstRequestTime>this.WINDOW_MS&&this.requestHistory.delete(n)}};function Yt(t){let e=new AbortController;for(let n of t){if(n.aborted)return e.abort(n.reason),e.signal;n.addEventListener("abort",()=>e.abort(n.reason),{once:!0,signal:e.signal})}return e.signal}function Xt(){return{width:window.screen.width,height:window.screen.height}}function Zt(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){return"UTC"}}function lt(){try{return navigator.language||"en-US"}catch(t){return"en-US"}}var M=typeof navigator!="undefined"?navigator.userAgent:"";function R(t,...e){for(let n of e){let i=t.match(n);if(i)return i}return null}function Qt(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,i]of e){let o=t.match(n);if(o){let r=o[1]||"";return{name:i,version:r,major:r.split(".")[0]||""}}}return{name:"",version:"",major:""}}function en(t){let e=R(t,/Windows NT ([\d.]+)/i)||R(t,/Mac OS X ([\d_.]+)/i)||R(t,/Android ([\d.]+)/i)||R(t,/iPhone OS ([\d_]+)/i)||R(t,/iPad.*OS ([\d_]+)/i)||R(t,/CrOS[\w ]*\/([\d.]+)/i)||R(t,/Linux/i);if(!e)return{name:"",version:""};let n=e[0],i=(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"}[i]||i}:/Mac OS X/i.test(n)?{name:"macOS",version:i}:/Android/i.test(n)?{name:"Android",version:i}:/iPhone|iPad/i.test(n)?{name:"iOS",version:i}:/CrOS/i.test(n)?{name:"Chrome OS",version:i}:/Linux/i.test(n)?{name:"Linux",version:""}:{name:"",version:""}}function tn(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 nn(t){let e=R(t,/AppleWebKit\/([\d.]+)/i)||R(t,/Gecko\/([\d.]+)/i)||R(t,/Trident\/([\d.]+)/i)||R(t,/Presto\/([\d.]+)/i);if(!e)return{name:"",version:""};let n=e[0],i=e[1]||"";return/AppleWebKit/i.test(n)?{name:"WebKit",version:i}:/Gecko/i.test(n)?{name:"Gecko",version:i}:/Trident/i.test(n)?{name:"Trident",version:i}:/Presto/i.test(n)?{name:"Presto",version:i}:{name:"",version:""}}function on(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 rn(){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 sn(t){return/Chrome|Chromium|Edge|Brave|Opera|Vivaldi|Arc/i.test(t)}function an(){return window.matchMedia("(display-mode: standalone)").matches||navigator.standalone===!0}function ln(t){return/mac/i.test(t)?navigator.maxTouchPoints>0:!1}function ct(){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=Qt(M),e=en(M),n=tn(M),i=nn(M),o=on(M),r;try{r={isBot:rn(),isChromeFamily:sn(t.name),isStandalonePWA:an(),isAppleSilicon:ln(e.name)}}catch(s){r={isBot:!1,isChromeFamily:!1,isStandalonePWA:!1,isAppleSilicon:!1}}return{userAgent:{name:M,browser:t,os:e,device:n,engine:i,cpu:o},screenResolution:Xt(),timeZone:Zt(),flags:r}}function dt(){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,gclid:t.get("gclid")||void 0}}var Ie=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 i=Array.from(this.listeners.get(e));await Promise.all(i.map(o=>{try{return Promise.resolve(o(n))}catch(r){return console.error('[EventBus] Error in listener for event "'.concat(e,'":'),r),Promise.resolve()}}))}}clear(){this.listeners.clear()}};ke();function ie(t){try{let e=t.split(".");if(e.length!==3)return console.error("Invalid JWT token format"),null;let n=e[1],i=n+"=".repeat((4-n.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 ut(t){try{let e=t.split(".");if(e.length!==3)return!0;let n=e[1],i=n+"=".repeat((4-n.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={},cn=["","VITE_","REACT_APP_","NEXT_PUBLIC_"];function F(t,e=cn){var n,i,o;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 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 dn=async(t="default")=>{try{if((F("TAGADA_ENV")||F("TAGADA_ENVIRONMENT"))==="production"||!Y(!0))return null;let n=await fetch("/.local.json");if(!n.ok)return null;let i=await n.json(),o={},r=!1;try{let a=await fetch("/config/".concat(t,".tgd.json"));a.ok||(a=await fetch("/config/".concat(t,".json"))),a.ok&&(o=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&&(o=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: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}},un=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(),at));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 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}},we=t=>{if(typeof document=="undefined")return;let e=document.querySelector('meta[name="'.concat(t,'"]'));return(e==null?void 0:e.getAttribute("content"))||void 0},fn=()=>{if(typeof window!="undefined"&&window.__TAGADA_PLUGIN_CONFIG__)return window.__TAGADA_PLUGIN_CONFIG__;try{let t=we("x-plugin-config");if(t)return JSON.parse(decodeURIComponent(t))}catch(t){}return{}};var gn=async()=>{try{if(typeof document=="undefined")return null;let t=we("x-plugin-store-id"),e=we("x-plugin-account-id");if(!t)return null;let n=we("x-plugin-base-path")||"/",i=fn();e||console.warn("\u26A0\uFE0F Plugin config: Account ID not found in meta tags");let o={storeId:t,accountId:e,basePath:n,config:i};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(i),configSize:JSON.stringify(i).length}),o}catch(t){return console.warn("\u26A0\uFE0F Error loading production config from meta tags:",t),null}},ft=async(t="default",e)=>{var s,a;console.log("\u{1F527} [V2] loadPluginConfig called with variant:",t);let n=await un(),i=await gn();if(i){let c=v(h({},i),{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 o=await mn();if(o){let c=v(h({},o),{staticResources:n!=null?n:void 0});return console.log("\u2705 [V2] Using environment variables config (PRIORITY 3 - build time)"),c}let r=await dn(t);if(r){let c=v(h({},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 pn(t="default",e){try{if(!Y())return null;if(e)return e;let n=["/config/".concat(t,".config.json"),"/config/".concat(t,".tgd.json"),"/config/".concat(t,".json")];for(let i of n)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(t,"'")),null}catch(n){return console.error("[loadLocalConfig] Error loading config:",n),null}}async function mn(){try{if(!Y())return;let t=F("TAGADA_STORE_ID"),e=F("TAGADA_ACCOUNT_ID"),n=F("TAGADA_BASE_PATH"),i=F("TAGADA_CONFIG_NAME");if(!t||!e)return;let o=await pn(i);if(!o)return;let r={storeId:t,accountId:e,basePath:n||"/",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(t){console.error("[createRawPluginConfig] Error creating config:",t);return}}ue();j();j();var Pe=new Map,_e=new Set;function hn(){return typeof window=="undefined"?null:new URLSearchParams(window.location.search).get("authCode")}async function gt(t,e,n,i=!1){if(_e.has(t))throw i&&console.log("[AuthHandoff] Code already resolved, skipping duplicate request"),new Error("Auth code already resolved");let o=Pe.get(t);if(o)return i&&console.log("[AuthHandoff] Resolution already in progress, waiting for existing request"),o;i&&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 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),yn(i),_e.add(t),a}catch(s){throw console.error("[AuthHandoff] \u274C Failed to resolve:",s),s}finally{Pe.delete(t)}})();return Pe.set(t,r),r}function yn(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 pt(){let t=hn();return!(!t||!t.startsWith("ah_")||_e.has(t))}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,d,g;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 p=this.getAccountId(),u=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:p},u).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=Me(i);e.customApiConfig&&(o=v(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:(d=e.rawPluginConfig)==null?void 0:d.funnelId,stepId:(g=e.rawPluginConfig)==null?void 0:g.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 n=await ft(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(pt()){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 i=new URLSearchParams(window.location.search).get("authCode");if(!i)return this.fallbackToNormalFlow();let o=await gt(i,n,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 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),x(n));let i=X();console.log("[TagadaClient ".concat(this.instanceId,"] Initializing token (normal flow)..."),{hasExistingToken:!!i,hasQueryToken:!!n,storeId:this.state.pluginConfig.storeId});let o=null,r=!1;if(n?(o=n,r=!0):i&&!ut(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 n=ee();this.state.debugMode&&console.log("[TagadaClient] Creating anonymous token for store:",e,{draft:n});let i=await this.apiClient.post("/api/v1/cms/session/anonymous",{storeId:e,role:"anonymous",draft:n},{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(n){console.error("[TagadaClient] Failed to create anonymous token:",n),this.updateState({isInitialized:!0,isLoading:!1})}}async initializeSession(e){var n,i,o,r,s,a,c,d,g,l,p;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 f=await ct(),u=dt(),w=lt(),m=ee(),I=new URLSearchParams(window.location.search).get("draft");I!==null&&Ee(I==="true");let A={storeId:e.storeId,accountId:e.accountId,customerId:e.customerId,role:e.role,browserLocale:w,queryLocale:u.locale,queryCurrency:u.currency,utmSource:u.utmSource,utmMedium:u.utmMedium,utmCampaign:u.utmCampaign,gclid:u.gclid,browser:f.userAgent.browser.name,browserVersion:f.userAgent.browser.version,os:f.userAgent.os.name,osVersion:f.userAgent.os.version,deviceType:(n=f.userAgent.device)==null?void 0:n.type,deviceModel:(i=f.userAgent.device)==null?void 0:i.model,deviceVendor:(o=f.userAgent.device)==null?void 0:o.vendor,userAgent:f.userAgent.name,engineName:f.userAgent.engine.name,engineVersion:f.userAgent.engine.version,cpuArchitecture:f.userAgent.cpu.architecture,isBot:(s=(r=f.flags)==null?void 0:r.isBot)!=null?s:!1,isChromeFamily:(c=(a=f.flags)==null?void 0:a.isChromeFamily)!=null?c:!1,isStandalonePWA:(g=(d=f.flags)==null?void 0:d.isStandalonePWA)!=null?g:!1,isAppleSilicon:(p=(l=f.flags)==null?void 0:l.isAppleSilicon)!=null?p:!1,screenWidth:f.screenResolution.width,screenHeight:f.screenResolution.height,timeZone:f.timeZone,draft:m,fetchMessages:!1},y=await this.apiClient.post("/api/v1/cms/session/v2/init",A);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(f){this.lastSessionInitError=f,this.sessionInitRetryCount++,console.error("[TagadaClient] Error initializing session (attempt ".concat(this.sessionInitRetryCount,"/").concat(this.MAX_SESSION_INIT_RETRIES,"):"),f),this.updateState({isInitialized:!0,isLoading:!1})}finally{this.isInitializingSession=!1}}updateSessionState(e,n){var s,a,c,d,g,l,p,f,u,w;if(e.store){let m=e.store,I=v(h({},e.store),{accountId:m.accountId||((s=this.state.pluginConfig)==null?void 0:s.accountId)||n.accountId||"",presentmentCurrencies:m.presentmentCurrencies||[e.store.currency||"USD"],chargeCurrencies:m.chargeCurrencies||[e.store.currency||"USD"]});this.updateState({store:I})}if(e.locale){let m={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:m})}if(e.store){let m={code:e.store.currency,symbol:this.getCurrencySymbol(e.store.currency),name:this.getCurrencyName(e.store.currency)};this.updateState({currency:m})}let i={isAuthenticated:(g=(d=e.customer)==null?void 0:d.isAuthenticated)!=null?g:!1,isLoading:!1,customer:(l=e.customer)!=null?l:null,session:n};this.updateState({customer:(p=e.customer)!=null?p:null,auth:i});let o=(f=this.config.features)==null?void 0:f.funnel,r=typeof o=="object"&&o.skipAutoInit;if(this.funnel&&!r&&n.customerId&&((u=e.store)!=null&&u.id)){let m=e.store.accountId||((w=this.state.pluginConfig)==null?void 0:w.accountId)||n.accountId||"";if(m){let A=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:m,funnelId:A||"auto-detect"}),this.funnel.autoInitialize({customerId:n.customerId,sessionId:n.sessionId},{id:e.store.id,accountId:m},A).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,n,i;return((e=this.state.store)==null?void 0:e.accountId)||((n=this.state.pluginConfig)==null?void 0:n.accountId)||((i=this.state.session)==null?void 0:i.accountId)||""}updatePluginConfig(e){this.state.debugMode&&console.log("[TagadaClient] Hot-reloading config:",e);let n=h(h({},this.state.pluginConfig.config),e);this.updateState({pluginConfig:v(h({},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 i,o;if(((i=n.data)==null?void 0:i.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(((o=n.data)==null?void 0:o.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 i="tagada-editor-highlight",o=document.getElementById(i);o&&o.remove();let r=l=>{var y;let f=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]).has(l.tagName.toLowerCase()),u=l;if(f){let T=l.parentElement;if((T==null?void 0:T.getAttribute("data-tagada-highlight-wrapper"))==="true"&&T instanceof HTMLElement)u=T;else{let S=document.createElement("div");S.setAttribute("data-tagada-highlight-wrapper","true");let oe=window.getComputedStyle(l),z=oe.display;if(z==="inline"?S.style.display="inline-block":S.style.display=z,S.style.position="relative",z==="inline"||z.includes("inline")){let D=oe.verticalAlign;D&&D!=="baseline"&&(S.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(),P=oe.getPropertyValue(W);P&&P.trim()!==""&&(D==="flex"&&P!=="none"&&P!=="0 1 auto"?S.style.flex=P:D==="boxSizing"?S.style.boxSizing=P:S.style.setProperty(W,P))}),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 P=l.style.getPropertyValue(W);P&&S.style.setProperty(W,P)}),(y=l.parentNode)==null||y.insertBefore(S,l),S.appendChild(l),u=S}}let w=getComputedStyle(f?l:u);(u.style.position==="static"||!u.style.position)&&(u.style.position="relative");let m=document.createElement("div");m.id=i,m.style.position="absolute",m.style.inset="0",m.style.pointerEvents="none",m.style.zIndex="9999",m.style.boxSizing="border-box",m.style.background="none",m.style.border="none",m.style.outline="none",m.style.margin="0",m.style.padding="0";let I=w.borderRadius;I&&(m.style.borderRadius=I),u.appendChild(m);let A=n||{boxShadow:"0 0 0 2px rgb(239 68 68)"};if(Object.entries(A).forEach(([T,q])=>{let S=T.includes("-")?T.replace(/-([a-z])/g,(oe,z)=>z.toUpperCase()):T;T.includes("-")?m.style.setProperty(T,q):m.style[S]=q}),l.scrollIntoView({behavior:"smooth",block:"center"}),this.state.debugMode){let T=Object.entries(A).map(([q,S])=>"".concat(q,": ").concat(S)).join("; ");console.log("[TagadaClient] Applied styles to highlight div of element #".concat(e,":"),T)}},s=5,a=1e3,c=0,d=l=>{let p=window.getComputedStyle(l);return p.display==="none"||p.visibility==="hidden"||p.opacity==="0"||l.hidden||l.offsetWidth===0||l.offsetHeight===0},g=()=>{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(g,a);return}let p=null;if(l.length===1)p=l[0];else{for(let f=0;f<l.length;f++)if(!d(l[f])){p=l[f];break}p||(p=l[0])}p&&r(p)};g()}};pe();var Cn=Object.freeze(["cf_click_id","cid","rtkclickid","cmc_tid","cmc_id","cmcid","clickid","click_id","gclid","gbraid","wbraid","fbclid","msclkid","ttclid","twclid","li_fat_id","epik","dclid","yclid","irclickid"]),In=Object.freeze(["cf_click_id","cfclid","rtkclickid-store","_rtkclickid","rtkclickid","_voluum","_voluumclickid","_binom","_binomclickid","_mck","cmcid","skro-click-id","click_id"]);function wn(t){if(typeof document=="undefined"||!document.cookie)return null;let e=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));if(!n)return null;try{return decodeURIComponent(n[1])}catch(i){return n[1]}}function vn(t,e){if(!t)return null;try{return new URLSearchParams(t).get(e)}catch(n){return null}}function Sn(){var r,s;let t={},e=null,n=null,i=null,o=typeof window!="undefined"&&(s=(r=window.location)==null?void 0:r.search)!=null?s:"";for(let a of Cn){let c=vn(o,a);c&&(t["url:".concat(a)]=c,e===null&&(e=c,n="url",i=a))}for(let a of In){let c=wn(a);c&&(t["cookie:".concat(a)]=c,e===null&&(e=c,n="cookie",i=a))}return{clickId:e,source:n,key:i,all:t}}function mt(){var n;if(typeof window=="undefined")return null;let t=Sn(),e=v(h({},t),{resolvedAt:Date.now()});return window.TagadaPay=v(h({},(n=window.TagadaPay)!=null?n:{}),{tracking:e}),e}function bn(){if(typeof window=="undefined"||typeof document=="undefined")return[];let t=k();return t!=null&&t.scripts?t.scripts.filter(e=>e.enabled):[]}function ht(t){return!t||/^<!--[\s\S]*?-->$/.test(t)?null:/^</.test(t)||/<\/?[a-zA-Z][\w-]*[\s/>]/.test(t)?{type:"html",html:t}:{type:"inline",code:t}}function Tn(t){let e=t.trim();if(!/<(?:script|noscript)[\s>]/i.test(e))return e?[{type:"inline",code:e}]:[];let n=[],i=/<(script|noscript)([^>]*)>([\s\S]*?)<\/\1>/gi,o=0,r;for(;(r=i.exec(e))!==null;){let a=ht(e.slice(o,r.index).trim());a&&n.push(a);let[,c,d,g]=r;if(c.toLowerCase()==="noscript")g.trim()&&n.push({type:"noscript",html:g.trim()});else{let l=d.match(/src=["']([^"']+)["']/i);l&&n.push({type:"external",src:l[1],async:/\basync\b/i.test(d),defer:/\bdefer\b/i.test(d)}),g.trim()&&n.push({type:"inline",code:g.trim()})}o=r.index+r[0].length}let s=ht(e.slice(o).trim());return s&&n.push(s),n}function Se(t,e){switch(e){case"head-start":document.head.firstChild?document.head.insertBefore(t,document.head.firstChild):document.head.appendChild(t);break;case"head-end":document.head.appendChild(t);break;case"body-start":document.body.firstChild?document.body.insertBefore(t,document.body.firstChild):document.body.appendChild(t);break;case"body-end":default:document.body.appendChild(t);break}}function kn(t,e){let n=t.position||"body-end",i=t.content.trim();i&&(document.querySelector('[data-tagada-stepconfig-index="'.concat(e,'"]'))||Tn(i).forEach((o,r)=>{let s="tagada-stepconfig-script-".concat(e,"-").concat(r);if(o.type==="external"){let a=document.createElement("script");a.id=s,a.setAttribute("data-tagada-stepconfig-script","true"),a.setAttribute("data-tagada-stepconfig-index",String(e)),a.setAttribute("data-script-name",t.name),a.src=o.src,o.async&&(a.async=!0),o.defer&&(a.defer=!0),Se(a,n)}else if(o.type==="inline"){let a=document.createElement("script");a.id=s,a.setAttribute("data-tagada-stepconfig-script","true"),a.setAttribute("data-tagada-stepconfig-index",String(e)),a.setAttribute("data-script-name",t.name),a.textContent="(function() {\n try {\n // Script: "+t.name+"\n"+o.code+'\n } catch (error) {\n console.error("[TagadaPay] StepConfig script error:", error);\n }\n})();',Se(a,n)}else if(o.type==="noscript"){let a=document.createElement("noscript");a.id=s,a.setAttribute("data-tagada-stepconfig-script","true"),a.setAttribute("data-tagada-stepconfig-index",String(e)),a.innerHTML=o.html,Se(a,n)}else if(o.type==="html"){let a=document.createElement("template");a.innerHTML=o.html,Array.from(a.content.childNodes).forEach(c=>{if(c.nodeType!==1)return;let d=c;d.setAttribute("data-tagada-stepconfig-script","true"),d.setAttribute("data-tagada-stepconfig-index",String(e)),d.setAttribute("data-script-name",t.name),Se(d,n)})}}))}function yt(){let t=bn();t.length!==0&&t.forEach((e,n)=>{kn(e,n)})}if(typeof window!="undefined"&&typeof document!="undefined"){try{mt()}catch(e){console.error("[TagadaPay] Failed to publish tracking global:",e)}let t=()=>{document.body?yt():document.addEventListener("DOMContentLoaded",yt,{once:!0})};"requestIdleCallback"in window?window.requestIdleCallback(t,{timeout:100}):setTimeout(t,0)}function Ct(t={}){return new ve(t)}j();var Fe="1.0.0";function It(t){return typeof window=="undefined"?null:new URLSearchParams(window.location.search).get(t)}function b(t,...e){t&&console.log("[TagadaTracker]",...e)}function wt(...t){console.warn("[TagadaTracker]",...t)}function xn(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 En(t,e,n){let i;for(let o=0;o<=e;o++)try{return await t()}catch(r){if(i=r instanceof Error?r:new Error(String(r)),o<e){let s=Math.min(1e3*2**o,8e3);b(n,"Retry ".concat(o+1,"/").concat(e," in ").concat(s,"ms...")),await new Promise(a=>setTimeout(a,s))}}throw i}var be=class{constructor(){this.config=null;this.client=null;this.initialized=!1;this.initializing=!1;this.unsubscribe=null;this.version=Fe}async init(e){var i,o;if(this.initialized)return b(e.debug||!1,"Already initialized \u2014 returning existing session."),this.getSession();if(this.initializing)return b(e.debug||!1,"Initialization in progress \u2014 skipping duplicate call."),null;this.initializing=!0,this.config=h({debug:!1},e);let n=this.config.debug;try{xn(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}b(n,"\u{1F680} Initializing external tracker v".concat(Fe),{storeId:e.storeId,accountId:e.accountId,stepId:e.stepId,funnelId:e.funnelId});try{let r=It("token");r&&(x(r),b(n,"\u{1F511} Bootstrapped token from URL")),this.client=Ct({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 En(()=>this.initializeFunnel(),2,n);b(n,"\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(b(n,"\u274C Initialization failed:",s),this.config.onError)return this.config.onError(s),null;throw s}finally{this.initializing=!1}}getSession(){var n,i;if(!((i=(n=this.client)==null?void 0:n.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,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.");b(this.config.debug,"\u{1F680} Navigating:",e);let n=e.autoRedirect!==!1;try{let i=await this.client.funnel.navigate({type:e.eventType,data:e.eventData||{}},{autoRedirect:!1});return i!=null&&i.url?(b(this.config.debug,"\u2705 Navigation result:",i.url),n&&typeof window!="undefined"&&(window.location.href=e.returnUrl||i.url),{url:i.url}):null}catch(i){throw b(this.config.debug,"\u274C Navigation failed:",i),i}}async trackEvent(e){if(!this.isReady()){wt("trackEvent called before init \u2014 event dropped:",e.name);return}b(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){b(this.config.debug,"\u26A0\uFE0F Event tracking failed (non-critical):",e.name)}}getCustomerId(){var e,n,i,o,r;return((n=(e=this.client)==null?void 0:e.state.auth.customer)==null?void 0:n.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,n,i;return((i=(n=(e=this.client)==null?void 0:e.funnel)==null?void 0:n.state.context)==null?void 0:i.sessionId)||null}buildUrl(e,n){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),n&&Object.entries(n).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.");b(this.config.debug,"\u{1F504} Resetting to step:",e),this.config.stepId=e;let n=await this.initializeFunnel(),i=this.getSession();return i&&((r=(o=this.config).onReady)==null||r.call(o,i)),i}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,b(!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 n=!1,i=setTimeout(()=>{var r;n||(n=!0,b(((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(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,n=(c=this.client.state.auth.session)==null?void 0:c.sessionId;!e&&!n&&wt("No auth session available \u2014 funnel init may fail.");let i={customerId:e||"anon_placeholder",sessionId:n||"sess_placeholder"},o={id:this.config.storeId,accountId:this.config.accountId},r=this.config.stepId;return b(this.config.debug,"\u{1F50D} Initializing funnel at step:",r),this.client.funnel.initialize(i,o,this.config.funnelId||It("funnelId")||void 0,r)}},vt=new be;typeof window!="undefined"&&(window.TagadaTracker=vt);return Rt(Rn);})();
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;