"use strict";(()=>{var gt=Object.defineProperty;var te=(o,t,e)=>t in o?gt(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var j=(o,t)=>()=>(o&&(t=o(o=0)),t);var ee=(o,t)=>{for(var e in t)gt(o,e,{get:t[e],enumerable:!0})};var E=(o,t,e)=>te(o,typeof t!="symbol"?t+"":t,e);function Ct(o){if(typeof document>"u")return null;let t=document.getElementById(o);if(!t?.textContent?.trim())return null;try{return JSON.parse(t.textContent)}catch{return null}}function k(){let o=Ct("moonbundle-store-config");return o?{storefrontToken:o["storefront-token"]??o.storefrontToken??"",shopConfig:o["shop-config"]??o.shopConfig??{},currentMarketId:o["current-market-id"]??o.currentMarketId??""}:null}function q(){let o=Ct("moonbundle-global-custom");return o?{globalCustomCss:o["global-custom-css"]??o.globalCustomCss??"",globalCustomJs:o["global-custom-js"]??o.globalCustomJs??""}:null}var H=j(()=>{"use strict"});function Pt(o,t={}){return Array.isArray(o)?t.preview??b()?.enabled===!0?o.filter(n=>n?.status!=="archived"&&n?.status!=="deleted"):o.filter(n=>{let r=n?.status;return!r||r==="published"}):[]}var Tt=j(()=>{"use strict";M()});var kt={};ee(kt,{getCachedBundleConfig:()=>W,mergeBundleMetafieldChunks:()=>Et,parseExtensionConfigurationMetafield:()=>At,resetCachedBundleConfigForTests:()=>he,resolveBundleConfig:()=>T,seedCachedBundleConfigFromInlineDom:()=>nt});function le(o){return o===0?"extension_configuration":`extension_configuration_${o+1}`}function At(o){if(!o||o==="[]")return[];try{let t=JSON.parse(o);return Array.isArray(t)?t.filter(Boolean):[]}catch{return[]}}function Et(o){let t=new Map;for(let n of o||[])n?.key&&t.set(n.key,n.value);let e=[];for(let{key:n}of It){let r=t.get(n);r&&e.push(...At(r))}return e}function de(){return`query MoonbundleExtensionConfigs { shop { metafields(identifiers: [${It.map(({namespace:t,key:e})=>`{namespace: "${t}", key: "${e}"}`).join(", ")}]) { namespace key value } } }`}async function fe(o){let t=await fetch(`/api/${ue}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":o},body:JSON.stringify({query:de()})});if(!t.ok)return console.warn("[MoonBundle] Storefront metafield fetch failed:",t.status),[];let e=await t.json();return e.errors?.length&&console.warn("[MoonBundle] Storefront metafield GraphQL errors:",e.errors),Et(e.data?.shop?.metafields)}function pe(){if(typeof document>"u")return null;let o=document.getElementById("moonbundle-bundle-config");if(!o?.textContent?.trim())return null;try{return JSON.parse(o.textContent)}catch{return null}}function W(){return w}function me(o){return w||(w=o,w)}function he(){w=null,F=null}function ge(){if(typeof document>"u")return[];let o=new Map;for(let t of document.querySelectorAll("moonbundle-component")){let e=t.getAttribute("bundle");if(e)try{let n=JSON.parse(e);n?.id&&o.set(n.id,n)}catch{}}return[...o.values()]}function nt(){let o=ge();if(!o.length)return null;let t=k(),e=q();return me({bundles:o,storefrontToken:t?.storefrontToken??"",shopConfig:t?.shopConfig??{},currentMarketId:t?.currentMarketId??"",globalBundleCustom:{globalCustomCss:e?.globalCustomCss??"",globalCustomJs:e?.globalCustomJs??""}})}async function T(){if(w)return w;if(F)return F;F=(async()=>{let o=k(),t=q();if(!o?.storefrontToken){let n=pe();return n?(w=n,w):null}return w={bundles:Pt(await fe(o.storefrontToken)),storefrontToken:o.storefrontToken,shopConfig:o.shopConfig??{},currentMarketId:o.currentMarketId??"",globalBundleCustom:{globalCustomCss:t?.globalCustomCss??"",globalCustomJs:t?.globalCustomJs??""}},w})();try{return await F}finally{F=null}}var ce,It,ue,w,F,L=j(()=>{"use strict";H();Tt();ce="$app:moonbundle_bundles";It=[0,1,2,3,4].map(o=>({namespace:ce,key:le(o)})),ue="2026-04",w=null,F=null});function b(o){let t;if(typeof o=="string")t=new URLSearchParams(o.startsWith("?")?o.slice(1):o);else if(o instanceof URLSearchParams)t=o;else if(typeof window<"u")t=new URLSearchParams(window.location.search);else return null;if(t.get(rt.PREVIEW)!=="1")return null;let e=t.get(rt.BUNDLE_ID)?.trim();if(!e)return null;let n=t.get(rt.VISITOR_ID)?.trim()||void 0;return{enabled:!0,bundleId:e,visitorId:n}}async function Mt(o){if(typeof document>"u"||!o)return null;let{resolveBundleConfig:t}=await Promise.resolve().then(()=>(L(),kt));return(await t())?.bundles?.find(n=>n.id===o)??null}function ye(o){if(!o||typeof document>"u")return!1;for(let t of document.querySelectorAll("moonbundle-component")){let e=t.getAttribute("bundle");if(e)try{if(JSON.parse(e).id===o)return!0}catch{}}return!1}function Ft(o){if(!o||typeof document>"u"||ye(o))return!1;let t=it();return!(t&&document.querySelector(`moonbundle-component[data-moonbundle-block="true"][data-moonbundle-product-id="${t}"]`))}function it(){if(typeof document>"u")return null;let o=window.ShopifyAnalytics?.meta?.product?.id;if(o!=null)return String(o);let t=window.meta?.product?.id;if(t!=null)return String(t);let e=document.querySelector('form[action*="/cart/add"] [name="product-id"]');return e?.value?String(e.value):null}var rt,M=j(()=>{"use strict";rt={PREVIEW:"moonbundle_preview",BUNDLE_ID:"moonbundle_bundle_id",VISITOR_ID:"moonbundle_visitor_id"}});function h(o){return o?.toString()?.includes("gid://shopify")?o?.split("/")?.pop()?.toString():o?.toString()}function D(o){let t=Number(h(o));return Number.isFinite(t)?t:0}function J(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let t=Math.random()*16|0;return(o==="x"?t:t&3|8).toString(16)})}function et(o,t){if(o?.slotType!=="fixed"||!o.product)return!1;let e=o.product;if(e.id==="previewProduct")return!0;let n=h(e.id);return!!(n&&n===t)}function ne(o,t){if(!o?.variants?.length||t==null)return!1;let e=h(t);return o.variants.some(n=>h(n.id)===e)}function yt({customProperties:o,isSlotKeyedOffer:t,lineKey:e,variantId:n,mainProduct:r,selectedOffer:i}){if(!o||!Object.keys(o).length)return!1;if(t&&i?.multiProduct?.slots?.length){let s=h(r?.id),a=i.multiProduct.slots.find(l=>l?.id!=null&&String(l.id)===String(e));if(a&&et(a,s))return!0}return ne(r,n)}var z="MoonBundle",re="__moonbundleLoadBundleBlockAssets";function bt({getValue:o,intervalMs:t,timeoutMs:e,isCancelled:n,onFirstMiss:r,schedule:i,now:s,timeoutMessage:a}){return new Promise((l,c)=>{let u=s(),d=!1,f=()=>{if(n()){c(Object.assign(new Error("cancelled"),{code:"cancelled"}));return}let y=o();if(y){l(y);return}if(!d&&(d=!0,r))try{r()}catch{}if(s()-u>=e){c(Object.assign(new Error(a),{code:"timeout"}));return}i(f,t)};f()})}function _t(o={}){let t=o.getMount??(()=>typeof window<"u"?window[z]:void 0),e=o.loadBlockAssets??(()=>{if(typeof window>"u")return;let n=window[re];if(typeof n=="function")return n()});return bt({getValue:()=>{let n=t();return typeof n=="function"?n:void 0},intervalMs:o.intervalMs??100,timeoutMs:o.timeoutMs??6e4,isCancelled:o.isCancelled??(()=>!1),onFirstMiss:e,schedule:o.schedule??((n,r)=>setTimeout(n,r)),now:o.now??(()=>Date.now()),timeoutMessage:"Svelte mount function not found. Ensure moonbundle-block JS is loaded."})}function St(o,t={}){let e=t.getEntry??(()=>typeof window<"u"&&window[z]&&window[z][o]?window[z][o]:void 0);return bt({getValue:e,intervalMs:t.intervalMs??100,timeoutMs:t.timeoutMs??6e4,isCancelled:t.isCancelled??(()=>!1),onFirstMiss:null,schedule:t.schedule??((n,r)=>setTimeout(n,r)),now:t.now??(()=>Date.now()),timeoutMessage:`MoonBundle instance stores never registered for "${o}".`})}function ie(o,t="EN"){if(!o||typeof o!="string")return t;let e=o.trim().replace(/_/g,"-").toLowerCase();if(!e)return t;let[n,r]=e.split("-");return n?n==="pt"&&r==="br"?"PT_BR":n==="pt"&&r==="pt"?"PT_PT":n==="zh"&&r==="cn"?"ZH_CN":n==="zh"&&r==="tw"?"ZH_TW":n.toUpperCase():t}function G(o="EN"){let t=typeof window<"u"?window.Shopify?.locale:void 0;return ie(t,o)}function wt(o,t){if(!t||!o?.sellingPlanGroups||!Array.isArray(o.sellingPlanGroups))return!1;for(let e of o.sellingPlanGroups)if(e?.sellingPlans&&Array.isArray(e.sellingPlans)&&e.sellingPlans.some(r=>h(r?.id)===h(t)))return!0;return!1}function oe(o){let t=0;for(let e=0;en.find(a=>a.type===s)?.value??"",i=s=>String(s).padStart(2,"0");return`${r("year")}-${i(r("month"))}-${i(r("day"))}T${i(r("hour"))}:${i(r("minute"))}:00`}function ot(o=new Date,t="UTC"){return{[be]:_e(o,t)}}function Dt(o){return o?(o.recurring?.length??0)>0||o.dateRange!=null:!1}function st(o){return!o?.bundles?.length||!o.bundles.some(e=>Dt(e.schedule))?null:{shopTimezone:Q(o.shopConfig?.ianaTimezone)}}function qt(){let o=st(W());return o?ot(new Date,o.shopTimezone):null}async function Se(o){let t=ot(new Date,o.shopTimezone);try{let e=await fetch(Bt("/cart/update.js"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({attributes:t})});e.ok||console.warn("[MoonBundle] Schedule cart sync failed:",e.status)}catch(e){console.warn("[MoonBundle] Schedule cart sync error:",e)}}async function Lt(o){if(b()?.enabled)return;let t=o??W(),e=st(t);!e&&o==null&&k()?.storefrontToken&&(t=await T(),e=st(t)),e&&await Se(e)}M();var X="moonbundle-storefront-preview-notice",Nt="moonbundle-storefront-preview-notice-styles",$t="moonbundle_preview_notice_dismissed",Rt={en:{title:"Preview",body:"This is a preview: this bundle is not published and is not visible to your store visitors. Discounts are not applied to the cart so as not to affect live store traffic.",dismiss:"Got it"},fr:{title:"Pr\xE9visualisation",body:"Ceci est une pr\xE9visualisation : ce bundle n'est pas publi\xE9 et n'est pas visible par les visiteurs de votre boutique. Les remises ne sont pas appliqu\xE9es au panier afin de ne pas perturber le trafic live.",dismiss:"Compris"}};function we(){let o=G()?.slice(0,2).toLowerCase();return Rt[o]??Rt.en}function ve(){if(typeof document>"u"||document.getElementById(Nt))return;let o=document.createElement("style");o.id=Nt,o.textContent=` .moonbundle-storefront-preview-notice { position: fixed; inset: 0; z-index: 2147483645; display: flex; align-items: center; justify-content: center; padding: 16px; background: rgba(0, 0, 0, 0.45); } .moonbundle-storefront-preview-notice__dialog { width: min(100%, 420px); padding: 24px; border-radius: 12px; background: #fff; color: #1a1a1a; box-shadow: 0 16px 48px rgba(0, 0, 0, 0.2); font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; } .moonbundle-storefront-preview-notice__title { margin: 0 0 12px; font-size: 18px; font-weight: 600; line-height: 1.3; } .moonbundle-storefront-preview-notice__body { margin: 0 0 20px; font-size: 14px; line-height: 1.5; color: #444; } .moonbundle-storefront-preview-notice__actions { display: flex; justify-content: flex-end; } .moonbundle-storefront-preview-notice__button { border: 0; border-radius: 8px; padding: 10px 16px; background: #1a1a1a; color: #fff; font-size: 14px; font-weight: 500; cursor: pointer; } .moonbundle-storefront-preview-notice__button:hover { background: #333; } `,document.head.appendChild(o)}function Ut(o){try{sessionStorage.setItem($t,"1")}catch{}o.remove()}function Vt(){if(typeof document>"u"||!b()?.enabled||document.getElementById(X))return;try{if(sessionStorage.getItem($t)==="1")return}catch{}let o=we();ve();let t=document.createElement("div");t.id=X,t.className="moonbundle-storefront-preview-notice",t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-labelledby",`${X}-title`),t.innerHTML=`

`,t.querySelector(".moonbundle-storefront-preview-notice__title").textContent=o.title,t.querySelector(".moonbundle-storefront-preview-notice__body").textContent=o.body;let e=t.querySelector(".moonbundle-storefront-preview-notice__button");e.textContent=o.dismiss,e.addEventListener("click",()=>Ut(t)),t.addEventListener("click",n=>{n.target===t&&Ut(t)}),document.body.appendChild(t),e.focus()}function Ce(){if(b()?.enabled)return"preview";if(typeof document>"u")return"idle";let o=[...document.querySelectorAll("moonbundle-component")];return o.some(n=>n.getAttribute("main-product")&&n.getAttribute("bundle"))?"inline":o.some(n=>n.getAttribute("data-moonbundle-product-id")&&!n.getAttribute("main-product"))?"deferred":document.getElementById("moonbundle-bundle-config")?"legacy":"idle"}function Pe(o,t=3e3){typeof window>"u"||("requestIdleCallback"in window?requestIdleCallback(o,{timeout:t}):setTimeout(o,0))}var jt=!1;function Jt(){return!!document.querySelector("moonbundle-component[data-moonbundle-product-id]:not([main-product])")}function zt(){return T()}function Te(){if(jt||typeof document>"u")return;if(jt=!0,Jt()){zt().catch(()=>{});return}let o=new MutationObserver(()=>{Jt()&&(o.disconnect(),zt().catch(()=>{}))});o.observe(document.documentElement,{childList:!0,subtree:!0}),window.setTimeout(()=>o.disconnect(),3e4)}function at(o){Pe(()=>{Lt(o).catch(()=>{})})}async function Gt(){let o=b();if(!o?.enabled||!o.bundleId||!Ft(o.bundleId)||!await Mt(o.bundleId))return;let e=it();if(!e)return;let n=document.createElement("moonbundle-component");n.setAttribute("data-moonbundle-product-id",e),n.setAttribute("data-moonbundle-preview-bootstrap","true"),document.body.appendChild(n)}async function Ie(o=()=>{}){let t=Ce();if(Te(),t==="preview"){try{let e=await T();at(e),await Gt()}catch(e){console.warn("[MoonBundle] Bundle config resolve failed:",e),await Gt().catch(n=>{console.error("[MoonBundle] Preview bootstrap failed:",n)})}return}if(t==="inline"){let e=nt();at(e);return}if(t==="deferred"||t==="legacy"){T().then(e=>at(e)).catch(()=>{});return}}function Ht(o={}){let t=o.removeInstance??(()=>{});Vt(),queueMicrotask(()=>{Ie(t).catch(()=>{})})}H();function ct(o){let[t,e]=o.split(":").map(Number);return t*60+e}function Ae(o,t){let n=new Intl.DateTimeFormat("en-US",{timeZone:t,weekday:"short",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(o),r=s=>n.find(a=>a.type===s)?.value??"";return{dayOfWeek:{Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6}[r("weekday")]??0,minutes:ct(`${r("hour")}:${r("minute")}`)}}function Ee(o,t){let e=o.dateRange;if(!e)return!1;let n=t.getTime(),r=Date.parse(e.start);if(Number.isNaN(r)||n{if(!s.days?.includes(r))return!1;let a=ct(s.startTime),l=ct(s.endTime);return i>=a&&is.id===t);if(r!="none"&&i>=0){let s=r.split(",");n=new Function("a","b",`return b ${s[0]} a;`)(s[1],i+1)}return n}var Y=class{constructor(t){this.visitorId=t,this.activeTimers=new Map,this.loadPersistedTimers(),this.setupPersistence()}loadPersistedTimers(){try{let t=`moonbundle_timers_${this.visitorId}`,e=localStorage.getItem(t);if(e){let n=JSON.parse(e),r=Date.now();Object.entries(n).forEach(([i,s])=>{r-s.lastUpdate>10080*60*1e3||!s.config?delete n[i]:this.activeTimers.set(i,s)}),localStorage.setItem(t,JSON.stringify(Object.fromEntries(this.activeTimers)))}}catch(t){console.warn("Failed to load persisted timers:",t)}}persistTimers(){try{let t=`moonbundle_timers_${this.visitorId}`,e={};this.activeTimers.forEach((n,r)=>{e[r]={...n,lastUpdate:Date.now()}}),localStorage.setItem(t,JSON.stringify(e))}catch(t){console.warn("Failed to persist timers:",t)}}setupPersistence(){window.addEventListener("beforeunload",()=>{this.persistTimers()}),setInterval(()=>{this.persistTimers()},1e3)}startTimer(t,e,n){let r=`${t}_${e}`,i=this.activeTimers.get(r);return i?(!i.config||this.hasConfigChanged(i.config,n)||this.hasModeChanged(i.mode,n.mode))&&(i.mode=n.mode||"duration",i.config={days:n.days||0,hours:n.hours||0,minutes:n.minutes||0,seconds:n.seconds||0,customEndDate:n.customEndDate||null,repeat:n.repeat||!1},i.startTime=Date.now(),i.lastUpdate=Date.now()):(i={bundleId:t,offerId:e,mode:n.mode||"duration",config:{days:n.days||0,hours:n.hours||0,minutes:n.minutes||0,seconds:n.seconds||0,customEndDate:n.customEndDate||null,repeat:n.repeat||!1},startTime:Date.now(),lastUpdate:Date.now()},this.activeTimers.set(r,i)),this.persistTimers(),i}hasConfigChanged(t,e){return t.days!==(e.days||0)||t.hours!==(e.hours||0)||t.minutes!==(e.minutes||0)||t.seconds!==(e.seconds||0)||t.customEndDate!==(e.customEndDate||null)||t.repeat!==(e.repeat||!1)}hasModeChanged(t,e){return t!==(e||"duration")}getTimer(t,e){let n=`${t}_${e}`;return this.activeTimers.get(n)||null}initializeTimersFromBundle(t){t&&(t.settings?.showTimer&&t.settings.timer&&this.startTimer(t.id,"bundle",t.settings.timer),t.offers&&t.offers.forEach(e=>{e.bestSellerMode==="timer"&&e.timer&&this.startTimer(t.id,e.id,e.timer)}))}},K=class{constructor(t){this.instance=t,this.cachedUserData=null}get visitorId(){return O}async sendVisitorData(){if(b()?.enabled)return;let t=this.collectVisitorData();await this.sendAnalytics(t)}getCachedUserData(){return this.cachedUserData||(this.cachedUserData={deviceType:this.getDeviceType(navigator.userAgent),browser:this.getBrowser(navigator.userAgent),platform:this.getPlatform(navigator.userAgent),screenResolution:`${screen.width}x${screen.height}`,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,language:navigator.language||navigator.userLanguage}),this.cachedUserData}collectVisitorData(){let t=this.visitorId,e=this.getCachedUserData(),n=document.referrer||"",r=window.location.pathname;return{type:"visitor",visitor_id:t,user_agent:navigator.userAgent,device_type:e.deviceType,screen_resolution:e.screenResolution,language:e.language,timezone:e.timezone,platform:e.platform,browser:e.browser,referrer:n,landing_page:r,main_item_id:this.instance.bundle?.id||"unknown",config_id:this.instance.configId}}async sendAnalytics(t){if(b()?.enabled)return null;try{let n=await fetch("/apps/moonbundle-analytics",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(n.ok)return await n.json();throw new Error(`HTTP error! status: ${n.status}`)}catch(e){return console.warn("Failed to send analytics after retries:",e),null}}async sendAddToCart(t,e){if(!this.visitorId)return;let n={type:"atc",visitor_id:this.visitorId,sub_item_id:t,main_item_id:this.instance.bundle?.id||"unknown",selling_plan_id:e,cart_drawer_id:window?.moonBundleCartDrawerConfig?.firstMetafield?.id||null,config_id:this.instance.configId||this.instance.bundle?.id};await this.sendAnalytics(n)}getDeviceType(t){let e=t.toLowerCase();return/tablet|ipad|playbook|silk|android(?!.*mobile)/i.test(e)?"tablet":/mobile|iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile|opera mini/i.test(e)?"mobile":"desktop"}getBrowser(t){let e=t.toLowerCase();return e.includes("firefox")?"Firefox":e.includes("edge")?"Edge":e.includes("chrome")?"Chrome":e.includes("safari")&&!e.includes("chrome")?"Safari":e.includes("opera")?"Opera":e.includes("msie")||e.includes("trident")?"Internet Explorer":"Unknown"}getPlatform(t){let e=t.toLowerCase();return e.includes("windows")?"Windows":e.includes("macintosh")||e.includes("mac os x")?"macOS":e.includes("linux")?"Linux":e.includes("android")?"Android":e.includes("iphone")||e.includes("ipad")||e.includes("ipod")?"iOS":"Unknown"}},N=class N{static addInstance(t){let e=J();t.id=e,this.instances.set(e,t)}static removeInstance(t){let e=t.id;e&&this.instances.delete(e)}static getInstance(t){return this.instances.get(t)}static getAllInstances(){return Array.from(this.instances.values())}static findInstance(t){let e={};if(t instanceof FormData)t.forEach((s,a)=>{e[a]=s});else if(typeof t=="string")try{e=JSON.parse(t)}catch{t.includes("=")&&new URLSearchParams(t).forEach((l,c)=>{e[c]=l})}let n=e.items;if(Array.isArray(n)){if(n.some(s=>s?.properties?._moonProgressiveGift!=null))return{instance:null}}else if(e.properties?._moonProgressiveGift!=null)return{instance:null};let r=e["instance-id"]||e.items&&e.items[0]&&e.items[0]["instance-id"]||null;if(r){let s=N.getInstance(r);if(s)return{instance:s}}let i=e["product-id"]||e.id||e.items&&e.items[0]&&e.items[0].id||e.items&&e.items[0]&&e.items[0]["product-id"]||null;if(i){let s=N.getAllInstances();for(let[,a]of s.entries()){if(a.mainProduct&&a.mainProduct.id==i)return{instance:a};if(a.mainProduct&&a.mainProduct.variants?.some(l=>l.id==i))return{instance:a}}}return{instance:null}}};E(N,"instances",new Map);var A=N,m=class m{static isCartAddUrl(t){let e=typeof t=="string"?t:t instanceof Request?t.url:"";return!(!e||!m.CART_ADD_REGEX.test(e)||e.includes("opens_cart=never")||e.includes("moonbundle_ignore=true")||e.includes("moonbundle_cart=true")||e.includes("moonbundle_pg=true"))}static modifyCartResponse(t){if(!t)return t;let e="moonbundle-key";t.key=t.key||e;let n=t?.sections?.["cart-notification-product"];return n&&typeof n=="string"&&(t.sections["cart-notification-product"]=n.replace(/id="cart-notification-product-[^"]+"/g,`id="cart-notification-product-${e}"`)),t}static patchCartNotificationElement(){let t=()=>{let e=customElements.get("cart-notification");if(!e?.prototype?.renderContents)return!1;if(e.prototype._moonRenderContentsPatched)return!0;let n=e.prototype.renderContents;return e.prototype.renderContents=function(r){return n.call(this,m.modifyCartResponse(r))},e.prototype._moonRenderContentsPatched=!0,!0};t()||customElements.whenDefined("cart-notification").then(t)}static cloneResponseWithBody(t,e,n){let r=new Response(e,{status:t.status,statusText:t.statusText,headers:t.headers}),i=t.url||(typeof n=="string"?n:n?.url)||"";if(i)try{Object.defineProperty(r,"url",{value:i,configurable:!0})}catch{}return r}static async normalizeCartAddResponse(t,e){if(!t?.ok)return t;try{let n=await t.clone().json();if(Array.isArray(n?.items)&&n.items.length>0&&!n.key)return m.cloneResponseWithBody(t,JSON.stringify(m.modifyCartResponse(n)),e)}catch{}return t}static wrapFetch(){let t=window.fetch;window.fetch=async function(e,n={}){if(!m.isCartAddUrl(e))return t.call(this,e,n);let{instance:r}=A.findInstance(n.body);if(!r)return t.call(this,e,n);let i=await m.modifyCartRequest(e,n,r);if(i?._moonBlocked)return i.targetInstance?.dispatchEvent(new CustomEvent("moonbundle:block-add-to-cart",{detail:{reason:i._moonBlockReason,offerId:i._moonBlockOfferId},bubbles:!0})),new Response(JSON.stringify({message:"Moonbundle: incomplete multi-product offer"}),{status:422,statusText:"Unprocessable Entity",headers:{"Content-Type":"application/json"}});if(!i)return t.call(this,e,n);i.body&&(n.body=i.body);try{let s=await t.call(this,e,i);return s.ok&&i._moonAnalyticsCallback&&i._moonAnalyticsCallback(),r.bundle?.settings?.skipAtc&&(window.location.href="/checkout"),window?.opusOpen&&window?.opusOpen(),m.normalizeCartAddResponse(s,e)}catch(s){return console.error("Fetch error:",s),t.call(this,e,n)}},window.fetch._moonbundle=!0}static ensureFetchInterceptor(){window.fetch._moonbundle||m.wrapFetch()}static initialize(){if(m.isInitialized)return;try{m.wrapFetch(),m.patchCartNotificationElement();let e=window.XMLHttpRequest;window.XMLHttpRequest=function(){let n=new e,r=n.open,i=n.send;return n.open=function(s,a,...l){this._moonUrl=a,this._moonMethod=s,this._moonIsCartAdd=m.isCartAddUrl(a);let c=r.call(this,s,a,...l);if(this._moonIsCartAdd)try{this.setRequestHeader("Content-Type","application/json")}catch{}return c},n.send=async function(s){if(!m.isCartAddUrl(this._moonUrl))return i.call(this,s);let{instance:a}=A.findInstance(s);if(!a)return i.call(this,s);let l=await m.modifyCartRequest(this._moonUrl,{method:this._moonMethod,body:s,_isXHR:!0},a);if(l?._moonBlocked){a.dispatchEvent(new CustomEvent("moonbundle:block-add-to-cart",{detail:{reason:l._moonBlockReason,offerId:l._moonBlockOfferId},bubbles:!0})),this.status=422,this.statusText="Unprocessable Entity",this.responseText=JSON.stringify({message:"Moonbundle: incomplete multi-product offer"}),this.response=this.responseText,this.readyState=4,this.onreadystatechange&&this.onreadystatechange();return}if(!l)return i.call(this,s);try{let c=this.onreadystatechange;this.onreadystatechange=function(){this.readyState===4&&this.status>=200&&this.status<300&&l._moonAnalyticsCallback&&l._moonAnalyticsCallback(),c&&c.call(this)};let u=i.call(this,l.body);return a.bundle?.settings?.skipAtc&&setTimeout(()=>{window.location.href="/checkout"},100),window?.opusOpen&&window?.opusOpen(),u}catch(c){return console.error("XHR error:",c),i.call(this,s)}},n},document.addEventListener("submit",async function(n){let r=n.target;if(!r||!(r instanceof HTMLFormElement))return;let i=r.action||"";if(!m.isCartAddUrl(i)||(m.ensureFetchInterceptor(),n.defaultPrevented))return;let s=new FormData(r);n.preventDefault();try{await window.fetch(i,{method:r.method||"POST",body:s}),window?.opusOpen||(window.location.href="/cart")}catch(a){console.error("[Moonbundle] Submit interceptor error:",a),r.submit()}},!1)}catch(e){console.error("Failed to initialize request interceptors:",e)}m.isInitialized=!0;let t=()=>m.ensureFetchInterceptor();queueMicrotask(t),typeof window<"u"&&window.addEventListener("load",t,{once:!0})}static countMultiProductSlotsTotal(t){let e=t?.multiProduct?.slots??[],n=0;for(let r of e)(r.slotType==="fixed"&&r.product||r.slotType==="dynamic"&&r.dynamic||r.slotType==="ai"&&r.ai)&&n++;return n}static countFilledMultiProductSlots(t,e,n,r){let i=t?.multiProduct?.slots??[],s=n||{},a=r||{},l=0;for(let c of i)if(c.slotType==="fixed"&&c.product)(e?.[c.id]?.map(d=>d.id)??[]).length>0&&l++;else if(c.slotType==="dynamic"&&c.dynamic){let u=`${t.id}::${c.id}`;a[u]?.product&&l++}else if(c.slotType==="ai"&&c.ai){let u=`${t.id}::${c.id}`;s[u]?.product&&l++}return l}static isGiftUnlockAllowedBySlots(t,e,n,r,i){let s=e?.id;if(!(s&&t?.offerConfigs?.[s]?.unlockOnlyWhenAllSlotsFilled)||!e||e.type!=="multiProductV2")return!0;let l=m.countMultiProductSlotsTotal(e);return l===0?!0:m.countFilledMultiProductSlots(e,n,r,i)>=l}static async modifyCartRequest(t,e,n){try{let r=n.storeFrontManager?.selectedOfferId,i=n.storeFrontManager?.config,s=n.storeFrontManager?.subscription,{formData:a}=m.parseRequestData(e.body);if(!r)return null;let l=n.bundle?.offers?.find(f=>f.id===r),c=n._moonMpRuntime||{};if(l?.type==="multiProductV2"&&l?.multiProduct?.requireAllSlotsForAddToCart){let f=m.countMultiProductSlotsTotal(l);if(f>0&&m.countFilledMultiProductSlots(l,i?.offers?.[r],c.aiSlotLineProducts,c.slotDynamicLineProducts){r&&n.analyticsManager.sendAddToCart(r,s&&h(s?.sellingPlan)&&s.enabled?h(s?.sellingPlan):null),document.dispatchEvent(new Event("ajax-cart:added"))}}}catch(r){return console.error("Cart interception error:",r),null}}static parseRequestData(t){let e={};if(t instanceof FormData)t.forEach((n,r)=>{e[r]=n});else if(typeof t=="string")try{e=JSON.parse(t)}catch{t.includes("=")&&new URLSearchParams(t).forEach((i,s)=>{e[s]=i})}return{formData:e}}static buildBundleItems(t,e,n,r,i=null){let{bundle:s}=t,a={offer_id:n,bundle_id:s.id,config_id:t.configId,main_product_id:h(t.mainProduct.id),market_added:window.Shopify?.country||null},l=i?.enabled??!1,c=i?.sellingPlan??null,u=m.extractCustomProperties(e),d=s?.offers?.find(p=>p.id===n),f=d?.type==="multiProductV2"||d?.type==="skuV2",y=f&&d?.multiProduct?.slots?.length?new Set(d.multiProduct.slots.map(p=>p?.id).filter(Boolean).map(p=>String(p))):null,C=p=>t.mainProduct?.variants?.some(P=>P.id===p)?t.mainProduct:t.otherProducts?.find(P=>P?.variants?.some(_=>_.id===p)),B=new Map,R=new Map,U=new Map,pt=t._moonMpRuntime||{},Xt=s?.gifts||[];if(r?.offers?.[n]&&Object.entries(r.offers[n]).filter(([p])=>p!=="gifts").filter(([p])=>p!=="upsells").filter(([p])=>p!=="quantityToAdd").filter(([p])=>p!=="isSelected").filter(([p])=>p!=="dynamicGiftSelections").reverse().forEach(([p,P])=>{if(Array.isArray(P)){if(y&&y.size>0&&!y.has(String(p)))return;let _=f?p:null,I={...a,type:"bundle",..._?{slot_id:h(_)}:{}},S=f?null:h(p)===h(t.mainProduct.id)?t.mainProduct:t.otherProducts?.find(v=>h(v?.id)===h(p));P.forEach(v=>{if(!v.available)return;let mt=f?C(v.id):S,V=v.id,tt=f?`${V}::${p}`:V;if(B.has(tt))B.get(tt).quantity++;else{let ht={id:h(V),quantity:1,properties:{...yt({customProperties:u,isSlotKeyedOffer:f,lineKey:p,variantId:V,mainProduct:t.mainProduct,selectedOffer:d})?u:{},__moonbundle:JSON.stringify(I)}};l&&c&&mt&&wt(mt,c)&&(ht.selling_plan=parseInt(h(c),10)),B.set(tt,ht)}})}}),r?.offers?.[n]?.gifts){let p=r.offers[n].gifts;p&&typeof p=="object"?Object.entries(p).forEach(([P,_])=>{let I=Xt.find(S=>S.id===P);I&&(!Qt(I,n,s)||!m.isGiftUnlockAllowedBySlots(I,d,r?.offers?.[n],pt.aiSlotLineProducts,pt.slotDynamicLineProducts))||(Array.isArray(_)?_.forEach(S=>{if(!S.available||S.subscriptionOnly&&!l||S.skipAtc)return;let v=S.id;R.has(v)?R.get(v).quantity++:R.set(v,{id:h(v),quantity:1,properties:{__moonbundle:JSON.stringify({...a,type:"gift"})}})}):console.error("variantObjects is not an array:",_))}):console.error("gifts is not an object:",p)}if(r?.offers?.[n]?.upsells){let p=r.offers[n].upsells;p&&typeof p=="object"?Object.entries(p).forEach(([P,_])=>{!_.isSelected||_.subscriptionOnly&&!l||(Array.isArray(_.variants)?_.variants.forEach(I=>{if(!I.available)return;let S=I.id;U.has(S)?U.get(S).quantity++:U.set(S,{id:h(S),quantity:1,properties:{__moonbundle:JSON.stringify({type:"upsell",...a})}})}):console.error("upsellDesign.variants is not an array:",_.variants))}):console.error("upsells is not an object:",p)}let $=1,Z=r.offers[n].quantityToAdd;Z&&Z>=1&&($=Z);let Yt=Array.from(B.values()).map(p=>({...p,quantity:p.quantity*$})),Kt=Array.from(R.values()).map(p=>({...p,quantity:p.quantity*$})),Zt=Array.from(U.values()).map(p=>({...p,quantity:p.quantity*$}));return[...Kt,...Zt,...Yt]}static buildRequestBody(t,e,n){let r={attributes:{moonbundle_visitor_id:n},items:t},i=qt();return i&&Object.assign(r.attributes,i),m.SHOPIFY_FIELDS.forEach(s=>{e[s]&&(r[s]=e[s])}),r}static extractCustomProperties(t){let e={};for(let r in t)if(r.startsWith("properties[")&&r.endsWith("]")){let i=r.slice(11,-1);e[i]=t[r]}let n=t.items;if(Array.isArray(n))for(let r of n){let i=r.properties;if(i&&typeof i=="object")for(let[s,a]of Object.entries(i))s in e||(e[s]=a)}return e}};E(m,"CART_ADD_REGEX",/\/cart\/add/),E(m,"SHOPIFY_FIELDS",["section-id","sections","sections_url"]),E(m,"isInitialized",!1);var lt=m,g=class g{static async load(t){let e=await T();if(!e?.bundles?.length)return null;let n=e.storefrontToken;if(!n)return null;let r={country:window.Shopify?.country,language:G()},i=await g.fetchProduct(n,t,r);if(!i)return null;let s=Q(e.shopConfig?.ianaTimezone),a=b(),l=a?.enabled&&a.bundleId?a.bundleId:void 0,c=g.selectBundle(e.bundles,`gid://shopify/Product/${i.id}`,i.collections,e.currentMarketId,s,{forceBundleId:l,skipSchedule:!!l});if(!c)return null;let u=await g.fetchRelatedProducts(c,n,r);return{product:i,otherProducts:u,bundle:c,shopConfig:e.shopConfig,globalCustomCss:e.globalBundleCustom?.globalCustomCss||"",globalCustomJs:e.globalBundleCustom?.globalCustomJs||"",storefrontToken:n}}static async storefrontQuery(t,e,n){let r=n?{query:e,variables:n}:{query:e},i=await fetch(`/api/${g.API_VERSION}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t},body:JSON.stringify(r)});if(!i.ok)return null;let s=await i.json();return s.errors?null:s.data}static inContextDirective(t){if(!t?.country&&!t?.language)return"";let e=[];return t.country&&e.push(`country: ${t.country}`),t.language&&e.push(`language: ${t.language}`),`@inContext(${e.join(", ")})`}static async fetchProduct(t,e,n={}){let r=e.startsWith?.("gid://")?e:`gid://shopify/Product/${e}`,s=`query ${g.inContextDirective(n)} { product(id: "${r}") { ${g.PRODUCT_FRAGMENT} } }`,a=await g.storefrontQuery(t,s);return a?.product?g.normalizeProduct(a.product):null}static async fetchProductsByIds(t,e,n={}){if(!e.length)return[];let i=`query($ids: [ID!]!) ${g.inContextDirective(n)} { nodes(ids: $ids) { ... on Product { ${g.PRODUCT_FRAGMENT} } } }`,s=await g.storefrontQuery(t,i,{ids:e});return s?.nodes?s.nodes.filter(Boolean).map(g.normalizeProduct):[]}static async fetchRelatedProducts(t,e,n={}){let r=new Set,i=a=>{if(a)for(let l of a){if(l.products)for(let u of l.products)u.id&&u.id!=="previewProduct"&&r.add(u.id);let c=l.multiProduct?.slots?.filter(u=>u.slotType==="fixed"&&u.product).map(u=>u.product)||[];for(let u of c)u.id&&u.id!=="previewProduct"&&r.add(u.id)}};for(let a of t.configs||[t])i(a.gifts),i(a.upsells),i(a.offers);if(!r.size)return[];let s=[...r].map(a=>a.startsWith?.("gid://")?a:`gid://shopify/Product/${a}`);return g.fetchProductsByIds(e,s,n)}static normalizeProduct(t){let e=D(t.id),n=t.collections.nodes.map(c=>({id:c.id,numericId:D(c.id),handle:c.handle,title:c.title})),r={},i={},s=[];for(let c of t.options||[]){s.push(c.name),r[c.name]=c.optionValues.map(d=>d.name);let u={};for(let d of c.optionValues){if(!d.swatch)continue;let f={};d.swatch.color&&(f.color=d.swatch.color),d.swatch.image?.previewImage?.url&&(f.image=d.swatch.image.previewImage.url),Object.keys(f).length&&(u[d.name]=f)}i[c.name]=u}let a=(t.variants?.nodes||[]).map(c=>{let u=Math.round(Number(c.price.amount)*100),d=c.compareAtPrice?Math.round(Number(c.compareAtPrice.amount)*100):null,f=c.selectedOptions.map(C=>C.value),y=(c.sellingPlanAllocations?.nodes||[]).map(C=>({selling_plan_id:D(C.sellingPlan.id),selling_plan_group_id:null,price:C.priceAdjustments?.[0]?.price?Math.round(Number(C.priceAdjustments[0].price.amount)*100):u}));return{id:D(c.id),title:c.title,name:`${t.title} - ${c.title}`,public_title:c.title,available:c.availableForSale,price:u,compare_at_price:d,options:f,option1:f[0]||null,option2:f[1]||null,option3:f[2]||null,featured_image:c.image?{src:c.image.url}:null,selling_plan_allocations:y}}),l=(t.sellingPlanGroups?.nodes||[]).map((c,u)=>({id:`gid://shopify/SellingPlanGroup/${u}`,sellingPlans:c.sellingPlans.nodes.map(d=>({id:d.id,name:d.name}))}));return{id:e,title:t.title,handle:t.handle,image:t.featuredImage?.url||null,variants:a,options:s,collections:n,options_with_values:r,optionSwatches:i,sellingPlanGroups:l}}static bundleMatchesProduct(t,e,n){if(t.visibility==="products"&&t.products?.length)return t.products.some(r=>r.id===e);if(t.visibility==="collections"&&t.collections?.length){for(let r of t.collections)if(n.some(i=>i.id===r.id||i.numericId===r.id||`gid://shopify/Collection/${i.numericId}`===r.id))return!0;return!1}if(t.visibility==="all"){let r=h(e);return!(t.excludedProducts||[]).some(s=>h(s.id)===r||s.id===e)}return!1}static selectBundle(t,e,n,r,i="UTC",s={}){let{forceBundleId:a,skipSchedule:l=!1}=s,c=d=>{let f=d.market;return!f||f==="all"?!0:!f.id||f.id===r};if(l&&a){let d=t.find(f=>f.id===a);if(d&&c(d)&&g.bundleMatchesProduct(d,e,n))return d}let u=d=>Wt(d.schedule,new Date,i);for(let d of t)if(!(!c(d)||!u(d))&&d.visibility==="products"&&d.products?.length&&d.products.some(f=>f.id===e))return d;for(let d of t)if(!(!c(d)||!u(d))&&d.visibility==="collections"&&d.collections?.length){for(let f of d.collections)if(n.some(y=>y.id===f.id||y.numericId===f.id||`gid://shopify/Collection/${y.numericId}`===f.id))return d}for(let d of t)if(!(!c(d)||!u(d))&&d.visibility==="all"&&g.bundleMatchesProduct(d,e,n))return d;return null}};E(g,"API_VERSION","2026-04"),E(g,"PRODUCT_FRAGMENT",` id handle title featuredImage { url } collections(first: 50) { nodes { id handle title } } options { name optionValues { name swatch { color image { ... on MediaImage { previewImage { url } } } } } } variants(first: 250) { nodes { id title availableForSale price { amount } compareAtPrice { amount } selectedOptions { name value } image { url } sellingPlanAllocations(first: 50) { nodes { sellingPlan { id } priceAdjustments { price { amount } } } } } } sellingPlanGroups(first: 10) { nodes { sellingPlans(first: 20) { nodes { id name } } } } `);var ut=g,dt=class extends HTMLElement{constructor(){super(),this.getAttribute("main-product")&&this._initFromAttributes()}_initFromAttributes(){this.mainProduct=JSON.parse(this.getAttribute("main-product")||"{}");let t=this.getAttribute("other-products")||"[]",e=JSON.parse(t);this.otherProducts=e.map(n=>{try{return typeof n=="string"?JSON.parse(n):n}catch(r){return console.warn("Failed to parse product:",n,r),null}}).filter(Boolean),this.bundle=JSON.parse(this.getAttribute("bundle")||"{}"),this.translations=JSON.parse(this.getAttribute("translations")||"null"),this.blockType=this.getAttribute("block-type")||"embed",this._applySharedStoreConfig(),this.analyticsManager=new K(this),this.timerManager=new Y(O),this.abTestManager=new x(O),this.initConfig(),A.addInstance(this)}_applySharedStoreConfig(t={}){let e=k(),n=q(),r=this.getAttribute("shop-config");this.shopConfig=t.shopConfig??e?.shopConfig??(r?JSON.parse(r):{}),this.storefrontToken=t.storefrontToken??e?.storefrontToken??this.getAttribute("storefront-token")??"";let i=t.globalCustomCss??n?.globalCustomCss??this.getAttribute("global-custom-css");this.globalCustomCss=i||null;let s=t.globalCustomJs??n?.globalCustomJs??this.getAttribute("global-custom-js");this.globalCustomJs=s||null}initConfig(){let t=this.abTestManager.getAssignedConfig(this.bundle);if(this.configId=t.configId,t.config){let e=this.bundle.id;this.bundle={...this.bundle,...t.config},this.bundle.id=e,delete this.bundle.configs}}connectedCallback(){if(this._isRendered)return;let t=this.getAttribute("data-moonbundle-product-id"),e=this.getAttribute("data-moonbundle-schedule-fallback")==="true";if(!this.getAttribute("main-product")&&t){if(e&&!b()?.enabled){this.remove();return}this._isDeferred=!0,this._deferredProductId=t,this._isThemeBlockShell=this.getAttribute("data-moonbundle-block")==="true"}if(this._isDeferred){if(this._isInitializing)return;this._isInitializing=!0,this._initDeferred();return}!this.bundle?.id&&this.getAttribute("main-product")&&this._initFromAttributes(),this._isRendered=!0;let n=this.mainProduct?.id,r=document.querySelector(`moonbundle-component[data-moonbundle-block="true"][data-moonbundle-product-id="${n}"]`);if(r&&r!==this&&this.blockType!=="block"){this.parentElement&&(this.parentElement.removeChild(this),A.removeInstance(this));return}this.render()}async _initDeferred(){try{let t=await ut.load(this._deferredProductId);if(!t)return;this.mainProduct=t.product,this.otherProducts=t.otherProducts,this.bundle=t.bundle,this.blockType=this._isThemeBlockShell?"block":"embed",this.translations=null,this._applySharedStoreConfig({shopConfig:t.shopConfig,storefrontToken:t.storefrontToken,globalCustomCss:t.globalCustomCss,globalCustomJs:t.globalCustomJs}),this.setAttribute("main-product",JSON.stringify(t.product)),this.setAttribute("other-products",JSON.stringify(t.otherProducts)),this.setAttribute("bundle",JSON.stringify(t.bundle)),this.setAttribute("block-type",this.blockType),this._isThemeBlockShell||this.setAttribute("data-moonbundle-deferred","true"),this.analyticsManager=new K(this),this.timerManager=new Y(O),this.abTestManager=new x(O),this.initConfig(),A.addInstance(this),this._isDeferred=!1,this._isRendered=!0,this.render()}catch(t){console.error("[MoonBundle] Deferred init failed:",t)}}render(){let t=n=>{this.svelteApp=n({target:this,props:{mainProduct:this.mainProduct,otherProducts:this.otherProducts,shopConfig:this.shopConfig,bundle:this.bundle,translations:this.translations,instanceId:this.id,configId:this.configId,globalCustomCss:this.globalCustomCss,globalCustomJs:this.globalCustomJs,storefrontToken:this.storefrontToken}});let r=new ft(this,this.analyticsManager);this.storeFrontManager=r,r.initialize(),this.analyticsManager&&this.analyticsManager.sendVisitorData(),this.timerManager&&this.timerManager.initializeTimersFromBundle(this.bundle),lt.initialize(),e()},e=async()=>{try{await St(this.id,{isCancelled:()=>!this.isConnected})}catch(n){n?.code!=="cancelled"&&console.warn("[MoonBundle] Svelte subscriptions skipped:",n);return}window.MoonBundle[this.id].config.subscribe(n=>{if(this.storeFrontManager.config=n,n?.offers){let r=Object.keys(n.offers).find(i=>n.offers[i]?.isSelected===!0);if(r&&r!==this.storeFrontManager.selectedOfferId){this.storeFrontManager.selectedOfferId=r;let i=this.bundle.offers.find(a=>a.id===r),s=this.storeFrontManager._getMainProductVariantIdFromOfferConfig(this.storeFrontManager.config?.offers?.[r],i,this.mainProduct?.id);s&&(this.storeFrontManager._isUpdatingFromBundle=!0,this.storeFrontManager._lastProcessedVariantId=s,this.storeFrontManager._updateThemeSelectors(s.toString()),this.storeFrontManager.updateVariantInForm(s),setTimeout(()=>{this.storeFrontManager._isUpdatingFromBundle=!1},300))}}if(n?.lastModifiedVariantId&&!this.storeFrontManager._isUpdatingFromTheme){this.storeFrontManager._isUpdatingFromBundle=!0,this.storeFrontManager._lastProcessedVariantId=n.lastModifiedVariantId;let r=n.lastModifiedVariantId.toString();this.storeFrontManager._updateThemeSelectors(r),this.storeFrontManager.updateVariantInForm(r),setTimeout(()=>{this.storeFrontManager._isUpdatingFromBundle=!1},300)}if(this.storeFrontManager.selectedOfferId){this.storeFrontManager.displayExpressCheckout();let r=this.bundle.offers.find(i=>i.id===this.storeFrontManager.selectedOfferId);this.storeFrontManager.updateQuantityInForm(r)}}),window.MoonBundle[this.id].subscription.subscribe(n=>{this.storeFrontManager.subscription=n}),window.MoonBundle[this.id].prices.subscribe(n=>{this.bundle.settings.themePrice?.sync&&this.storeFrontManager.updateThemePrice(n,this.bundle.settings.themePrice.syncMethod)}),this.storeFrontManager.initializeVariantSync()};_t({isCancelled:()=>!this.isConnected}).then(n=>{!this.isConnected||this.svelteApp||t(n)}).catch(n=>{n?.code!=="cancelled"&&console.warn("[MoonBundle] Svelte mount function not found. Ensure moonbundle-block JS is loaded.",n)})}},ft=class{constructor(t,e){this.instance=t,this.selectedOfferId=null,this.config=null,this.subscription={enabled:!1,sellingPlan:null},this.analyticsManager=e,this._isUpdatingFromBundle=!1,this._isUpdatingFromTheme=!1,this._lastProcessedVariantId=null,this.productForms=document.querySelectorAll('section[class*="product"]:not(.shopify-section--product-recommendations), section[id*="product"]:not(.shopify-section--product-recommendations), section[data-product]:not(.shopify-section--product-recommendations), [id*="ProductInformation"], product-info, [class*="product-block"], [class*="product_section"]:not(.shopify-section--product-recommendations), [class*="product-form-product-template"], [class*="addToCartForm"], [class*="product__main__content"], [data-ref="product-form"], article.m6pr'),this._currentDiscountedPrice=null,this._currentOriginalPrice=null,this._currentDiscountPercent=null,this._priceObserver=null}getFirstAtcVisibleForm(t=!1){let e=r=>{let i=r.getAttribute("id")||"",s=r.getAttribute("class")||"";return i.includes("cart-popup")||i.includes("quick-add")||i.includes("drawer")||s.includes("cart-popup")||s.includes("quick-add")||s.includes("drawer")||s.includes("atc_sticky")||s.includes("upsell")||i.includes("product-installment-form")||i.includes("product-form-installment")||i.includes("atc_sticky")||i.includes("upsell")},n=r=>{let i=r.parentElement;for(;i;){let s=i.querySelector('product-form form[action*="/cart/add"]');if(s&&!e(s))return s;let a=i.querySelector('form[action*="/cart/add"]');if(a&&!e(a))return a;i=i.parentElement}return null};if(t)return n(this.instance);for(let r of document.querySelectorAll("product-form")){let i=r.offsetParent&&r.querySelector('form[action*="/cart/add"]');if(i&&!e(i))return i}for(let r of document.querySelectorAll('form[action*="/cart/add"]'))if(r.offsetParent&&!e(r))return r;for(let r of document.querySelectorAll("[data-replo-product-container]")){let i=r.querySelector('form[action*="/cart/add"]');if(i&&!e(i))return i}return null}displayExpressCheckout(){let t=document.querySelectorAll('[class*="shopify-payment-button"], [id*="shopify-payment-button"], shopify-accelerated-checkout');if(t.length===0)return;let e=this.config?.offers?.[this.selectedOfferId]?.[this.instance.mainProduct?.id],n=this.config?.offers?.[this.selectedOfferId]?.gifts&&Object.keys(this.config.offers[this.selectedOfferId].gifts).length>0,r=this.config?.offers?.[this.selectedOfferId]?.upsells&&Object.values(this.config.offers[this.selectedOfferId].upsells).some(u=>u.isSelected),i=this.config?.offers?.[this.selectedOfferId],s=i&&Object.keys(i).filter(u=>u!=="gifts"&&u!=="upsells"&&u!=="isSelected"&&u!=="lastModifiedVariantId"&&u!=="quantityToAdd"),a=Array.isArray(s)&&s.length>1,l=e&&e.length>1&&e.some(u=>{let d=u.id,f=e[0].id;return d!==f}),c=n||l||a||r;t.forEach(u=>{u.style.display=c?"none":"block",u.style.visibility=c?"hidden":"visible"})}initialize(){let t=this.instance.blockType==="block";this.atcForm=this.getFirstAtcVisibleForm(t);let e='[class*="quantity"]:not([class*="moonbundle"]):not([id*="moon_bundle"]):not([class*="product-form__quantity"]):not([class*="bndlr-contains-quantity-break"]), [id*="quantity"]:not([class*="moonbundle"]):not([id*="moon_bundle"]):not([class*="product-form__quantity"]):not([class*="bndlr-contains-quantity-break"]), quantity-selector-component, gp-product-quantity, kaching-subscriptions, [class*="sealsubs"], [class*="appstle"], [class*="subify"], [class*="loop-widget"], [class*="Avada-Subscription"], [class*="bsub-widget"], gp-product-quantity';if(this.instance.bundle.settings.hideThemePicker&&(e+=', [id*="variant"]:not(li, ul, [class*="moonbundle"], [class*="no-variants"], [class*="hide-variant"], [class*="sticky-atc"], [class*="quick-add"], [class*="drawer"], [class*="variants--"]), [class*="variant"]:not(li, ul, [class*="moonbundle"], [class*="no-variants"], [class*="variants--"], [class*="hide-variant"], [class*="sticky-atc"], [class*="quick-add"], [class*="drawer"]), variant-selects:not([class*="sticky-atc"]), product-variants:not([class*="sticky-atc"]), variant-picker:not([class*="sticky-atc"]), [data-pf-type="ProductVariantSwatches"]:not([class*="sticky-atc"]), [class*="radio-wrapper"]:not([class*="sticky-atc"]), [class*="variant-picker"]:not([class*="sticky-atc"]), [class*="variant-wrapper"]:not([class*="sticky-atc"]), [class*="swatch_options"]:not([class*="sticky-atc"]), [class*="selector-wrapper"], variant-radios, [class*="t4s-swatch-variants"]'),this.instance.bundle.settings.themePrice?.hide&&(e+=', [class*="price"]:not([class*="moonbundle"]), [id*="price"]:not([class*="moonbundle"])'),this.atcForm){if(!this.atcForm.querySelector('input[type="hidden"][name="product-id"], input[type="hidden"][name="id"]')){let c=document.createElement("input");c.type="hidden",c.name="product-id",c.value=this.instance.mainProduct.id,this.atcForm.appendChild(c)}if(!this.atcForm.querySelector('input[type="hidden"][name="instance-id"]')){let c=document.createElement("input");c.type="hidden",c.name="instance-id",c.value=this.instance.id,this.atcForm.appendChild(c)}}this.hideThemeElements(e),this.instance.bundle.settings.hideThemePicker&&this.startHideObserver(e),this.startPriceObserver();let n=document.querySelector(".moonbundleCustomLoader"),r=this.instance.bundle.settings.position==="page_builder"&&!!n,i=this.instance.hasAttribute("data-moonbundle-deferred"),s=this.instance.hasAttribute("data-moonbundle-preview-bootstrap");if(!(i&&!s))if(r)n.appendChild(this.instance);else{if(t)return;{if(!this.atcForm){console.error("MoonBundleComponent: Impossible d'afficher le bundle - formulaire 'Ajouter au panier' introuvable");return}let a=this.atcForm.querySelector("gp-product-button"),l=this.atcForm.querySelector('button[data-pf-type*="ProductATC2"]'),u=this.atcForm.closest("[data-replo-product-container]")?.querySelector("button[data-replo-add-product-variant-to-cart]");a?a.insertAdjacentElement("beforebegin",this.instance):u?u.insertAdjacentElement("beforebegin",this.instance):l?l.insertAdjacentElement("beforebegin",this.instance):this.atcForm.insertAdjacentElement("beforebegin",this.instance)}}}_handleBundleChangeFromTheme(t){this._isUpdatingFromBundle||(this._lastProcessedVariantId=t,this._isUpdatingFromTheme=!0,this._syncToBundle(t),setTimeout(()=>{this._isUpdatingFromTheme=!1},100))}initializeVariantSync(){this._syncFromUrl(),this._setupUrlListener(),this._setupFormListener()}_syncFromUrl(){let e=new URL(window.location.href).searchParams.get("variant");e&&(this._lastSyncedVariantId=e,this._syncToBundle(e))}_setupUrlListener(){this._setupLocationChangeEvent(),this._onUrlChange=()=>{let e=new URL(window.location.href).searchParams.get("variant");this._isUpdatingFromBundle||e&&e==this._lastProcessedVariantId||e&&this._handleBundleChangeFromTheme(e)},window.addEventListener("locationchange",this._onUrlChange)}_setupLocationChangeEvent(){if(window._moonbundleLocationChangeSetup)return;window._moonbundleLocationChangeSetup=!0;let t=()=>{window.dispatchEvent(new Event("locationchange"))},e=history.pushState;history.pushState=function(...r){let i=e.apply(this,r);return t(),i};let n=history.replaceState;history.replaceState=function(...r){let i=n.apply(this,r);return t(),i},window.addEventListener("popstate",t)}_setupFormListener(){if(!this.atcForm)return;let t=this.atcForm.querySelector("[name='id']");t&&(this._onVariantInputChange=()=>{let e=t.value;this._isUpdatingFromBundle||e&&e==this._lastProcessedVariantId||e&&this._handleBundleChangeFromTheme(e)},t.addEventListener("change",this._onVariantInputChange),t.addEventListener("variant-change",this._onVariantInputChange),t.addEventListener("input",this._onVariantInputChange))}_isMainProductMultiproductSlot(t,e){return et(t,e)}_getMainProductVariantIdFromOfferConfig(t,e,n){if(!t)return null;let r=t[n]?.[0]?.id;if(r)return r;let i=h(n);for(let s of e?.multiProduct?.slots??[]){if(!this._isMainProductMultiproductSlot(s,i))continue;let a=t[s.id]?.[0]?.id;if(a)return a}return null}_buildSyncedVariantLines(t,e,n,r){if(r.length>0){let i=[];for(let s=0;sr.id.toString()===t||h(r.id)===t);if(!e)return;let n=window.MoonBundle[this.instance.id]?.config;if(!n){console.error("\u274C [SYNC\u2192BUNDLE] No config store found");return}n.update(r=>{let i={...r};i.offers||(i.offers={});let s=this.instance.mainProduct.id,a=h(s),l=`gid://shopify/Product/${s}`;return this.instance.bundle.offers.forEach(c=>{i.offers[c.id]||(i.offers[c.id]={});let u=i.offers[c.id],d=c.variants?.productSettings?.[l]?.variants||[];if(u[s]){let f=this.getOfferQuantity(c);u[s]=this._buildSyncedVariantLines(u[s]||[],f,e,d)}c.multiProduct?.slots?.length&&c.multiProduct.slots.forEach(f=>{if(!this._isMainProductMultiproductSlot(f,a))return;let y=f.id;if(!u[y])return;let C=f.quantity??f.product?.quantity??1;u[y]=this._buildSyncedVariantLines(u[y]||[],C,e,d)})}),i.lastModifiedVariantId!==e.id&&(i.lastModifiedVariantId=e.id),i})}_updateThemeSelectors(t){let e=this.instance.mainProduct.variants.find(i=>i.id.toString()===t.toString());if(!e||!e.options)return;let n=e.options,r=this.instance.mainProduct.options;n.forEach((i,s)=>{if(sc.value===n)&&a.value!==n)return a.value=n,a.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1}_updateDirectVariantSelect(t){let e=document.querySelectorAll('select:not([class*="moonbundle"])');for(let n of e)if(Array.from(n.options).find(i=>Number(i.value)===Number(t))&&n.value!==t.toString())return n.value=t.toString(),n.dispatchEvent(new Event("change",{bubbles:!0})),!0;return!1}getOfferQuantity(t){if(t.qty&&!t.multiProduct?.slots?.length)return t.qty;if(t.multiProduct?.slots?.length){let e=t.multiProduct.slots.filter(i=>i.slotType==="fixed"&&i.product).map(i=>i.product),n=h(this.instance.mainProduct.id);return e.find(i=>i.id==="previewProduct"||h(i.id)===n)?.quantity||1}return 1}updateQuantityInForm(t){if(!t||!this.atcForm)return;document.querySelectorAll('[name="quantity"]:not([data-moonbundle-quantity])').forEach(s=>{s.getAttribute("form")&&s.removeAttribute("form"),s.type!=="hidden"&&(s.style.display="none",s.disabled=!0)});let n=this.atcForm.querySelector("[data-moonbundle-quantity]");n||(n=document.createElement("input"),n.type="hidden",n.name="quantity",n.setAttribute("data-moonbundle-quantity","true"),this.atcForm.appendChild(n));let r=this.getOfferQuantity(t),i=this.config.offers[t.id].quantityToAdd;i&&i>1&&(r*=i),n.value=r}updateVariantInForm(t){if(!t||!this.atcForm)return;let e=this.atcForm.querySelector("[name='id']");e||(e=document.createElement("input"),e.type="hidden",e.name="id",this.atcForm.appendChild(e)),e.value=t;try{e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new Event("input",{bubbles:!0}))}catch{}}updateThemePrice(t,e){if(!this.selectedOfferId||!t||!t[this.selectedOfferId])return;let n=t[this.selectedOfferId],r,i;e==="unit_price"?(r=n.unitDiscountedPriceFormatted,i=n.unitOriginalPriceFormatted):e==="bundle_total"&&(r=n.totalWithUpsellsDiscountedPriceFormatted,i=n.totalWithUpsellsOriginalPriceFormatted);let s=e==="unit_price"?n.unitOriginalPrice:n.totalWithUpsellsOriginalPrice,a=e==="unit_price"?n.unitDiscountedPrice:n.totalWithUpsellsDiscountedPrice,l=s>0?Math.round((s-a)/s*100):0;this._currentDiscountedPrice=r,this._currentOriginalPrice=i,this._currentDiscountPercent=l,this._updateCurrentPrice(r),r!==i&&this._updateComparePrice(i),this._updateDiscountBadge(l)}_shouldSkipThemePriceElement(t){return!t||typeof t.closest!="function"?!0:t.closest('[class*="moonbundle"]')||t.closest('[id*="moonbundle"]')||t.closest("slideshow-component")}_updateCurrentPrice(t){this._priceObserver&&this._priceObserver.disconnect();let e=[".price--large .price__regular .price-item--regular",".price--large .price__sale .price-item--sale",".price--medium .price__regular .price-item--regular",".price--medium .price__sale .price-item--sale",".lumin-price .price__regular .price-item--regular",".lumin-price .price__sale .price-item--sale",".product-page-price .price__regular .price-item--regular",".product-page-price .price__sale .price-item--sale",".f-price--large .f-price__regular .f-price-item--regular",".f-price--large .f-price__sale .f-price-item--sale",'gp-product-price div[type="price"]',"product-price .price",".pp-product-price .pp-price-item--regular",".product__price-and-badge .product__price--regular",".product-block--price span[data-product-price]",".main-product__block-price .m-price__regular .m-price-item--regular",".main-product__block-price .m-price__sale .m-price-item--sale",".product-info__price price-money",'.product-info__block-item[data-block-type="price"] price-money',".product-form__info-item .price--on-sale",'[data-product-type="price"]',".product__price-wrapper .price__container .price__regular",".product__price-wrapper .price__container .price__sale",".price-regular .price",'[itemprop="price"]',".main-atc-price",".total-price__detail",'[id*="atc-price"]','[data-ref="price"]',"button.overlay-buy_button span",".main-product-price .price",".shop-product-price-block","sale-price","price-list sale-price",".product-info__price sale-price",".new-price","product-buy-price","[data-button-price]",".section-store--atc-price"];this.productForms.forEach(n=>{e.forEach(r=>{n.querySelectorAll(r).forEach(s=>{if(!this._shouldSkipThemePriceElement(s)&&(s.innerHTML!==t&&(s.innerHTML=t),s.hasAttribute("data-price"))){let a=parseInt(t.replace(/[^0-9]/g,""),10);!isNaN(a)&&s.getAttribute("data-price")!==String(a)&&s.setAttribute("data-price",a)}})})}),document.querySelectorAll("product-price").forEach(n=>{if(this._shouldSkipThemePriceElement(n)||Array.from(this.productForms).some(s=>s.contains(n)))return;let i=n.querySelector('[data-ref="price"], .price');i&&i.innerHTML!==t&&(i.innerHTML=t)}),document.querySelectorAll(".shop-add-to-cart-button, .product-form__submit").forEach(n=>{if(this._shouldSkipThemePriceElement(n))return;let r=n.dataset.persistentText;if(!r)return;let i=`${r} - ${t}`,s=n.querySelector(".button-text");s&&s.textContent!==i&&(s.textContent=i),n.dataset.originalText!==i&&(n.dataset.originalText=i)}),this._priceObserver&&this.productForms.forEach(n=>{this._priceObserver.observe(n,{childList:!0,subtree:!0,characterData:!0})})}_updateComparePrice(t){this._priceObserver&&this._priceObserver.disconnect();let e=[".price--large .price__sale .price-item--regular",".price--medium .price__sale .price-item--regular",".lumin-price .price__sale .price-item--regular",".product-page-price .price__sale .price-item--regular",".f-price--large .f-price__sale .f-price-item--regular",'gp-product-price div[type="compare"]',"product-price .compare-at-price",".pp-product-price .pp-price-item--sale",".product__price-and-badge .product__price--compare",".product-block--price span[data-compare-price]",".main-product__block-price .m-price__sale .m-price-item--regular",".product-info__price compare-at-price",'.product-info__block-item[data-block-type="price"] compare-at-price',".product-form__info-item .price--compare",'[data-product-type="compare_at_price"]',".product__price-wrapper .price__container .price__sale del",'[data-ref="compare-at-price"]',".compare-price",".section-store--atc-compare-price"];this.productForms.forEach(n=>{e.forEach(r=>{n.querySelectorAll(r).forEach(s=>{this._shouldSkipThemePriceElement(s)||(s.innerHTML!==t&&(s.innerHTML=t),s.style.display!==""&&(s.style.display=""))})})}),document.querySelectorAll("product-price").forEach(n=>{if(this._shouldSkipThemePriceElement(n)||Array.from(this.productForms).some(s=>s.contains(n)))return;let i=n.querySelector('[data-ref="compare-at-price"], .compare-at-price');i&&(i.innerHTML!==t&&(i.innerHTML=t),i.style.display!==""&&(i.style.display=""))}),this._priceObserver&&this.productForms.forEach(n=>{this._priceObserver.observe(n,{childList:!0,subtree:!0,characterData:!0})})}_updateDiscountBadge(t){this._priceObserver&&this._priceObserver.disconnect();let e=[".price--large .price__badge-sale",".lumin-price .price__badge-sale",".product-page-price .price__badge-sale",".f-price--large .f-price__badge-sale","product-price .badge",".pp-product-price .pp-price__badge",".product__price-and-badge .product__badge",".product-block--price .product-block__badge",".main-product__block-price .m-price__badge",".product-info__price .badge",'.product-info__block-item[data-block-type="price"] .badge',".product-form__info-item .badge",'[data-product-type="badge"]',".product__price-wrapper .price__badge"];this.productForms.forEach(n=>{e.forEach(r=>{n.querySelectorAll(r).forEach(s=>{if(!this._shouldSkipThemePriceElement(s))if(t>0){let a=s.querySelector(".badge__percentage-saved");if(a){let l=String(t);a.textContent!==l&&(a.textContent=l)}else{let l=s.innerHTML.replace(/-?\d+(\s*<[^>]*>\s*)?%/,`-${t}%`);l!==s.innerHTML&&(s.innerHTML=l)}s.style.display!==""&&(s.style.display="")}else s.style.display!=="none"&&(s.style.display="none")})})}),document.querySelectorAll("product-price").forEach(n=>{if(this._shouldSkipThemePriceElement(n)||Array.from(this.productForms).some(s=>s.contains(n)))return;let i=n.querySelector(".badge");if(i)if(t>0){let s=i.querySelector('[data-ref="difference-price-value"], .badge__savings, .badge__percentage-saved');if(s){let a=`-${t}%`;s.textContent!==a&&(s.textContent=a)}else{let a=i.innerHTML.replace(/-?\d+(\s*<[^>]*>\s*)?%/,`-${t}%`);a!==i.innerHTML&&(i.innerHTML=a)}i.style.display!==""&&(i.style.display="")}else i.style.display!=="none"&&(i.style.display="none")}),this._priceObserver&&this.productForms.forEach(n=>{this._priceObserver.observe(n,{childList:!0,subtree:!0,characterData:!0})})}hideThemeElements(t){this.productForms.forEach(e=>{let n=e.querySelectorAll(t);n.length>0&&n.forEach(r=>{r.style.visibility="hidden",r.style.setProperty("display","none","important")})})}startHideObserver(t){let e=new MutationObserver(n=>{let r=!1;n.forEach(i=>{i.type==="childList"&&i.addedNodes.forEach(s=>{s.nodeType===Node.ELEMENT_NODE&&(s.matches&&s.matches(t)&&(r=!0),s.querySelectorAll&&s.querySelectorAll(t).length>0&&(r=!0))})}),r&&this.hideThemeElements(t),this.displayExpressCheckout()});e.observe(document.body,{childList:!0,subtree:!0}),this._hideObserver=e}startPriceObserver(){let n=[],r=!1,i=0,s=()=>{i=0,!r&&this._currentDiscountedPrice&&(this._updateCurrentPrice(this._currentDiscountedPrice),this._currentDiscountedPrice!==this._currentOriginalPrice&&this._updateComparePrice(this._currentOriginalPrice),this._updateDiscountBadge(this._currentDiscountPercent))},a=new MutationObserver(()=>{if(r||!this._currentDiscountedPrice)return;let l=typeof performance<"u"&&performance.now?performance.now():Date.now();if(n.push(l),n.length>50&&(n=n.filter(c=>l-c<1e3)),n.length>50){r=!0,a.disconnect(),this._priceObserver=null,i&&(cancelAnimationFrame(i),i=0),this._currentDiscountedPrice=null,this._currentOriginalPrice=null,this._currentDiscountPercent=null,console.warn('[MoonBundle] Theme price sync disabled: detected a runaway update loop with the theme. Disable "Synchroniser le prix du th\xE8me" in the bundle settings to avoid this.');return}i||(i=requestAnimationFrame(s))});this.productForms.forEach(l=>{a.observe(l,{childList:!0,subtree:!0,characterData:!0})}),this._priceObserver=a}};customElements.define("moonbundle-component",dt);Ht({removeInstance:o=>A.removeInstance(o)});})();