PageSourceSearch

https://operadepot.com/cdn/shop/t/188/assets/app.js?v=29719832494942380221790943631

js operadepot.com collected 2026-10-02 13:23:22 UTC 300,997 bytes, 92 lines download raw bytes

1function src_default$1(Alpine2){let persist=()=>{let alias,storage;try{storage=localStorage}catch(e){console.error(e),console.warn("Alpine: $persist is using temporary storage since localStorage is unavailable.");let dummy=new Map;storage={getItem:dummy.get.bind(dummy),setItem:dummy.set.bind(dummy)}}return Alpine2.interceptor((initialValue,getter,setter,path,key)=>{let lookup=alias||`_x_${path}`,initial=storageHas(lookup,storage)?storageGet(lookup,storage):initialValue;return setter(initial),Alpine2.effect(()=>{let value=getter();storageSet(lookup,value,storage),setter(value)}),initial},func=>{func.as=key=>(alias=key,func),func.using=target=>(storage=target,func)})};Object.defineProperty(Alpine2,"$persist",{get:()=>persist()}),Alpine2.magic("persist",persist),Alpine2.persist=(key,{get,set},storage=localStorage)=>{let initial=storageHas(key,storage)?storageGet(key,storage):get();set(initial),Alpine2.effect(()=>{let value=get();storageSet(key,value,storage),set(value)})}}function storageHas(key,storage){return storage.getItem(key)!==null}function storageGet(key,storage){let value=storage.getItem(key,storage);if(value!==void 0)return JSON.parse(value)}function storageSet(key,value,storage){storage.setItem(key,JSON.stringify(value))}var module_default$1=src_default$1;function morph(from,toHtml,options){monkeyPatchDomSetAttributeToAllowAtSymbols();let toEl,key,lookahead,updating,updated,removing,removed,adding,added;function assignOptions(options2={}){let defaultGetKey=el=>el.getAttribute("key"),noop=()=>{};updating=options2.updating||noop,updated=options2.updated||noop,removing=options2.removing||noop,removed=options2.removed||noop,adding=options2.adding||noop,added=options2.added||noop,key=options2.key||defaultGetKey,lookahead=options2.lookahead||!1}function patch(from2,to){if(differentElementNamesTypesOrKeys(from2,to))return swapElements(from2,to);let updateChildrenOnly=!1;if(!shouldSkip(updating,from2,to,()=>updateChildrenOnly=!0)){if(from2.nodeType===1&&window.Alpine&&(window.Alpine.cloneNode(from2,to),from2._x_teleport&&to._x_teleport&&patch(from2._x_teleport,to._x_teleport)),textOrComment(to)){patchNodeValue(from2,to),updated(from2,to);return}updateChildrenOnly||patchAttributes(from2,to),updated(from2,to),patchChildren(from2,to)}}function differentElementNamesTypesOrKeys(from2,to){return from2.nodeType!=to.nodeType||from2.nodeName!=to.nodeName||getKey(from2)!=getKey(to)}function swapElements(from2,to){if(shouldSkip(removing,from2))return;let toCloned=to.cloneNode(!0);shouldSkip(adding,toCloned)||(from2.replaceWith(toCloned),removed(from2),added(toCloned))}function patchNodeValue(from2,to){let value=to.nodeValue;from2.nodeValue!==value&&(from2.nodeValue=value)}function patchAttributes(from2,to){if(from2._x_transitioning||from2._x_isShown&&!to._x_isShown||!from2._x_isShown&&to._x_isShown)return;let domAttributes=Array.from(from2.attributes),toAttributes=Array.from(to.attributes);for(let i=domAttributes.length-1;i>=0;i--){let name=domAttributes[i].name;to.hasAttribute(name)||from2.removeAttribute(name)}for(let i=toAttributes.length-1;i>=0;i--){let name=toAttributes[i].name,value=toAttributes[i].value;from2.getAttribute(name)!==value&&from2.setAttribute(name,value)}}function patchChildren(from2,to){let fromKeys=keyToMap(from2.children),fromKeyHoldovers={},currentTo=getFirstNode(to),currentFrom=getFirstNode(from2);for(;currentTo;){seedingMatchingId(currentTo,currentFrom);let toKey=getKey(currentTo),fromKey=getKey(currentFrom);if(!currentFrom)if(toKey&&fromKeyHoldovers[toKey]){let holdover=fromKeyHoldovers[toKey];from2.appendChild(holdover),currentFrom=holdover,fromKey=getKey(currentFrom)}else{if(!shouldSkip(adding,currentTo)){let clone=currentTo.cloneNode(!0);from2.appendChild(clone),added(clone)}currentTo=getNextSibling(to,currentTo);continue}let isIf=node=>node&&node.nodeType===8&&node.textContent==="[if BLOCK]><![endif]",isEnd=node=>node&&node.nodeType===8&&node.textContent==="[if ENDBLOCK]><![endif]";if(isIf(currentTo)&&isIf(currentFrom)){let nestedIfCount=0,fromBlockStart=currentFrom;for(;currentFrom;){let next=getNextSibling(from2,currentFrom);if(isIf(next))nestedIfCount++;else if(isEnd(next)&&nestedIfCount>0)nestedIfCount--;else if(isEnd(next)&&nestedIfCount===0){currentFrom=next;break}currentFrom=next}let fromBlockEnd=currentFrom;nestedIfCount=0;let toBlockStart=currentTo;for(;currentTo;){let next=getNextSibling(to,currentTo);if(isIf(next))nestedIfCount++;else if(isEnd(next)&&nestedIfCount>0)nestedIfCount--;else if(isEnd(next)&&nestedIfCount===0){currentTo=next;break}currentTo=next}let toBlockEnd=currentTo,fromBlock=new Block(fromBlockStart,fromBlockEnd),toBlock=new Block(toBlockStart,toBlockEnd);patchChildren(fromBlock,toBlock);continue}if(currentFrom.nodeType===1&&lookahead&&!currentFrom.isEqualNode(currentTo)){let nextToElementSibling=getNextSibling(to,currentTo),found=!1;for(;!found&&nextToElementSibling;)nextToElementSibling.nodeType===1&&currentFrom.isEqualNode(nextToElementSibling)&&(found=!0,currentFrom=addNodeBefore(from2,currentTo,currentFrom),fromKey=getKey(currentFrom)),nextToElementSibling=getNextSibling(to,nextToElementSibling)}if(toKey!==fromKey){if(!toKey&&fromKey){fromKeyHoldovers[fromKey]=currentFrom,currentFrom=addNodeBefore(from2,currentTo,currentFrom),fromKeyHoldovers[fromKey].remove(),currentFrom=getNextSibling(from2,currentFrom),currentTo=getNextSibling(to,currentTo);continue}if(toKey&&!fromKey&&fromKeys[toKey]&&(currentFrom.replaceWith(fromKeys[toKey]),currentFrom=fromKeys[toKey],fromKey=getKey(currentFrom)),toKey&&fromKey){let fromKeyNode=fromKeys[toKey];if(fromKeyNode)fromKeyHoldovers[fromKey]=currentFrom,currentFrom.replaceWith(fromKeyNode),currentFrom=fromKeyNode,fromKey=getKey(currentFrom);else{fromKeyHoldovers[fromKey]=currentFrom,currentFrom=addNodeBefore(from2,currentTo,currentFrom),fromKeyHoldovers[fromKey].remove(),currentFrom=getNextSibling(from2,currentFrom),currentTo=getNextSibling(to,currentTo);continue}}}let currentFromNext=currentFrom&&getNextSibling(from2,currentFrom);patch(currentFrom,currentTo),currentTo=currentTo&&getNextSibling(to,currentTo),currentFrom=currentFromNext}let removals=[];for(;currentFrom;)shouldSkip(removing,currentFrom)||removals.push(currentFrom),currentFrom=getNextSibling(from2,currentFrom);for(;removals.length;){let domForRemoval=removals.shift();domForRemoval.remove(),removed(domForRemoval)}}function getKey(el){return el&&el.nodeType===1&&key(el)}function keyToMap(els){let map={};for(let el of els){let theKey=getKey(el);
1theKey&&(map[theKey]=el)}return map}function addNodeBefore(parent,node,beforeMe){if(!shouldSkip(adding,node)){let clone=node.cloneNode(!0);return parent.insertBefore(clone,beforeMe),added(clone),clone}return node}return assignOptions(options),toEl=typeof toHtml=="string"?createElement(toHtml):toHtml,window.Alpine&&window.Alpine.closestDataStack&&!from._x_dataStack&&(toEl._x_dataStack=window.Alpine.closestDataStack(from),toEl._x_dataStack&&window.Alpine.cloneNode(from,toEl)),patch(from,toEl),toEl=void 0,from}morph.step=()=>{},morph.log=()=>{};function shouldSkip(hook,...args){let skip=!1;return hook(...args,()=>skip=!0),skip}var patched=!1;function createElement(html){const template=document.createElement("template");return template.innerHTML=html,template.content.firstElementChild}function textOrComment(el){return el.nodeType===3||el.nodeType===8}var Block=class{constructor(start,end){this.startComment=start,this.endComment=end}get children(){let children=[],currentNode=this.startComment.nextSibling;for(;currentNode&&currentNode!==this.endComment;)children.push(currentNode),currentNode=currentNode.nextSibling;return children}appendChild(child){this.endComment.before(child)}get firstChild(){let first=this.startComment.nextSibling;if(first!==this.endComment)return first}nextNode(reference){let next=reference.nextSibling;if(next!==this.endComment)return next}insertBefore(newNode,reference){return reference.before(newNode),newNode}};function getFirstNode(parent){return parent.firstChild}function getNextSibling(parent,reference){let next;return parent instanceof Block?next=parent.nextNode(reference):next=reference.nextSibling,next}function monkeyPatchDomSetAttributeToAllowAtSymbols(){if(patched)return;patched=!0;let original=Element.prototype.setAttribute,hostDiv=document.createElement("div");Element.prototype.setAttribute=function(name,value){if(!name.includes("@"))return original.call(this,name,value);hostDiv.innerHTML=`<span ${name}="${value}"></span>`;let attr=hostDiv.firstElementChild.getAttributeNode(name);hostDiv.firstElementChild.removeAttributeNode(attr),this.setAttributeNode(attr)}}function seedingMatchingId(to,from){let fromId=from&&from._x_bindings&&from._x_bindings.id;fromId&&to.setAttribute&&(to.setAttribute("id",fromId),to.id=fromId)}function src_default(Alpine2){Alpine2.morph=morph}var module_default=src_default;const ESC_KEY="Escape",TAB_KEY="Tab",ARROW_UP_KEY="ArrowUp",ARROW_DOWN_KEY="ArrowDown",ARROW_RIGHT_KEY="ArrowRight",ARROW_LEFT_KEY="ArrowLeft",isMobile=()=>window.matchMedia("(max-width: 767px)").matches;let globalTargetElement=null,isDocumentFreezed=!1;function onDocumentTouchMove(e){e.target instanceof HTMLInputElement&&e.target.type==="range"||e.preventDefault()}function onElementTouchMove(e){e.stopPropagation(),e.stopImmediatePropagation()}function onDocumentArrowKeys(e){(e.key===ARROW_DOWN_KEY||e.key===ARROW_UP_KEY)&&e.preventDefault()}function onElementArrowKeys(e){(e.key===ARROW_DOWN_KEY||e.key===ARROW_UP_KEY)&&(e.stopPropagation(),e.stopImmediatePropagation())}const freezeScroll=()=>{isDocumentFreezed||(document.addEventListener("touchmove",onDocumentTouchMove,{passive:!1}),document.addEventListener("wheel",onDocumentTouchMove,{passive:!1}),document.addEventListener("keydown",onDocumentArrowKeys,{passive:!1}),document.body.style.overflow="hidden",isDocumentFreezed=!0)},makeElementScrollable=targetElement=>{targetElement&&targetElement!==globalTargetElement&&(globalTargetElement=targetElement,globalTargetElement.addEventListener("keydown",onElementArrowKeys),globalTargetElement.addEventListener("touchmove",onElementTouchMove),globalTargetElement.addEventListener("wheel",onElementTouchMove),globalTargetElement.style.setProperty("-webkit-overflow-scrolling","touch"))},makeElementNotScrollable=()=>{globalTargetElement&&(globalTargetElement.removeEventListener("keydown",onElementArrowKeys),globalTargetElement.removeEventListener("touchmove",onElementTouchMove),globalTargetElement.removeEventListener("wheel",onElementTouchMove),globalTargetElement.style.removeProperty("-webkit-overflow-scrolling"),globalTargetElement=null)},unfreezeScroll=()=>{isDocumentFreezed&&(document.removeEventListener("keydown",onDocumentArrowKeys),document.removeEventListener("touchmove",onDocumentTouchMove),document.removeEventListener("wheel",onDocumentTouchMove),isDocumentFreezed=!1,document.body.style.overflow=""),makeElementNotScrollable()},doElementTransitionFromSrcToDest=async({srcElem,destElementCallback,transitionContainer,isCopyCssProperties=!1,cloneClass=""})=>{var _a;if(!srcElem||!destElementCallback)return;const{top:st,left:sl,width:sw,height:sh}=srcElem.getBoundingClientRect();if(sw<2||sh<2)return;const clonedElement=srcElem.cloneNode(!0);clonedElement.classList.add("element-transition-clone"),cloneClass&&clonedElement.classList.add(cloneClass);const skipEl=clonedElement.querySelector("[x-element-transition-skip]");if(isCopyCssProperties){const styles=window.getComputedStyle(srcElem);["font-family","font-size","font-weight","background","outline","border","color"].forEach(key=>{clonedElement.style.setProperty(key,styles.getPropertyValue(key))})}(_a=clonedElement.querySelector('[loading="lazy"]'))==null||_a.setAttribute("loading","eager"),clonedElement.style.top=`${st}px`,clonedElement.style.left=`${sl}px`,clonedElement.style.width=`${sw}px`,clonedElement.style.height=`${sh}px`,clonedElement.style.position="absolute",clonedElement.style.margin="0",clonedElement.setAttribute("x-ignore",""),transitionContainer.appendChild(clonedElement),await new Promise((resolve,reject)=>{let maxTries=30;const interval=setInterval(()=>{maxTries<=0&&(clearInterval(interval),reject()),destElementCallback()&&(clearInterval(interval),resolve()),maxTries-=1},100)});const destEl=destElementCallback(),{top:tt,left:tl,width:tw,height:th}=destEl.getBoundingClientRect();if(tw<2||th<2){clonedElement.remove();return}if(skipEl){skipEl.style.transform=`scale(${sw/tw}, ${sh/th})`,skipEl.style.bottom=`${8/(th/sh)}
1px`;const styles=skipEl.getAttribute("x-element-transition-skip");if(styles){const styleRules=JSON.parse(styles);Object.keys(styleRules).forEach(key=>{skipEl.style[key]=styleRules[key]})}}clonedElement.style.transform=`translate3d(${tl-sl}px, ${tt-st}px, 0) scale(${tw/sw}, ${th/sh})`,clonedElement.style.setProperty("border-radius",window.getComputedStyle(destEl).borderRadius,"important"),await new Promise(resolve=>{clonedElement.addEventListener("transitionend",()=>{resolve()},{once:!0})})},_handleInputValue=(from,to)=>{!(from instanceof HTMLInputElement)||!(to instanceof HTMLInputElement)||(from.type==="checkbox"||from.type==="radio")&&from.checked!==to.checked&&(from.checked=to.checked)},_handleTemplates=(from,to)=>{if(!(from instanceof HTMLTemplateElement)||!(to instanceof HTMLTemplateElement))return;const newNodes=Array.from(to.content.children);from.content.replaceChildren(...newNodes)},replaceElement=(from,to,resetInputValues)=>{!from||!to||Alpine.morph(from,to,{updating(from2,to2,_childrenOnly,skip){if(from2 instanceof Element&&from2.hasAttribute("x-morph-ignore")){skip();return}if(from2 instanceof HTMLImageElement&&to2 instanceof HTMLImageElement){const fromSrc=from2.src.replace(/^https?:\/\//,"//"),toSrc=to2.src.replace(/^https?:\/\//,"//");if(fromSrc===toSrc&&from2.complete){skip();return}}},updated(from2,to2){_handleTemplates(from2,to2),resetInputValues&&_handleInputValue(from2,to2)}})};var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x.default:x}var nprogress={exports:{}};/* NProgress, (c) 2013, 2014 Rico Sta. Cruz - http://ricostacruz.com/nprogress
2 * @license MIT */(function(module,exports){(function(root,factory){module.exports=factory()})(commonjsGlobal,function(){var NProgress={};NProgress.version="0.2.0";var Settings=NProgress.settings={minimum:.08,easing:"ease",positionUsing:"",speed:200,trickle:!0,trickleRate:.02,trickleSpeed:800,showSpinner:!0,barSelector:'[role="bar"]',spinnerSelector:'[role="spinner"]',parent:"body",template:'<div class="bar" role="bar"><div class="peg"></div></div><div class="spinner" role="spinner"><div class="spinner-icon"></div></div>'};NProgress.configure=function(options){var key,value;for(key in options)value=options[key],value!==void 0&&options.hasOwnProperty(key)&&(Settings[key]=value);return this},NProgress.status=null,NProgress.set=function(n){var started=NProgress.isStarted();n=clamp(n,Settings.minimum,1),NProgress.status=n===1?null:n;var progress=NProgress.render(!started),bar=progress.querySelector(Settings.barSelector),speed=Settings.speed,ease=Settings.easing;return progress.offsetWidth,queue(function(next){Settings.positionUsing===""&&(Settings.positionUsing=NProgress.getPositioningCSS()),css(bar,barPositionCSS(n,speed,ease)),n===1?(css(progress,{transition:"none",opacity:1}),progress.offsetWidth,setTimeout(function(){css(progress,{transition:"all "+speed+"ms linear",opacity:0}),setTimeout(function(){NProgress.remove(),next()},speed)},speed)):setTimeout(next,speed)}),this},NProgress.isStarted=function(){return typeof NProgress.status=="number"},NProgress.start=function(){NProgress.status||NProgress.set(0);var work=function(){setTimeout(function(){NProgress.status&&(NProgress.trickle(),work())},Settings.trickleSpeed)};return Settings.trickle&&work(),this},NProgress.done=function(force){return!force&&!NProgress.status?this:NProgress.inc(.3+.5*Math.random()).set(1)},NProgress.inc=function(amount){var n=NProgress.status;return n?(typeof amount!="number"&&(amount=(1-n)*clamp(Math.random()*n,.1,.95)),n=clamp(n+amount,0,.994),NProgress.set(n)):NProgress.start()},NProgress.trickle=function(){return NProgress.inc(Math.random()*Settings.trickleRate)},(function(){var initial=0,current=0;NProgress.promise=function($promise){return!$promise||$promise.state()==="resolved"?this:(current===0&&NProgress.start(),initial++,current++,$promise.always(function(){current--,current===0?(initial=0,NProgress.done()):NProgress.set((initial-current)/initial)}),this)}})(),NProgress.render=function(fromStart){if(NProgress.isRendered())return document.getElementById("nprogress");addClass(document.documentElement,"nprogress-busy");var progress=document.createElement("div");progress.id="nprogress",progress.innerHTML=Settings.template;var bar=progress.querySelector(Settings.barSelector),perc=fromStart?"-100":toBarPerc(NProgress.status||0),parent=document.querySelector(Settings.parent),spinner;return css(bar,{transition:"all 0 linear",transform:"translate3d("+perc+"%,0,0)"}),Settings.showSpinner||(spinner=progress.querySelector(Settings.spinnerSelector),spinner&&removeElement(spinner)),parent!=document.body&&addClass(parent,"nprogress-custom-parent"),parent.appendChild(progress),progress},NProgress.remove=function(){removeClass(document.documentElement,"nprogress-busy"),removeClass(document.querySelector(Settings.parent),"nprogress-custom-parent");var progress=document.getElementById("nprogress");progress&&removeElement(progress)},NProgress.isRendered=function(){return!!document.getElementById("nprogress")},NProgress.getPositioningCSS=function(){var bodyStyle=document.body.style,vendorPrefix="WebkitTransform"in bodyStyle?"Webkit":"MozTransform"in bodyStyle?"Moz":"msTransform"in bodyStyle?"ms":"OTransform"in bodyStyle?"O":"";return vendorPrefix+"Perspective"in bodyStyle?"translate3d":vendorPrefix+"Transform"in bodyStyle?"translate":"margin"};function clamp(n,min,max){return n<min?min:n>max?max:n}function toBarPerc(n){return(-1+n)*100}function barPositionCSS(n,speed,ease){var barCSS;return Settings.positionUsing==="translate3d"?barCSS={transform:"translate3d("+toBarPerc(n)+"%,0,0)"}:Settings.positionUsing==="translate"?barCSS={transform:"translate("+toBarPerc(n)+"%,0)"}:barCSS={"margin-left":toBarPerc(n)+"%"},barCSS.transition="all "+speed+"ms "+ease,barCSS}var queue=(function(){var pending=[];function next(){var fn=pending.shift();fn&&fn(next)}return function(fn){pending.push(fn),pending.length==1&&next()}})(),css=(function(){var cssPrefixes=["Webkit","O","Moz","ms"],cssProps={};function camelCase(string){return string.replace(/^-ms-/,"ms-").replace(/-([\da-z])/gi,function(match,letter){return letter.toUpperCase()})}function getVendorProp(name){var style=document.body.style;if(name in style)return name;for(var i=cssPrefixes.length,capName=name.charAt(0).toUpperCase()+name.slice(1),vendorName;i--;)if(vendorName=cssPrefixes[i]+capName,vendorName in style)return vendorName;return name}function getStyleProp(name){return name=camelCase(name),cssProps[name]||(cssProps[name]=getVendorProp(name))}function applyCss(element,prop,value){prop=getStyleProp(prop),element.style[prop]=value}return function(element,properties){var args=arguments,prop,value;if(args.length==2)for(prop in properties)value=properties[prop],value!==void 0&&properties.hasOwnProperty(prop)&&applyCss(element,prop,value);else applyCss(element,args[1],args[2])}})();function hasClass(element,name){var list=typeof element=="string"?element:classList(element);return list.indexOf(" "+name+" ")>=0}function addClass(element,name){var oldList=classList(element),newList=oldList+name;hasClass(oldList,name)||(element.className=newList.substring(1))}function removeClass(element,name){var oldList=classList(element),newList;hasClass(element,name)&&(newList=oldList.replace(" "+name+" "," "),element.className=newList.substring(1,newList.length-1))}function classList(element){return(" "+(element.className||"")+" ").replace(/\s+/gi," ")}function removeElement(element){element&&element.parentNode&&element.parentNode.removeChild(element)}return NProgress})})(nprogress);var nprogressExports=nprogress.exports;const nProgress=getDefaultExportFromCjs(nprogressExports);nProgress.configure({showSpinner:!1});let lastMainContentUpdateUrl=window.location.href;const cachedResponses={},isExternalURL=url=>url.startsWith("//")?new URL(location.protocol+url).origin!==location.origin:url.includes("://")?new URL(url).origin!==location.origin:!1,TransitionStore={isTransitioning:!1,pageData:void 0,pageType:void 0,isA
2nimating:!1,isPreviewAnimating:!1,originalFocusableEl:null,__activeTransitionAreaRef:null,isPreviewActive:!1,async _doTransition(areaId,callback,sourceAreaEl=null){if(!Alpine.store("main").isMobile||Alpine.store("main").isReducedMotion){callback();return}const transitionContainerRef=document.querySelector("[x-element-transition-wrapper]");if(!transitionContainerRef){console.log("transition container not found"),callback();return}freezeScroll(),this.__activeTransitionAreaRef=areaId;const areaElement=sourceAreaEl||document.querySelector(`[x-element-transition-area="${areaId}"]`);if(!areaElement){unfreezeScroll(),this.__activeTransitionAreaRef=null,callback();return}const srcElements=Object.fromEntries([...areaElement.querySelectorAll("[x-element-transition-src]")].map(srcElement=>[srcElement.getAttribute("x-element-transition-src"),srcElement]));if(!srcElements||Object.entries(srcElements).length===0){unfreezeScroll(),this.__activeTransitionAreaRef=null,callback();return}this.isTransitioning=!0,await new Promise(resolve=>{transitionContainerRef.addEventListener("transitionstart",()=>{resolve()},{once:!0})});const currentPage=window.location.href,animationPromise=Promise.all(Object.entries(srcElements).map(([key,srcElem])=>doElementTransitionFromSrcToDest({srcElem,destElementCallback:()=>{if(currentPage===window.location.href)return null;const destEl=document.querySelector(`[x-element-transition-dest="${key}"]`);return destEl||null},transitionContainer:transitionContainerRef,isCopyCssProperties:!0,cloneClass:areaId&&String(areaId).startsWith("p-")?"element-transition-clone--product":"element-transition-clone--plain"}).catch(()=>{})));for(await new Promise(resolve=>{transitionContainerRef.addEventListener("transitionend",()=>{resolve()},{once:!0})}),callback(),await animationPromise,this.isTransitioning=!1,await new Promise(resolve=>{transitionContainerRef.addEventListener("transitionstart",()=>{resolve()},{once:!0})}),await new Promise(resolve=>{transitionContainerRef.addEventListener("transitionend",()=>{resolve()},{once:!0})});transitionContainerRef.firstChild;)transitionContainerRef.removeChild(transitionContainerRef.firstChild);this.__activeTransitionAreaRef=null,unfreezeScroll()},_showTransitionFallback(isPreview){const target=isPreview?document.getElementById("PreviewContent"):document.getElementById("MainContent"),template=document.querySelector(`[x-fallback-template-type="${this.pageType}"]`);if(!template)return;const content=template.innerHTML;if(target){target.innerHTML=content;const title=this.pageData&&typeof this.pageData.title=="string"?this.pageData.title:"";target.querySelectorAll("[data-transition-title]").forEach(node=>{node.textContent=title})}isPreview||window.scrollTo(0,0)},_clearFallback(){this.pageType=void 0}},replaceMeta=rawContent=>{const regex=/<!-- page-meta -->([\s\S]*?)<!-- end-page-meta -->
2/,content=rawContent.match(regex),newContent=content?content[0]:"";if(!newContent)return;const metaNodes=[];let foundStart=!1,foundEnd=!1,endComment=null;for(let i=0;i<document.head.childNodes.length;i++){const node=document.head.childNodes[i];if(node.nodeType===8){if(node.nodeValue===" page-meta "){foundStart=!0;continue}if(node.nodeValue===" end-page-meta "){endComment=node,foundEnd=!0;break}}foundStart&&!foundEnd&&metaNodes.push(node)}if(!endComment)return;metaNodes.forEach(node=>node.remove());const newMetaContent=newContent.replace("<!-- page-meta -->","<head>").replace("<!-- end-page-meta -->","</head>");[...new DOMParser().parseFromString(newMetaContent,"text/html").head.childNodes].forEach(node=>{document.head.insertBefore(node,endComment)})},morphContent=(rawContent,lookup,target)=>{const regex=new RegExp(`<!-- ${lookup} -->([\\s\\S]*?)<!-- end-${lookup} -->`,"g"),content=rawContent.match(regex),newContent=content?content[0]:"";replaceElement(target,newContent)},replaceContent=(rawContent,lookup,target)=>{const regex=new RegExp(`<!-- ${lookup} -->([\\s\\S]*?)<!-- end-${lookup} -->
2`,"g"),content=rawContent.match(regex),newContent=content?content[0]:"";target.innerHTML=newContent},replaceMainContent=rawContent=>{lastMainContentUpdateUrl=window.location.href,console.log("[OD transition] replaceMainContent",{url:window.location.pathname+window.location.search}),replaceMeta(rawContent);const result=morphContent(rawContent,"main-content",document.getElementById("MainContent"));return document.dispatchEvent(new CustomEvent("od:main-content-replaced",{detail:{url:window.location.pathname+window.location.search}})),result},replacePreviewContent=rawContent=>(replaceMeta(rawContent),replaceContent(rawContent,"preview-content",document.getElementById("PreviewContent"))),pushStateAndNotify=(...args)=>{if(window.Shopify.designMode)window.location.replace(args[2]);else{history.pushState(...args);const pushStateEvent=new CustomEvent("pushstate",{detail:{state:args[0],url:args[2]}});window.dispatchEvent(pushStateEvent)}},fetchPage=url=>(enableFadeInImages(),fetch(url).then(res=>{if(res.ok||res.status===404)return res.text();throw new Error("Failed to get page for transition")})),enableFadeInImages=()=>{document.body.classList.remove("[&_.no-fade]:opacity-100"),document.body.classList.remove("max-md:[&_.card-product:nth-child(-n+2)_.no-fade]:opacity-100"),document.body.classList.remove("md:[&_.card-product_.no-fade]:opacity-100")},cachePage=(url,html)=>{cachedResponses[url]=html},fetchAndCachePage=async url=>{const html=await fetchPage(url);return cachePage(url,html),html},preloadCategoryTransitionImage=options=>{if(options?.type!=="category")return;const img=options.data&&typeof options.data.img=="string"?options.data.img:"";if(!img)return;const preloadedImage=new Image;preloadedImage.src=img},navigateWithTransition=(nextUrl,options={})=>{Alpine.store("transition").isAnimating=!1,Alpine.store("transition").isPreviewAnimating=!1,console.log("TRANSITION DATA:",{type:options.type,data:options.data});const currentUrl=window.location.pathname+window.location.search,scrollPosition=window.scrollY;if(currentUrl===nextUrl){Alpine.store("popup").hideAllPopups(),Alpine.store("resizable").hideAll(),window.scrollTo(0,0);return}preloadCategoryTransitionImage(options),nProgress.start();const isPreview=!!options.preview&&!Alpine.store("main").isMobile,isAnimating=!!options.animate,navigate=async()=>{options.type&&options.data&&(isPreview?(Alpine.store("transition").isPreviewAnimating=isAnimating,Alpine.store("transition").originalFocusableEl=options.target):Alpine.store("transition").isAnimating=isAnimating,Alpine.store("transition").pageType=options.type,Alpine.store("transition").pageData=options.data,Alpine.store("transition")._showTransitionFallback(isPreview)),Alpine.nextTick(async()=>{Alpine.store("popup").hideAllPopups(),Alpine.store("resizable").hideAll(),history.replaceState({...history.state,scrollPosition},""),pushStateAndNotify({isPreview},"",nextUrl);const html=await fetchAndCachePage(nextUrl);isPreview?replacePreviewContent(html):(replaceMainContent(html),window.scrollTo(0,0)),Alpine.store("transition")._clearFallback(),nProgress.done()})};options.areaId||options.sourceAreaEl?Alpine.store("transition")._doTransition(options.areaId,navigate,options.sourceAreaEl||null):navigate()},prefetchedLinks=new Set,prefetchLink=link=>{const prefetchLink2=document.createElement("link");prefetchLink2.rel="prefetch",prefetchLink2.href=link,prefetchLink2.as="document",document.head.appendChild(prefetchLink2),prefetchedLinks.add(link)},prefetchObserver=new IntersectionObserver(entries=>{entries.forEach(entry=>{if(!entry.isIntersecting)return;const element=entry.target,href=typeof element._odResolveTransitionHref=="function"?element._odResolveTransitionHref():element.getAttribute("href");if(!href)return;let timeoutId=element.timeoutId;entry.isIntersecting&&!timeoutId?element.timeoutId=setTimeout(()=>{prefetchedLinks.has(href)||(prefetchLink(href),prefetchObserver.unobserve(element))},200):!entry.isIntersecting&&timeoutId&&(clearTimeout(timeoutId),element.timeoutId=null)})},{threshold:.1});function TransitionPlugin(Alpine2){const normalizeProductTransitionLink=(el,link)=>
2{if(!el||!link)return link;try{const parsed=new URL(link,window.location.origin);if(!(parsed.pathname.includes("/collections/")||parsed.searchParams.has("_pos")||parsed.searchParams.has("_psq")||parsed.searchParams.has("_ss")||parsed.searchParams.has("_v")))return link;const card=el.closest("[data-product-card]"),handle=card?.getAttribute("data-product-handle");if(!handle)return link;const variant=parsed.searchParams.get("variant"),canonicalPath=`/products/${handle}`;return variant?`${canonicalPath}?variant=${variant}`:canonicalPath}catch{return link}};if(Alpine2.store("transition",TransitionStore),Alpine2.directive("element-transition-trigger",(el,{value,modifiers,expression},{evaluate,cleanup})=>{if(el._odElementTransitionCleanup&&el._odElementTransitionCleanup(),modifiers.includes("desktop")&&Alpine2.store("main").isMobile)return;const transitionAreaEl=el.closest("[x-element-transition-area]"),areaId=transitionAreaEl?transitionAreaEl.getAttribute("x-element-transition-area"):null,isTargetBlank=el.getAttribute("target")==="_blank",isMobile2=Alpine2.store("main").isMobile,getLink=()=>{const hrefAttr=el.getAttribute("href");if(hrefAttr)return hrefAttr;if(el instanceof HTMLAnchorElement){const hrefProp=el.href;if(hrefProp&&hrefProp!==window.location.href)return hrefProp}return""};if(el._odResolveTransitionHref=getLink,isTargetBlank)return;const onHover=()=>{const link=getLink();!link||isExternalURL(link)||prefetchedLinks.has(link)||prefetchLink(link)},onClick=e=>{const link=getLink();if(!link||isExternalURL(link))return;console.log("[OD transition] trigger click",{type:value,link,areaId,isMobile:isMobile2,hasHrefAttr:el.hasAttribute("href"),hrefAttr:el.getAttribute("href")});const shouldBypassMobileAreaTransition=isMobile2&&value==="product"&&!!el.closest("[data-dynamic-card]");if(window.navigationType==="MPA"){const areaElement=document.querySelector(`[x-element-transition-area="${areaId}"]`);if(!areaElement||!isMobile2)return;const srcElement=areaElement.querySelector("[x-element-transition-src]"),key=srcElement?.getAttribute("x-element-transition-src");srcElement&&(sessionStorage.setItem("elementRect",JSON.stringify(srcElement.getBoundingClientRect())),sessionStorage.setItem("elementHtml",srcElement.innerHTML.replace('loading="lazy"','loading="eager"')),sessionStorage.setItem("destKey",key||""))}else{e.preventDefault(),e.stopPropagation();const normalizedLink=value==="product"?normalizeProductTransitionLink(el,link||""):link||"";navigateWithTransition(normalizedLink,{preview:modifiers.includes("preview"),animate:modifiers.includes("animate"),type:value,data:expression?evaluate(expression):void 0,areaId:shouldBypassMobileAreaTransition?void 0:areaId||void 0,sourceAreaEl:shouldBypassMobileAreaTransition?void 0:transitionAreaEl||void 0,target:e.target})}};el.addEventListener("click",onClick),window.navigationType==="MPA"&&(isMobile2?prefetchObserver.observe(el):el.addEventListener("mouseover",onHover)),el._odElementTransitionCleanup=()=>{el.removeEventListener("click",onClick),window.navigationType==="MPA"&&(isMobile2?prefetchObserver.unobserve(el):el.removeEventListener("mouseover",onHover)),delete el._odResolveTransitionHref,delete el._odElementTransitionCleanup},cleanup(()=>{el._odElementTransitionCleanup&&el._odElementTransitionCleanup()})}),window.navigationType==="MPA")window.addEventListener("pageshow",event=>{event.persisted&&prefetchedLinks.forEach(link=>prefetchLink(link))});else{let lastPopStateUrl=window.location.href;window.addEventListener("popstate",async event=>{var _a,_b,_c,_d;if(Alpine2.store("transition").isAnimating=!1,Alpine2.store("transition").isPreviewAnimating=!1,history.scrollRestoration="manual",window.location.href===lastMainContentUpdateUrl)return;const currentPopStateUrl=window.location.href;lastPopStateUrl=window.location.href,Alpine2.store("popup").hideAllPopups(),Alpine2.store("resizable").hideAll(),nProgress.start();const{pathname,search}=new URL(window.location.href),cachedHtml=cachedResponses[pathname+search];if(cachedHtml){if((_a=event.state)!=null&&_a.isPreview)replacePreviewContent(cachedHtml);else{const currentUrl=pathname+search,shouldDeferCollectionRestore=!!(window.__odCollectionRestore&&window.__odCollectionRestore.shouldDeferScrollRestore(currentUrl));shouldDeferCollectionRestore&&(window.__odCollectionRestore.setPending(currentUrl,((_b=event.state)==null?void 0:_b.scrollPosition)||0),window.__odCollectionRestore.beginDeferredReveal(currentUrl)),replaceMainContent(cachedHtml),!shouldDeferCollectionRestore&&((_b=event.state)!=null&&_b.scrollPosition)&&window.scrollTo({top:event.state.scrollPosition,behavior:"instant"})}nProgress.done();return}if(lastPopStateUrl!==currentPopStateUrl)return;const html=await fetchAndCachePage(window.location.pathname+window.location.search);if(lastPopStateUrl===currentPopStateUrl){if((_c=event.state)!=null&&_c.isPreview)replacePreviewContent(html);else{const currentUrl=window.location.pathname+window.location.search,shouldDeferCollectionRestore=!!(window.__odCollectionRestore&&window.__odCollectionRestore.shouldDeferScrollRestore(currentUrl));shouldDeferCollectionRestore&&(window.__odCollectionRestore.setPending(currentUrl,((_d=event.state)==null?void 0:_d.scrollPosition)||0),window.__odCollectionRestore.beginDeferredReveal(currentUrl)),replaceMainContent(html),!shouldDeferCollectionRestore&&((_d=event.state)!=null&&_d.scrollPosition)&&window.scrollTo({top:event.state.scrollPosition,behavior:"instant"})}nProgress.done()}})}}function ElementIntersection(Alpine2){Alpine2.directive("intersect",Alpine2.skipDuringClone((element,{value,expression,modifiers},{evaluateLater,cleanup,effect})=>{const evaluate=evaluateLater(expression),observerOptions={rootMargin:getRootMargin(modifiers),threshold:getThreshold(modifiers)||1e-6};let isVisibleRef=null,observerTimeoutRef=null,observer=new IntersectionObserver(entries=>
2{entries.forEach(entry=>{const newIsVisible=entry.isIntersecting;isVisibleRef!==newIsVisible&&(observerTimeoutRef&&clearTimeout(observerTimeoutRef),isVisibleRef=newIsVisible,element._x_visible=newIsVisible,newIsVisible!==(value==="leave")&&(observerTimeoutRef=setTimeout(()=>{isVisibleRef=newIsVisible,evaluate()},getDelay(modifiers)),modifiers.includes("once")&&observer.disconnect()))})},observerOptions),prevIsFocused=Alpine2.store("popup").isCurrentPopupFocused;effect(()=>{const isFocused=Alpine2.store("popup").isCurrentPopupFocused;prevIsFocused!==isFocused&&(prevIsFocused=isFocused,observer.unobserve(element),observerTimeoutRef&&clearTimeout(observerTimeoutRef),observerTimeoutRef=setTimeout(()=>{observerTimeoutRef=null,observer.observe(element)},getDelay(modifiers)))}),observer.observe(element),cleanup(()=>{observer.disconnect()})}))}function getThreshold(modifiers){if(modifiers.includes("full"))return .99;if(modifiers.includes("half"))return .5;if(!modifiers.includes("threshold"))return 0;let threshold=modifiers[modifiers.indexOf("threshold")+1];return threshold==="100"?1:threshold==="0"?0:+`.${threshold}`}function getLengthValue(rawValue){let match=rawValue.match(/^(-?[0-9]+)(px|%)?$/);return match?match[1]+(match[2]||"px"):void 0}function getRootMargin(modifiers){const key="margin",fallback="0px 0px 0px 0px",index=modifiers.indexOf(key);if(index===-1)return fallback;let values=[];for(let i=1;i<5;i++)values.push(getLengthValue(String(modifiers[index+i])||""));return values=values.filter(v=>v!==void 0),values.length?values.join(" ").trim():fallback}function getDelay(modifiers){if(!modifiers.includes("delay"))return 300;let delay=modifiers[modifiers.indexOf("delay")+1];return Number(delay)}const SELECTOR_LIST="a, button, textarea, input, select, [role=radio][aria-checked]";let trapInitial=null,trapStart=null,trapEnd=null,trapEls=[];const RESIZABLE_ANIMATION_DURATION=300;function Accessibility(Alpine2){Alpine2.directive("a11y-trap",(el,{expression},{evaluateLater,effect,cleanup})=>{const getIsTrapped=evaluateLater(expression),onKeyDown=async e=>{const focusEls=Array.from(el.querySelectorAll(SELECTOR_LIST)).filter(element=>window.getComputedStyle(element).display!=="none"),allFocusEls=trapEls.concat(focusEls),first=trapStart||allFocusEls[0],last=trapEnd||allFocusEls[allFocusEls.length-1];if(e.key===TAB_KEY){if(e.shiftKey){e.target===first&&(last?.focus(),e.preventDefault());return}e.target===last&&(first?.focus(),e.preventDefault())}},trapFocus=()=>{document.addEventListener("keydown",onKeyDown),el.setAttribute("role","dialog"),el.setAttribute("aria-modal","true");const labelRef=el.querySelector("h1, h2, h3, h4, h5, p");labelRef&&(labelRef.id="popup-label",el.setAttribute("aria-labelledby","popup-label"));const firstVisibleEl=Array.from(el.querySelectorAll(SELECTOR_LIST)).find(element=>window.getComputedStyle(element).display!=="none");if(isMobile())return;const first=trapStart||trapInitial||firstVisibleEl;first?.focus()};effect(()=>{getIsTrapped(trapped=>{if(!trapped)return;setTimeout(trapFocus,RESIZABLE_ANIMATION_DURATION);const observer=new MutationObserver(()=>{el.querySelectorAll(SELECTOR_LIST).length&&(setTimeout(trapFocus,RESIZABLE_ANIMATION_DURATION),observer.disconnect())});observer.observe(el,{subtree:!0,childList:!0})})}),cleanup(()=>{document.removeEventListener("keydown",onKeyDown),el.removeAttribute("role"),el.removeAttribute("aria-modal"),el.removeAttribute("aria-labelledby")})}),Alpine2.directive("a11y-trap-target",(el,{modifiers,expression},{evaluateLater,effect,cleanup})=>{const getIsTrapped=evaluateLater(expression);effect(()=>{getIsTrapped(trapped=>{trapped?modifiers.includes("start")?trapStart=el:modifiers.includes("end")?trapEnd=el:modifiers.includes("initial")&&(trapInitial=el):modifiers.includes("start")&&trapStart===el?trapStart=null:modifiers.includes("end")&&trapEnd===el?trapEnd=null:modifiers.includes("initial")&&trapInitial===el&&(trapInitial=null)})}),cleanup(()=>{modifiers.includes("start")?trapStart=null:modifiers.includes("end")?trapEnd=null:modifiers.includes("initial")&&(trapInitial=null)})}),Alpine2.directive("a11y-trap-element",(el,{expression},{evaluateLater,effect,cleanup})=>{const getIsActive=evaluateLater(expression);effect(()=>{getIsActive(active=>{active?trapEls.includes(el)||trapEls.push(el):trapEls.includes(el)&&trapEls.splice(trapEls.indexOf(el),1)})}),cleanup(()=>{})}),Alpine2.directive("a11y-radio",(el,_,{cleanup})=>{const onKeyDown=e=>{if(!e.target||!(e.target instanceof HTMLElement)||e.target.role!=="radio")throw"x-a11y-radio can only be used on elements of 'radio' role";if(e.key===" "){e.preventDefault();return}const isNext=e.key==="ArrowDown"||e.key==="ArrowRight",isPrev=e.key==="ArrowUp"||e.key==="ArrowLeft";if(!isNext&&!isPrev)return;e.preventDefault();const radioGroup=e.target.closest("[role=radiogroup]");if(!radioGroup)throw"x-a11y-radio can only be used inside an element with 'radiogroup' role";const radios=[...radioGroup.querySelectorAll("[role=radio]")],currentRadio=e.target,currentIndex=radios.indexOf(currentRadio),nextIndex=currentIndex===radios.length-1?0:currentIndex+1,prevIndex=currentIndex===0?radios.length-1:currentIndex-1,newRadio=radios[isNext?nextIndex:prevIndex];newRadio.click(),newRadio.focus()};el.addEventListener("keydown",onKeyDown),cleanup(()=>{el.removeEventListener("keydown",onKeyDown)})})}const appendPaginationContent=rawContent=>{const regex=/<!-- pagination-content -->([\s\S]*?)<!-- end-pagination-content -->/,match=rawContent.match(regex),newContent=match?match[1]:"",el=document.querySelector("[data-content-wrapper]"),newElements=document.createElement("div");if(newElements.innerHTML=newContent,el){const appendedChildren=Array.from(newElements.children),fragment=document.createDocumentFragment();
2appendedChildren.forEach(child=>{child.setAttribute("data-dynamic-card","true"),fragment.appendChild(child)}),el.appendChild(fragment);const root=el.closest("#ProductGridContainer");root&&document.dispatchEvent(new CustomEvent("od:collection:grid-updated",{detail:{root,reason:"pagination"}}))}};function Pagination(Alpine2){let isPaginating=!1;const getPageFromLocation=()=>parseInt(new URLSearchParams(window.location.search).get("page")||"1",10),getCurrentPage=el=>parseInt(el.dataset.currentPage||String(getPageFromLocation()),10);Alpine2.directive("pagination-trigger",(el,{expression},{evaluate,cleanup})=>{const{lastPage}=evaluate(expression);el.dataset.currentPage=el.dataset.currentPage||String(getPageFromLocation());const onClick=async e=>{if(e.preventDefault(),e.stopPropagation(),enableFadeInImages(),isPaginating)return;const currentPage=getCurrentPage(el);isPaginating=!0,el.ariaBusy="1";try{if(currentPage<lastPage){const nextPage=currentPage+1,params=new URLSearchParams(window.location.search);params.set("page",String(nextPage));const nextUrl=`${window.location.pathname}?${params.toString()}`,html=await fetchPage(nextUrl);appendPaginationContent(html),cachePage(nextUrl,html),el.dataset.currentPage=String(nextPage),document.dispatchEvent(new CustomEvent("pagination:updated",{detail:{currentPage:nextPage,lastPage}})),nextPage>=lastPage&&(el.closest("[data-auto-pagination-trigger-wrap]")||el).remove()}}catch(error){console.error("Pagination error:",error)}finally{isPaginating=!1,el.ariaBusy="0"}};el.addEventListener("click",onClick),cleanup(()=>{el.removeEventListener("click",onClick),isPaginating=!1,el.dataset.currentPage=String(getPageFromLocation())})})}function Portal(Alpine2){const placeInDom=(clone,target)=>{target?.appendChild(clone)},getAllClones=()=>Array.from(document.querySelectorAll("[data-from-portal]")),getAllTemplates=()=>Array.from(document.querySelectorAll("[data-portal]")),getCurrentCloneFromTemplate=template=>getAllClones().find(clone=>clone._x_teleportBack===template),getTarget=template=>{const expression=template.getAttribute("x-portal")||"";let rawTarget=Alpine2.evaluate(template,expression);if(!rawTarget)throw"No element provided to x-portal...";return rawTarget instanceof HTMLElement||console.warn(`Cannot find x-portal target for selector: "${expression}"`),rawTarget},initClone=(clone,targetEl,templateEl)=>{try{templateEl._x_teleport=clone,clone._x_teleportBack=templateEl,clone._x_teleportTarget=targetEl,clone.setAttribute("data-from-portal","true"),templateEl.setAttribute("data-portal","true"),templateEl._x_forwardEvents&&templateEl._x_forwardEvents.forEach(eventName=>{clone.addEventListener(eventName,e=>{e.stopPropagation(),templateEl.dispatchEvent(new e.constructor(e.type,e))})}),Alpine2.addScopeToNode(clone,{},templateEl),Alpine2.mutateDom(()=>{placeInDom(clone,targetEl),Alpine2.initTree(clone),clone._x_ignore=!0})}catch{console.log("Failed to init clone for",templateEl),console.trace()}},createPortal=templateEl=>{const targetEl=getTarget(templateEl),oldClone=getCurrentCloneFromTemplate(templateEl);if(oldClone){teleportClone(templateEl,oldClone);return}const clone=templateEl.content.cloneNode(!0).firstElementChild;initClone(clone,targetEl,templateEl)};function cloneWithCleanup(originalElement){const doCleanup=source=>{const cSource=source;cSource._x_currentIfEl&&cSource._x_currentIfEl.remove(),cSource._x_lookup&&Object.values(cSource._x_lookup).forEach(element=>{element.remove()})},recursivelyCloneChildren=originalParent=>{const originalChildren=originalParent.children;for(let i=0;i<originalChildren.length;i++)doCleanup(originalChildren[i]),recursivelyCloneChildren(originalChildren[i])};return recursivelyCloneChildren(originalElement),originalElement.cloneNode(!0)}const teleportClone=(templateEl,oldClone)=>{const newClone=cloneWithCleanup(oldClone),targetEl=getTarget(templateEl);initClone(newClone,targetEl,templateEl)};new MutationObserver(()=>{getAllClones().forEach(clone=>{const templateEl=clone._x_teleportBack;if(templateEl){const newTeleportTarget=Alpine2.evaluate(templateEl,templateEl.getAttribute("x-portal")||"");if(!document.body.contains(templateEl)){clone.remove();return}if(newTeleportTarget!==clone._x_teleportTarget){clone.remove();return}}else{clone.remove();return}document.body.contains(clone)||clone.remove()}
2),getAllTemplates().forEach(templateEl=>{const targetEl=templateEl._x_teleport;targetEl&&(document.body.contains(targetEl)||createPortal(templateEl))})}).observe(document.body,{childList:!0,subtree:!0}),Alpine2.directive("portal",(rawEl,{},{cleanup,effect})=>{rawEl.tagName.toLowerCase()!=="template"&&console.warn("x-portal can only be used on a <template> tag",rawEl);const templateEl=rawEl;createPortal(templateEl),effect(()=>{const newTargetEl=getTarget(templateEl),currentClone=getCurrentCloneFromTemplate(templateEl),currentTarget=currentClone?._x_teleportTarget;newTargetEl!==currentTarget&&createPortal(templateEl)}),cleanup(()=>{const clone=getCurrentCloneFromTemplate(templateEl);clone&&clone.remove()})})}const TOP_VAR="--scroll-top";function StickyScroll(Alpine2){Alpine2.directive("sticky-scroll",(stickyElement,{expression},{evaluate,cleanup})=>{const{container,top:topGap,bottom:bottomGap}=evaluate(expression),scrollTarget=container instanceof HTMLElement?container:document,propertyTarget=container instanceof HTMLElement?container:document.getElementById("MainContent"),getScrollTargetScrollY=()=>container instanceof HTMLElement?container.scrollTop:window.scrollY,getHeightOfTarget=()=>window.innerHeight,positionStickySidebar=()=>{propertyTarget._x_endScroll=propertyTarget._x_screenHeight-stickyElement.offsetHeight-bottomGap;let stickyElementTop=parseInt(propertyTarget.style.getPropertyValue(TOP_VAR).replace("px",""),10);propertyTarget._x_stickyElementHeight+topGap+bottomGap>propertyTarget._x_screenHeight?getScrollTargetScrollY()<propertyTarget._x_currPos?stickyElementTop<topGap?propertyTarget.style.setProperty(TOP_VAR,`${stickyElementTop+propertyTarget._x_currPos-getScrollTargetScrollY()}px`):stickyElementTop>=topGap&&stickyElementTop!=topGap&&propertyTarget.style.setProperty(TOP_VAR,`${topGap}px`):stickyElementTop>propertyTarget._x_endScroll?propertyTarget.style.setProperty(TOP_VAR,`${stickyElementTop+propertyTarget._x_currPos-getScrollTargetScrollY()}px`):stickyElementTop<propertyTarget._x_endScroll&&stickyElementTop!=propertyTarget._x_endScroll&&propertyTarget.style.setProperty(TOP_VAR,`${propertyTarget._x_endScroll}px`):propertyTarget.style.setProperty(TOP_VAR,`${topGap}px`),propertyTarget._x_currPos=getScrollTargetScrollY()};function updateSticky(){propertyTarget._x_screenHeight=getHeightOfTarget(),propertyTarget._x_stickyElementHeight=stickyElement.offsetHeight,positionStickySidebar()}function onResize(){propertyTarget._x_currPos=getScrollTargetScrollY(),updateSticky()}propertyTarget._x_endScroll=getHeightOfTarget()-stickyElement.offsetHeight-500,propertyTarget._x_currPos=getScrollTargetScrollY(),propertyTarget._x_screenHeight=getHeightOfTarget(),propertyTarget._x_stickyElementHeight=stickyElement.offsetHeight,propertyTarget.style.setProperty(TOP_VAR,`${topGap.toString()}px`),propertyTarget._x_scroll_listener=updateSticky,propertyTarget._x_resize_listener=onResize,window.addEventListener("resize",propertyTarget._x_resize_listener),scrollTarget.addEventListener("scroll",propertyTarget._x_scroll_listener,{capture:!0,passive:!0}),cleanup(()=>{scrollTarget.removeEventListener("scroll",propertyTarget._x_scroll_listener,{capture:!0}),window.removeEventListener("resize",propertyTarget._x_resize_listener),propertyTarget._x_endScroll=0,propertyTarget._x_currPos=0,propertyTarget._x_screenHeight=0,propertyTarget._x_stickyElementHeight=0,propertyTarget.style.removeProperty(TOP_VAR)})})}const POPUP_OVERLAY_CLICK_EVENT="popup-overlay-click",POPUP_APPEARANCE_DURATION=500;let __popups=[];const PopupStore={currentPopup:null,isCurrentPopupFullScreen:!1,isCurrentPopupFocused:!1,originalFocusableEl:null,__currentPopupRef:null,__nextPopupRef:null,__popupHistory:[],__isNoRenderWhileHidingRef:!1,__endOfHeaderHeight:0,__popupContentHeight:0,_nextPopup:null,_isPopupVisible:!1,_isPopupSimple:!1,_popupContentRatio:0,_isMaxHeightReached:!1,_isPopupContentHidden:!1,__isKeyboardVisibleRef:!1,__prevWindowHeightRef:0,__mutationObserver:null,__attachedOverlayCallback:null,init(){Alpine.effect(()=>{const currentPopupConfig=__popups.find(popup=>popup.id===this.__currentPopupRef),nextPopupConfig=__popups.find(popup=>popup.id===this.__nextPopupRef),isPopupContentHidden=this.__nextPopupRef!==null,isPopupVisible=!!this.currentPopup,isPopupFocused=isPopupContentHidden?nextPopupConfig?.isFocused:currentPopupConfig?.isFocused,isPopupFullScreen=isPopupContentHidden?nextPopupConfig?.isFullScreen:currentPopupConfig?.isFullScreen,isPopupSimple=isPopupContentHidden?nextPopupConfig&&!isPopupFocused:currentPopupConfig&&!isPopupFocused,overlayCallback=isPopupContentHidden?nextPopupConfig?.overlayCallback:currentPopupConfig?.overlayCallback,isMaxHeightReached=this.__popupContentHeight>this.__getWindowHeight()-this.__endOfHeaderHeight-32;this.isCurrentPopupFocused=!!isPopupFocused,this.isCurrentPopupFullScreen=!!isPopupFullScreen,this._isPopupVisible=!!isPopupVisible,this._isPopupSimple=!!isPopupSimple,this._isMaxHeightReached=isMaxHeightReached,this._isPopupContentHidden=isPopupContentHidden,isPopupFocused?(Alpine.store("main").isPrint||freezeScroll(),this.__mutationObserver=new MutationObserver(()=>{this.__updateScrollLockIfNeeded()}),this.__mutationObserver.observe(document.getElementById("popup-content-portal"),{childList:!0,subtree:!0,attributeFilter:["class"]})):(unfreezeScroll(),this.__mutationObserver&&(this.__mutationObserver.disconnect(),this.__mutationObserver=null)),this._isMaxHeightReached||Alpine.nextTick(()=>{this.updateContentSize()}),setTimeout(()=>{const popupContentRatio=(this.__popupContentHeight+32)/100;this._popupContentRatio=popupContentRatio}
2,0),overlayCallback?this.__addOverlayCallback(overlayCallback):this.__removeOverlayCallback()})},_registerPopup(popup){__popups.push(popup),popup.isAlwaysVisible&&this.showPopup(popup.id)},_unregisterPopup(popup){__popups=__popups.filter(p=>p.id!==popup.id),this.__popupHistory.includes(popup.id)&&this.hidePopup(popup.id)},_updatePopupConfig(popup){__popups=__popups.map(p=>p.id===popup.id?popup:p)},extendPopupConfig(popup){const popupConfig=__popups.find(p=>p.id===popup.id);this._updatePopupConfig({...popupConfig,...popup})},async hideAllPopups(){isMobile()&&(this.__isNoRenderWhileHidingRef=!0,this.__currentPopupRef=null,this.__isNoRenderWhileHidingRef&&await this.__doSupportiveTransition(),this.__isNoRenderWhileHidingRef&&await this.updateContentSize(),this.__isNoRenderWhileHidingRef&&await new Promise(res=>{setTimeout(res,POPUP_APPEARANCE_DURATION/4)}),this.__isNoRenderWhileHidingRef&&(unfreezeScroll(),this.currentPopup=null,this.__popupHistory=[]))},hideCurrentPopup(){var _a;if(!isMobile())return;document.removeEventListener("keydown",this._onKeyDown),(_a=this.originalFocusableEl)==null||_a.focus(),this.originalFocusableEl=null;const popup=this.__currentPopupRef,popupConfig=__popups.find(p=>p.id===popup);if(popupConfig&&popupConfig.isPreventOverlayClose)return;for(let i=this.__popupHistory.length-1;i>=0&&this.__popupHistory[i]===popup;i--)this.__popupHistory.pop();const lastPopup=this.__popupHistory[this.__popupHistory.length-1];if(!lastPopup){this.hideAllPopups();return}this.showPopup(lastPopup)},__updatePopupHeight(popup){popup?this.__popupContentHeight=document.getElementById("popup-content-portal").getBoundingClientRect().height:this.__popupContentHeight=0},async __doSupportiveTransition(popup=null){const start=document.getElementById("end-of-header").getBoundingClientRect().top;this.__endOfHeaderHeight=start,this.__updatePopupHeight(popup),this.__nextPopupRef=popup,this._nextPopup=popup,!(!popup||Alpine.store("main").isReducedMotion)&&await new Promise(resolve=>{document.getElementById("popup-content").addEventListener("transitionstart",()=>{resolve()},{once:!0})})},async showPopup(popup,isClosePrevious=!0){if(!isMobile())return;if(this.originalFocusableEl=document.activeElement.closest(SELECTOR_LIST),document.addEventListener("keydown",this._onKeyDown.bind(this)),this.__currentPopupRef){const currentPopupConfig=__popups.find(p=>p.id===this.__currentPopupRef),nextPopupConfig=__popups.find(p=>p.id===popup);currentPopupConfig&&currentPopupConfig.isFullScreen&&nextPopupConfig?.isFullScreen&&this.__popupHistory.pop()}if(!isClosePrevious&&this.__currentPopupRef){this.__popupHistory.unshift(popup);return}this.__popupHistory[this.__popupHistory.length-1]!==popup&&this.__popupHistory.push(popup);const isAlreadyOpen=this.__currentPopupRef===popup,popupConfig=__popups.find(p=>p.id===popup);if(!popupConfig)return;await Promise.resolve(),this.__isNoRenderWhileHidingRef=!1,isAlreadyOpen||await this.__doSupportiveTransition(popup);const{isFocused}=popupConfig;isFocused?(freezeScroll(),this.__mutationObserver=new MutationObserver(()=>{this.__updateScrollLockIfNeeded()}),this.__mutationObserver.observe(document.getElementById("popup-content-portal"),{childList:!0,subtree:!0})):(unfreezeScroll(),this.__mutationObserver&&(this.__mutationObserver.disconnect(),this.__mutationObserver=null));try{Alpine.nextTick(()=>{this.__updatePopupHeight(popup),this.__nextPopupRef=null,this.__currentPopupRef=popup,this.currentPopup=popup})}catch{}},_onKeyDown(e){e.key===ESC_KEY&&this.hideCurrentPopup()},hidePopup(popup){popup===this.__currentPopupRef&&this.hideCurrentPopup()},__getWindowHeight(){if(this.__isKeyboardVisibleRef)return this.__prevWindowHeightRef;const newWindowHeight=window.visualViewport?window.visualViewport.height:window.screen.availHeight;return this.__prevWindowHeightRef=newWindowHeight,newWindowHeight},__updateScrollLockIfNeeded(){const contentPortal=document.getElementById("popup-content-portal");if(!contentPortal)return;contentPortal.scrollHeight>this.__getWindowHeight()-this.__endOfHeaderHeight-32?makeElementScrollable(contentPortal):makeElementNotScrollable()},onPopupOverlayClick(){const event=new CustomEvent(POPUP_OVERLAY_CLICK_EVENT);document.dispatchEvent(event),this.hideCurrentPopup()},updateContentSize(){var _a;this.__updatePopupHeight(this.__currentPopupRef),this.__updateScrollLockIfNeeded(),(_a=document.getElementById("popup-content-portal"))==null||_a.scrollTo({top:0})},useOnPopupOverlayClick(popup,callback){this.extendPopupConfig({id:popup,overlayCallback:callback})},__addOverlayCallback(callback){this.__attachedOverlayCallback&&this.__attachedOverlayCallback!==callback&&this.__removeOverlayCallback(),this.__attachedOverlayCallback||(document.addEventListener(POPUP_OVERLAY_CLICK_EVENT,callback),this.__attachedOverlayCallback=callback)},__removeOverlayCallback(){this.__attachedOverlayCallback&&(document.removeEventListener(POPUP_OVERLAY_CLICK_EVENT,this.__attachedOverlayCallback),this.__attachedOverlayCallback=null)}};let _all={};const ResizableStore={_current:{},originalFocusableEl:null,_keyDownEventListener:()=>{}
2,__observer:null,__onResize(entries){for(const entry of entries){const{id}=entry.target;if(this._current[id]&&entry.contentBoxSize){const{blockSize,inlineSize}=entry.contentBoxSize[0];this._current[id]={width:inlineSize,height:blockSize},isDocumentFreezed&&blockSize<entry.target.scrollHeight&&makeElementScrollable(document.getElementById(id))}}},_maxHeight:window.innerHeight-66,init(){this.__observer=new ResizeObserver(this.__onResize.bind(this)),document.addEventListener("resize",()=>{this._maxHeight=window.innerHeight-66})},_register(config){_all[config.id]=config},_unregister(areaId){delete _all[areaId]},_onKeyDown(e,id){e.key===ESC_KEY&&this.hide(id)},async show(id){var _a;const config=_all[id];if(Object.keys(this._current).length>0&&(Object.keys(this._current).forEach(id2=>{this.hide(id2)}),await new Promise(resolve=>{setTimeout(resolve,300)})),config){const{width,height}=document.getElementById(id).getBoundingClientRect();this._current[id]={width,height}}const resizable=document.getElementById(id);(_a=this.__observer)==null||_a.observe(resizable),this._keyDownEventListener=e=>{this._onKeyDown(e,id)},document.addEventListener("keydown",this._keyDownEventListener),this.originalFocusableEl=document.activeElement.closest(SELECTOR_LIST)},hide(id){var _a;const wrapperEl=document.querySelector(".resizable--visible .resizable__content--portal");wrapperEl&&(wrapperEl.removeAttribute("role"),wrapperEl.removeAttribute("aria-modal"),wrapperEl.removeAttribute("aria-labelledby"));const resizable=document.getElementById(id);(_a=this.__observer)==null||_a.unobserve(resizable),delete this._current[id],document.removeEventListener("keydown",this._keyDownEventListener),resizable.closest(".resizable").addEventListener("transitionend",()=>{var _a2;(_a2=this.originalFocusableEl)==null||_a2.focus()},{once:!0})},hideAll(){Object.keys(this._current).forEach(id=>{this.hide(id)})},isVisible(id=null){const keys=Object.keys(this._current);return id?keys.includes(id):keys.length}},ProductListStore={isFiltersSidebarExpanded:!0,toggleFiltersSidebar(){this.isFiltersSidebarExpanded=!this.isFiltersSidebarExpanded}},Main={showCurrency:!1,isHeaderShadowVisible:!1,scaleFactor:1,yOffset:0,totalCartQty:0,isMobile:isMobile(),isPrint:window.matchMedia("print").matches,isReducedMotion:window.matchMedia("(prefers-reduced-motion: reduce)").matches,opacityOnZoom:1,init(){this.setTransformValues(),this.onResize(),window.addEventListener("resize",this.onResize.bind(this)),window.matchMedia("(prefers-reduced-motion: reduce)").addEventListener("change",e=>{this.isReducedMotion=e.matches}),window.matchMedia("print").addEventListener("change",e=>{this.isPrint=e.matches})},onResize(){const newIsMobile=isMobile();this.isMobile!==newIsMobile&&(Alpine.store("popup").currentPopup=null,Alpine.store("resizable")._current={},unfreezeScroll()),this.isMobile=newIsMobile,document.documentElement.style.setProperty("--screen-width",window.innerWidth.toString()),document.documentElement.style.setProperty("--screen-height",window.innerHeight.toString())},setTransformValues(){const windowHeight=window.innerHeight,windowWidth=window.innerWidth,desiredEndWidth=windowWidth+16,documentScrollHeight=document.body.scrollHeight,widthScaleFactor=(desiredEndWidth-windowWidth)/windowWidth,heightScaleFactor=(windowHeight-16)/windowHeight,minScaleFactor=Math.min(widthScaleFactor,heightScaleFactor),newScaleFactor=1+minScaleFactor,newYOffset=documentScrollHeight*minScaleFactor*-1*window.scrollY/documentScrollHeight;this.scaleFactor=newScaleFactor,this.yOffset=newYOffset},getPrice(value){var _a,_b,_c;const locale=((_a=window?.Shopify)==null?void 0:_a.locale)||"en",currency=((_c=(_b=window?.Shopify)==null?void 0:_b.currency)==null?void 0:_c.active)||"USD",displayedCurrency=this.showCurrency?` ${currency}`:"",price=Number.isInteger(value)?value/100:Number(value)||0;return new Intl.NumberFormat(locale,{style:"currency",currency}).format(price).replace(".00","")+displayedCurrency},isPopupFocused(){return this.isMobile?Alpine.store("popup").isCurrentPopupFocused:Object.keys(Alpine.store("resizable")._current).length>0},hideAllPopupsAndResizables(){Alpine.store("popup").onPopupOverlayClick(),Alpine.store("resizable").hideAll()}},CART_RESIZABLE_ID="cart-desktop",CART_POPUP_ID="cart",SECTION_MAIN_CART_ITEMS="main-cart-items",ABORT_ERROR_NAME="AbortError",CartStore={cartType:"drawer",cartUrl:"",cart:null,cartItems:[],itemCount:0,itemsSubtotalPrice:null,totalPriceCents:null,cartToken:null,discounts:[],isCartInitialized:!1,isLoading:!1,addingItemIds:[],remov
2ingItemKey:null,abortController:null,cartRequestSeq:0,latestAppliedCartRequestSeq:0,error:{message:void 0,errors:{}},init(){this.hydrateFromPageCart(),document.addEventListener("od:main-content-replaced",()=>this.hydrateFromPageCart()),document.addEventListener("od:after-swap",()=>this.hydrateFromPageCart())},_nextCartRequestSeq(){return this.cartRequestSeq+=1,this.cartRequestSeq},_isValidCents(value){return typeof value=="number"&&Number.isFinite(value)},_normalizeDiscounts(discounts=[]){return Array.isArray(discounts)?discounts.map(discount=>{var _a,_b,_c,_d,_e,_f;const application=discount.discount_application||discount,amount=this._isValidCents(discount.total_allocated_amount)?discount.total_allocated_amount:this._isValidCents(application?.total_allocated_amount)?application.total_allocated_amount:null;return this._isValidCents(amount)?{...discount,title:((_a=discount.title)==null?void 0:_a.toString())||((_b=application?.title)==null?void 0:_b.toString())||((_c=discount.code)==null?void 0:_c.toString())||((_d=application?.code)==null?void 0:_d.toString())||((_f=(_e=discount.discount_application)==null?void 0:_e.type)==null?void 0:_f.toString())||"",total_allocated_amount:amount}:null}).filter(Boolean):[]},applyCartState(cart,requestSeq=this._nextCartRequestSeq()){return!cart||!Array.isArray(cart.items)?(console.warn("[CartStore] Ignoring invalid cart response",cart),this.cart):requestSeq<this.latestAppliedCartRequestSeq?this.cart||cart:(this.latestAppliedCartRequestSeq=requestSeq,this.cart=cart,this.cartToken=cart.token||this.cartToken,this.itemCount=this._isValidCents(cart.item_count)?cart.item_count:cart.items.reduce((total,item)=>total+Number(item.quantity||0),0),this.setCartItems(this.processCartItems(cart.items),this.itemCount),this._isValidCents(cart.items_subtotal_price)?this.itemsSubtotalPrice=cart.items_subtotal_price:console.warn("[CartStore] Cart response missing items_subtotal_price",cart),this._isValidCents(cart.total_price)?this.totalPriceCents=cart.total_price:console.warn("[CartStore] Cart response missing total_price",cart),this.setDiscounts(cart.cart_level_discount_applications||[]),cart)},hydrateFromPageCart(){const cartJson=document.querySelector("[data-od-cart-json]");if(!cartJson)return this.cart;try{const cart=JSON.parse(cartJson.textContent||"{}");return this.applyCartState(cart)}catch(error){return console.error("[CartStore] Failed to hydrate cart from page JSON",error),this.cart}},refreshCart(){const requestSeq=this._nextCartRequestSeq(),root=window.Shopify&&Shopify.routes&&Shopify.routes.root||"/";return fetch(`${root}cart.js`,{headers:{Accept:"application/json"},credentials:"same-origin",cache:"no-store"}).then(response=>{if(!response.ok)throw new Error(`Failed to fetch cart.js: ${response.status}`);return response.json()}).then(cart=>this.applyCartState(cart,requestSeq)).catch(error=>{throw console.error("[CartStore] Cart refresh failed",error),error})},refresh(cart){return cart&&Array.isArray(cart.items)?Promise.resolve(this.applyCartState(cart)):this.refreshCart()},getCart(){return this.refreshCart()},setCartItems(cartItems,itemCount){this.cartItems=cartItems;const nextItemCount=this._isValidCents(itemCount)?itemCount:cartItems.reduce((total,item)=>total+Number(item.quantity||0),0);this.itemCount=nextItemCount,Alpine.store("main").totalCartQty=nextItemCount},addCartItems(cartItems){this.setCartItems([...cartItems,...this.cartItems])},processCartItems(items){return items.map(item=>{var _a;return{...item,image:(_a=item.image)==null?void 0:_a.replace(/^https:\/\/cdn\.shopify\.com\/s\/files\/(?:\d+\/)+files/,`//${window.Shopify.cdnHost}/shop/files`)}})},addToCart(itemProps){const{id}=itemProps;this.addingItemIds.includes(id)||this.addingItemIds.push(id);const formData={items:[itemProps],sections:"header"};fetch(`${window.Shopify.routes.root}cart/add.js`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(formData)}).then(response=>response.json()).then(response=>{var _a;if(response.status===422){this.error.message=response.description,this.error.errors=response.errors,this.refreshCart().catch(()=>{});return}const addedItemKey=(_a=response.items)==null?void 0:_a[0]?.key;return this.refreshCart().then(()=>
2{if(this.cartType==="page"){navigateWithTransition(this.cartUrl);return}this.focusInCart(addedItemKey),this.error.message="",this.error.errors={};const miniCart=document.getElementById("mini-cart");response.sections&&response.sections.header&&miniCart&&replaceContent(response.sections.header,"mini-cart",miniCart)})}).catch(error=>console.error("Error:",error)).finally(()=>{this.addingItemIds=this.addingItemIds.filter(itemId=>itemId!==id)})},updateCartItem(key,qty){this.abortController&&(this.removingItemKey=null,this.abortController.abort());const cartItem=this.cartItems.find(item=>item.key===key);if(!cartItem)return this.refreshCart().catch(()=>{});this.isLoading=!0,this.abortController=new AbortController;const requestSeq=this._nextCartRequestSeq();cartItem.quantity===0&&(cartItem.isDeleted=!0,this.removingItemKey=key),fetch(`${window.Shopify.routes.root}cart/update.js`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:{[key]:qty},sections:SECTION_MAIN_CART_ITEMS}),signal:this.abortController.signal}).then(response=>response.json()).then(data=>{if(data.status===422)return this.error.message=data.description,this.error.errors=data.errors||{},this.refreshCart().finally(()=>{this.isLoading=!1,this.removingItemKey=null});this.applyCartState(data,requestSeq),this.isLoading=!1,this.removingItemKey=null}).catch(error=>{error.name!==ABORT_ERROR_NAME&&(console.error("Error:",error),this.isLoading=!1,this.removingItemKey=null)})},updateCart(){return this.isLoading=!0,this.refreshCart().then(()=>{this.isLoading=!1,this.removingItemKey=null}).catch(error=>{error.name!==ABORT_ERROR_NAME&&(console.error("Error:",error),this.isLoading=!1,this.removingItemKey=null)})},increaseQty(key,openCart=!1){const cartItem=this.cartItems.find(item=>item.key===key);if(cartItem&&(cartItem.quantity=Number(cartItem.quantity)+1,this.updateCartItem(key,cartItem.quantity),openCart))return this.focusInCart(key)},focusInCart(key){this.cartItems.forEach(cartItem=>{const isFocused=cartItem.key===key;cartItem.focusedUntil=isFocused?Date.now()+2e3:void 0}),this.showCart()},showCart(){Alpine.store("main").isMobile?Alpine.store("popup").showPopup(CART_POPUP_ID,!0):Alpine.store("resizable").show(CART_RESIZABLE_ID)},hideCart(){this._updateFocusAnimation(),Alpine.store("main").isMobile?Alpine.store("popup").hidePopup(CART_POPUP_ID):Alpine.store("resizable").hide(CART_RESIZABLE_ID)},decreaseQty(key,openCart=!1){const cartItem=this.cartItems.find(item=>item.key===key);if(cartItem&&(cartItem.quantity=Number(cartItem.quantity)-1,this.updateCartItem(key,cartItem.quantity),openCart))return this.focusInCart(key)},setQty(quantity,key){const cartItem=this.cartItems.find(item=>item.key===key);cartItem&&(cartItem.quantity=Math.max(0,Number(quantity)),this.updateCartItem(key,cartItem.quantity))},setDiscounts(discounts){this.discounts=this._normalizeDiscounts(discounts)},_formatAuthoritativePrice(cents){return this._isValidCents(cents)?Alpine.store("main").getPrice(cents):""},subtotalPrice(){return this._formatAuthoritativePrice(this.itemsSubtotalPrice)},totalPrice(){return this._formatAuthoritativePrice(this.totalPriceCents)},_updateFocusAnimation(){this.cartItems.forEach(cartItem=>{cartItem.focusedUntil&&(cartItem.focusedUntil=Date.now()<cartItem.focusedUntil?cartItem.focusedUntil:void 0)})}},BeforeAfter=props=>({wrapperRect:null,wrapperEl:null,exposure:50,init(){const{id}=props;this.wrapperEl=document.getElementById(id);const computeWrapperRect=()=>{if(!this.wrapperEl)return;const rect=this.wrapperEl.getBoundingClientRect();this.wrapperRect=rect};window.addEventListener("resize",computeWrapperRect),computeWrapperRect(),this.$watch("exposure",value=>{this.wrapperEl&&this.wrapperEl.style.setProperty("--exposure",`${100-parseInt(value,10)}%`)})},onPointerDown(){const move=e=>{if(!this.wrapperEl||!this.wrapperRect)return;const x=e.clientX-this.wrapperRect.left;this.exposure=Math.min(100,Math.max(0,x/this.wrapperRect.width*100))},up=()=>{document.removeEventListener("pointermove",move),document.removeEventListener("pointerup",up)};document.addEventListener("pointermove",move),document.addEventListener("pointerup",up)},onKeyDown(e){this.wrapperEl&&(e.key===ARROW_RIGHT_KEY&&this.exposure<100&&(this.exposure++,e.preventDefault()),e.key===ARROW_LEFT_KEY&&this.exposure>0&&(this.exposure--,e.preventDefault()))}}),easeInOutQuad=x=>x,OFFSET_TOP=window.innerHeight>1080?400:200;let prevIsMobile=isMobile();const TransitionPreview=()=>({isActive:!1,lastSeenWithoutPreview:0,offsetTop:OFFSET_TOP,maxScroll:OFFSET_TOP/4*3,_scrollContainerRef:null,init(){Alpine.nextTick(()=>
2{this._scrollContainerRef=this.$refs.scrollContainer}),window.addEventListener("pushstate",async event=>{const{state}=event.detail;state?.isPreview?(this.lastSeenWithoutPreview+=1,this.showPreview()):(this.lastSeenWithoutPreview=0,this.hidePreview())}),window.addEventListener("popstate",async event=>{const{state}=event;state?.isPreview?(this.lastSeenWithoutPreview-=1,this.showPreview()):(this.lastSeenWithoutPreview=0,this.hidePreview())}),window.addEventListener("beforeunload",function(){const{isPreview}=window.history.state||{};isPreview&&history.replaceState({isPreview:!1},"",window.location.href)}),this.$refs.scrollContainer.addEventListener("scroll",()=>{const percentOfMaxScroll=Math.min(this.$refs.scrollContainer.scrollTop/this.maxScroll,1);this.$refs.preview.style.setProperty("--scroll-progress",easeInOutQuad(percentOfMaxScroll).toString())}),window.addEventListener("resize",()=>{prevIsMobile!==isMobile()&&this.hidePreview()})},scrollToPreviewTop(){var _a;(_a=this._scrollContainerRef)==null||_a.scrollTo({top:this.maxScroll,behavior:"smooth"})},scrollToTop(){var _a;(_a=this._scrollContainerRef)==null||_a.scrollTo({top:0,behavior:"smooth"})},showPreview(){if(this.isActive){this.scrollToPreviewTop();return}this.isActive=!0,Alpine.store("transition").isPreviewActive=!0,this.scrollToTop(),freezeScroll(),makeElementScrollable(this._scrollContainerRef),document.addEventListener("keydown",this._onKeyDown.bind(this))},hidePreview(){this.isActive&&(this.scrollToTop(),this.isActive=!1,Alpine.store("transition").isPreviewActive=!1,this.lastSeenWithoutPreview&&history.go(-this.lastSeenWithoutPreview),unfreezeScroll(),setTimeout(()=>{var _a;const wrapperEl=document.querySelector(".transition-preview");wrapperEl&&(wrapperEl.removeAttribute("role"),wrapperEl.removeAttribute("aria-modal"),wrapperEl.removeAttribute("aria-labelledby")),document.getElementById("PreviewContent").innerHTML="",(_a=Alpine.store("transition").originalFocusableEl)==null||_a.focus(),Alpine.store("transition").originalFocusableEl=null},300),document.removeEventListener("keydown",this._onKeyDown))},_onKeyDown(e){if(e.key===ESC_KEY){const resizables=Alpine.store("resizable")._current;Object.keys(resizables).length||this.hidePreview()}}}),SEARCH_QUERY_NAME="q",ProductList=(...args)=>{const[path]=args;return{isLoadingProducts:!1,init(){console.log("[OD ProductList] init",{path,location:window.location.pathname+window.location.search,hasDefaultComingSoonDefer:this.$refs.ProductGridContainer?.getAttribute("data-default-collection-coming-soon-defer")}),this._fetchPage=this._fetchPage.bind(this)},resetAll(){this._fetchPage(this._getSearchQueryString(),!0),this.$dispatch("reset-filters")},_getSearchQuery(){return new URLSearchParams(window.location.search).get(SEARCH_QUERY_NAME)||""},_getSearchQueryString(){const searchValue=this._getSearchQuery();return searchValue?`?${SEARCH_QUERY_NAME}=${searchValue}`:""},_fetchPage(queryString,isReset=!1){console.log("[OD ProductList] fetchPage",{path,queryString,isReset,location:window.location.pathname+window.location.search}),this.isLoadingProducts=!0,fetch(`${path}${queryString}`).then(response=>response.text()).then(data=>{const resultHtml=document.createElement("div");resultHtml.innerHTML=data;const productGridHtml=resultHtml.querySelector("#ProductGridContainer"),productGridElem=this.$refs.ProductGridContainer;replaceElement(productGridElem,productGridHtml,isReset),history.replaceState(history.state,"",queryString||location.pathname)}).catch(error=>console.error("Error:",error)).finally(()=>this.isLoadingProducts=!1)}}},formatPrice=(price,currency)=>new Intl.NumberFormat("en-US",{style:"currency",currency}).format(price),POPUP_FILTERS="filters",POPUP_BOTTOM_FILTERS="bottom-filters",FILTER_SORT="sort_by",FILTER_PRICE="Price",FILTER_PRICE_PARAM_NAME="filter.v.price",FILTER_PRICE_MIN="filter.v.price.gte",FILTER_PRICE_MAX="filter.v.price.lte",Filters=(defaultSort,minPrice,maxPrice,currency)=>({currentName:"",searchQuery:"",isTopLevel:!0,isTopFilterVisible:null,filters:[],sortOptions:[],sortBy:!1,init(){this.updateFilters=this.updateFilters.bind(this),this.onResetButtonClick=this.onResetButtonClick.bind(this),this.searchQuery=this._getSearchQuery(),this.$watch("currentName",(value,oldValue)=>{value!=oldValue&&this.$nextTick(()=>{setTimeout(()=>{this.$store.popup.updateContentSize()},50)})}),this.$watch("isTopFilterVisible",value=>{value?this.$store.popup.hidePopup(POPUP_BOTTOM_FILTERS):this.$store.popup.showPopup(POPUP_BOTTOM_FILTERS,!1)}),this.$watch("$store.popup.currentPopup",value=>{value===POPUP_BOTTOM_FILTERS&&this.isTopFilterVisible&&this.$store.popup.hidePopup(POPUP_BOTTOM_FILTERS)})},onResetButtonClick(){this.isTopLevel?(this.resetAll(),this.hideFilters()):this.resetCurrent()},showFilters(isTopLevel=!0,currentName=""){this.isTopLevel=isTopLevel,this.currentName=currentName,this.$store.popup.showPopup(POPUP_FILTERS,!0)},hideFilters(){this.$store.popup.hidePopup(POPUP_FILTERS),this.isTopLevel=!1,this.currentName=""},getPriceFilter(){return this.filters.find(f=>
2f.param_name===FILTER_PRICE_PARAM_NAME)},getFormattedMinPrice(){return formatPrice(parseFloat(this.getPriceFilter().min_value.value),currency)},getFormattedMaxPrice(){return formatPrice(parseFloat(this.getPriceFilter().max_value.value),currency)},resetSelectedFiltersState(){this.filters.forEach(filter=>{filter.param_name===FILTER_PRICE_PARAM_NAME?(filter.min_value.value="",filter.max_value.value=""):filter.active_values=[]}),this.sortBy=!1},setSortBy(value){this.sortBy=value||!1,this.sortBy===defaultSort&&(this.sortBy=!1)},getSelectedSortOption(){return this.sortBy?this.sortOptions.find(option=>option.value===this.sortBy):this.sortOptions.find(option=>option.value===defaultSort)},getIsFilterValueSelected(param_name,value){if(param_name===FILTER_SORT)return this.getSelectedSortOption().value===value;{const filter=this.filters.find(filter2=>filter2.param_name===param_name);return!!filter?.active_values.find(a=>a.value===value)}},getIsFilterSelected(param_name){if(param_name===FILTER_SORT)return!!this.sortBy;if(param_name===FILTER_PRICE_PARAM_NAME){const priceFilter=this.getPriceFilter();return!!priceFilter.min_value.value||!!priceFilter.max_value.value}else{const filter=this.filters.find(filter2=>filter2.param_name===param_name);return!!filter?.active_values.length}},getIsDefault(){let isDefault=!0;return this.filters.forEach(filter=>{filter.param_name===FILTER_PRICE_PARAM_NAME?(filter.min_value.value||filter.max_value.value)&&(isDefault=!1):filter.active_values.length&&(isDefault=!1)}),this.sortBy&&(isDefault=!1),isDefault},updateFilters(removedAttr={}){const form=document.getElementById("FilterForm"),formData=new FormData(form);let urlParams=new URLSearchParams(formData);[...urlParams.entries()].forEach(([key,value])=>{if(this._isFilterEmptyOrDefault(key,value)){urlParams.delete(key);return}if(this._isFilterRemoved(key,value,removedAttr)){const paramValues=urlParams.getAll(key);urlParams.delete(key),value&&paramValues.length>1&&paramValues.forEach(paramValue=>{paramValue!==value&&urlParams.append(key,paramValue)})}}),urlParams.sort();const queryString=urlParams.toString()?`?${urlParams.toString()}`:"";queryString!==window.location.search&&(this.resetSelectedFiltersState(),[...urlParams.entries()].forEach(([key,value])=>{var _a;if(key===FILTER_SORT)this.setSortBy(value);else if(key===FILTER_PRICE_MIN)this.getPriceFilter().min_value.value=value;else if(key===FILTER_PRICE_MAX)this.getPriceFilter().max_value.value=value;else{const filter=this.filters.find(f=>f.param_name===key),label=((_a=filter?.values.find(v=>v.param_name===key&&v.value===value))==null?void 0:_a.label)||"";filter?.active_values.push({label,param_name:key,value})}}),this._fetchPage(queryString,!!Object.keys(removedAttr).length),setTimeout(()=>{window.scrollTo({top:0,behavior:"smooth"})},300))},removeFilter(name,value=""){this.updateFilters({[name]:value}),this.$dispatch("reset-filters",{name})},resetCurrent(filterWrapperId){const filterWrapper=document.getElementById(filterWrapperId||`filter-${this.currentName.toLowerCase()}`);if(!filterWrapper)return;let removedAttr={};Array.from(filterWrapper.getElementsByTagName("input")).forEach(item=>{item.name&&item.value&&!removedAttr.hasOwnProperty(item.name)&&(removedAttr[item.name]="")}),Object.keys(removedAttr).length&&(this.updateFilters(removedAttr),this.$dispatch("reset-filters",{name:this.currentName}))},_isFilterEmptyOrDefault(key,value){return!value||key===FILTER_SORT&&value===String(defaultSort)||key===FILTER_PRICE_MIN&&value===String(minPrice)||key===FILTER_PRICE_MAX&&value===String(maxPrice)},_isFilterRemoved(key,value,removedAttr){return key in removedAttr?!removedAttr[key]||value==removedAttr[key]:!1}}),POPUP_BOTTOM_ACTIONS="product_bottom_actions",ProductPage=()=>({isVariantInCart:!1,variantQty:1,selectedVariantId:void 0,selectedOptions:[],manuallySelectedVariantId:void 0,productId:void 0,contentId:"product-page",isSyncedWithUrl:!0,isScrollingToTop:!0,productUrl:"",sectionId:null,XRMediaModels:[],properties:{__shopify_send_gift_card_to_recipient:!1,"Recipient email":null,"Recipient name":null,Message:null,"Send on":null},cartItemKey:void 0,variantsCount:null,_formRef:null,_mutationObserver:null,productActionsPopup:"product_actions",variants:[],variantsOptions:[],isVariantAvailable:!0,setProductPageProps({manuallySelectedVariantId,selectedVariantId,selectedOptions,productId,productUrl,isSyncedWithUrl=!1,isScrollingToTop=!1,sectionId=null,XRMediaModels=[],variants=[]}){this.isVariantManuallySelected=!!manuallySelectedVariantId,this.selectedVariantId=selectedVariantId,this.selectedOptions=selectedOptions,this.productId=productId,this.productActionsPopup+=`-${productId}`,this.productUrl=productUrl,this.isSyncedWithUrl=isSyncedWithUrl,this.isScrollingToTop=isScrollingToTop,this.sectionId=sectionId,this.XRMediaModels=XRMediaModels,this.variants=variants,this.variantsOptions=variants.map(variant=>variant.options),this.variantsCount=variants.length,sectionId&&(this.productActionsPopup+=`-${sectionId}`),this._updateSelectedVariantCartState(),this.XRMediaModels.length&&this.setupShopifyXR()},get isProductBeingRemoved(){return Alpine.store("cart").removingItemKey===this.cartItemKey},get isProductBeingAdded(){return this.selectedVariantId?Alpine.store("cart").addingItemIds.includes(this.selectedVariantId):!1},init(){var _a;(_a=window.Shopify.PaymentButton)==null||_a.init(),this._formRef=this.$refs.ProductForm,this.$watch("$store.cart.cartItems",()=>{this._updateSelectedVariantCartState()}),this.$watch("properties",()=>{this.properties.__shopify_send_gift_card_to_recipient||(this.properties={__shopify_send_gift_card_to_recipient:!1,"Recipient email":null,"Recipient name":null,Message:null,"Send on":null}),this._updateSelectedVariantCartState()}),Alpine.nextTick(()=>{this._formRef&&(this._mutationObserver=new MutationObserver(mutationList=>{for(const mutation of mutationList){if(mutation.type==="childList"){this._updateSelectedVariantCartState();return}mutation.target.nodeName==="INPUT"&&mutation.target.name==="selling_plan"&&this._updateSelectedVariantCartState()}}),this._mutationObserver.observe(this._formRef,{attributeFilter:["value"],subtree:!0,childList:!0}))}),document.addEventListener(POPUP_OVERLAY_CLICK_EVENT,()=>{this.$store.popup.currentPopup===this.productActionsPopup&&this._handleStickyProductActionsClosure()})}
2,setupShopifyXR(){window.Shopify.loadFeatures([{name:"shopify-xr",version:"1.0",onLoad:this.setupXRElements.bind(this)}])},setupXRElements(errors){if(!errors){if(!window.ShopifyXR){document.addEventListener("shopify_xr_initialized",()=>{this.setupXRElements()});return}window.ShopifyXR.addModels(this.XRMediaModels),window.ShopifyXR.setupXRElements()}},_updateSelectedVariantCartState(){if(!this.selectedVariantId)return;const cartItem=Alpine.store("cart").cartItems.find(this.checkIsItemInCart.bind(this));this.isVariantInCart=!!cartItem,this.variantQty=cartItem?.quantity||1,this.cartItemKey=cartItem?.key},checkIsItemInCart(item){var _a,_b;if(item.isDeleted||item.id!==this.selectedVariantId)return!1;const selling_plan=(_a=this._formRef)==null?void 0:_a.querySelector("input[name=selling_plan]");return!(Number(selling_plan?.value||null)!==Number(((_b=item.selling_plan_allocation)==null?void 0:_b.selling_plan.id)||null)||Object.keys(this.properties).some(key=>{const value=this.properties[key],valueToCheck=value===""?null:value;return(Object.keys(item.properties).length?item.properties:{__shopify_send_gift_card_to_recipient:!1,"Recipient email":null,"Recipient name":null,Message:null,"Send on":null})[key]!==valueToCheck}))},async selectOptionAndSetVariantId(optionIndex,optionValue,variantId,variantImg){var _a;if(!this.selectedOptions)return;if(this.selectedOptions[optionIndex]=optionValue,this.isVariantManuallySelected=!0,this.isVariantAvailable=this.variantsOptions.some(variant=>variant.every(option=>{var _a2;return(_a2=this.selectedOptions)==null?void 0:_a2.includes(option)})),!this.isVariantAvailable){const value=Object.values(this.selectedOptions)[0];variantId=(this.variants.find(v=>v.option1===value)||this.variants.find(v=>v.option2===value)||this.variants.find(v=>v.option3===value)).id}if(this.selectedVariantId===variantId||(this.selectedVariantId=variantId,this._updateSelectedVariantCartState(),this.variantsCount==1))return;const nextUrl=new URL(this.productUrl,document.baseURI);nextUrl.searchParams.set("variant",variantId.toString()),this.sectionId&&nextUrl.searchParams.set("section_id",this.sectionId),nProgress.start();const html=await fetchPage(nextUrl.href),wrapper=document.getElementById(this.sectionId||this.contentId);wrapper.classList.add("disable-fade"),Alpine.store("transition").pageData={...Alpine.store("transition").pageData,variantImg},replaceContent(html,this.sectionId||`${this.contentId}-content`,wrapper),this.isSyncedWithUrl&&history.replaceState(history.state,"",nextUrl.href),this.isScrollingToTop&&this.scrollToTop(),(_a=window.Shopify.PaymentButton)==null||_a.init(),nProgress.done()},toggleStickyProductActions(show){this.$store.popup.currentPopup&&this.$store.popup.currentPopup!==POPUP_BOTTOM_ACTIONS||(show?this.$store.popup.showPopup(POPUP_BOTTOM_ACTIONS,!0):this.$store.popup.hidePopup(POPUP_BOTTOM_ACTIONS))},decreaseQty(){!this.selectedVariantId&&this.variantQty<=0||(this.variantQty-=1,Alpine.store("cart").decreaseQty(this.cartItemKey))},increaseQty(){this.selectedVariantId&&(this.variantQty+=1,Alpine.store("cart").increaseQty(this.cartItemKey))},setQuantity(quantity){this.selectedVariantId&&(this.variantQty=Math.max(0,Number(quantity)),Alpine.store("cart").setQty(quantity,this.cartItemKey))},addToCart(){if(!this.selectedVariantId)return;const formData=new FormData(this._formRef),formProps=Object.fromEntries(formData);this.hideProductActions(),this.$store.cart.addToCart({...formProps,id:this.selectedVariantId,quantity:this.variantQty,properties:this.properties})},hideProductActions(){this._handleStickyProductActionsClosure(),this.$store.popup.hidePopup(this.productActionsPopup)},_handleStickyProductActionsClosure(){const el=document.getElementById("product-actions");el&&el._x_visible&&(this.$store.popup.__popupHistory=this.$store.popup.__popupHistory.filter(p=>p!==POPUP_BOTTOM_ACTIONS))},showProductActions(){this.$store.popup.showPopup(this.productActionsPopup,!0)},quickBuy(singleVariant){if(singleVariant)return this.isVariantInCart?Alpine.store("cart").increaseQty(this.cartItemKey,!0):this.$store.cart.addToCart({id:this.selectedVariantId,quantity:1});this.contentId="product-options",this.showProductActions()},scrollToTop(){typeof this.scrollToPreviewTop<"u"?this.scrollToPreviewTop():window.scrollTo({top:0,behavior:"smooth"})},async fetchProductRecommendations(id,url){const text=await fetchPage(url),html=document.createElement("div");
2html.innerHTML=text;const fallback=html.querySelector(`#${id}`),wrapper=document.querySelector(`#${id}-wrapper`);if(fallback){wrapper.remove();return}const content=html.querySelector(`#${id}-wrapper`);wrapper.innerHTML=content?.innerHTML}}),Dropdown=()=>({isDropdownVisible:!1,_dropdownWrapper:null,_onClick:_event=>{},_onKeydown:_event=>{},init(){Alpine.nextTick(()=>{this._dropdownWrapper=this.$refs.DropdownWrapper})},toggleDropdown(){this.isDropdownVisible?this.hide():this.show()},show(){this.isDropdownVisible=!0,this._onClick=e=>{var _a;(_a=this._dropdownWrapper)!=null&&_a.contains(e.target)||this.hide()},document.addEventListener("click",this._onClick),this._onKeydown=e=>{e.key===ESC_KEY&&this.hide()},document.addEventListener("keydown",this._onKeydown)},hide(){this.isDropdownVisible=!1,document.removeEventListener("click",this._onClick),document.removeEventListener("keydown",this._onKeydown)},search(value){var _a;const options=(_a=this._dropdownWrapper)==null?void 0:_a.querySelectorAll("li a");options?.forEach(option=>{const match=option.outerText.toLowerCase().includes(value.toLowerCase());option.classList.toggle("hidden",!match)})}}),SEARCH_OPTIONS={"resources[type]":"product,collection,query","resources[limit]":"4","resources[limit_scope]":"each"},initialSearch=new URLSearchParams(window.location.search).get("q"),Search=()=>({isLoading:!1,isDropdownVisible:!1,searchTerm:"",searchTermInput:initialSearch||"",queries:[],products:[],categories:[],isNoResults:!1,getIsSearchActive(){return this.isDropdownVisible&&(this.products.length||this.categories.length||this.queries.length||this.isNoResults)},init(){document.addEventListener("click",e=>{e.target.closest("a")&&this.getIsSearchActive()&&this.closePredictiveSearch()}),this.$watch("searchTerm",value=>{value?this.search():(this.queries=[],this.products=[],this.categories=[],this.isNoResults=!1,this.isLoading=!1)}),document.addEventListener("od:after-swap",this.closePredictiveSearch.bind(this)),window.addEventListener("popstate",this.closePredictiveSearch.bind(this))},setSearchTerm(){const nextValue=this.searchTermInput.trim();this.searchTerm!==nextValue&&(this.isLoading=!0),this.searchTerm=nextValue,this.isDropdownVisible=!!nextValue},resetSearchTerm(){this.searchTermInput="",this.searchTerm="",this.queries=[],this.products=[],this.categories=[],this.isNoResults=!1,this.isLoading=!1,this.isDropdownVisible=!1},closePredictiveSearch(){this.isDropdownVisible=!1},search(){this.isLoading=!0;const urlParams=new URLSearchParams(SEARCH_OPTIONS);urlParams.set("q",this.searchTerm);const searchQuery=urlParams.toString();fetch(`${window.Shopify.routes.root}search/suggest.json?${searchQuery}`).then(response=>response.json()).then(suggestions=>{this.queries=suggestions.resources.results.queries,this.products=suggestions.resources.results.products,this.categories=suggestions.resources.results.collections,this.isNoResults=!this.queries.length&&!this.products.length&&!this.categories.length}).catch(error=>console.error("Error:",error)).finally(()=>this.isLoading=!1)},goToSearchPage(path){this.closePredictiveSearch(),navigateWithTransition(this.getSearchUrl(path),{type:"search",animate:!0,data:{search:this.searchTermInput}})},getSearchUrl(path){return this.searchTermInput?`${path}?q=${encodeURIComponent(this.searchTermInput.trim())}`:path}}),Accordion=(isExpanded=!1,duration=0,onlyMobile=!1)=>({_buttonRef:null,_panelRef:null,_iconRef:null,isExpanded:!!isExpanded,duration:Number(duration),init(){onlyMobile&&!Alpine.store("main").isMobile||(this._initElements(),Alpine.nextTick(()=>{this._update(),this.$watch("isExpanded",this._update.bind(this))}))},_initElements(){this._buttonRef=this.$refs.AccordionButton,this._panelRef=this.$refs.AccordionPanel,this._iconRef=this.$refs.AccordionIcon,this._buttonRef&&this._buttonRef.addEventListener("click",this._toggle.bind(this)),this._panelRef&&(this._panelRef.style.transitionDuration=`${this.duration}ms`),this._iconRef&&(this._iconRef.style.transitionProperty="rotate",this._iconRef.style.transitionDuration=`${this.duration}ms`)},_toggle(){this.isExpanded=!this.isExpanded},_update(){if(this._panelRef){this._panelRef.style.opacity=this.isExpanded?"1":"0";const containerMaxheight=this._panelRef.scrollHeight?`${String(this._panelRef.scrollHeight)}px`:"10000px";this._panelRef.style.maxHeight=this.isExpanded?containerMaxheight:"0"}this._iconRef&&(this._iconRef.style.rotate=this.isExpanded?"-180deg":"")}}),Address=()=>({renderedPage:"",address:{},province:null,deleteId:null,editId:null,_onKeyDown(e){e.key===ESC_KEY&&this.hideForm()},showForm(page,popup_id){if(this.focusableEl=document.activeElement,document.addEventListener("keydown",this._onKeyDown.bind(this)),this._updateProvince(this.$refs.address_country),Alpine.store("main").isMobile){Alpine.store("popup").showPopup(popup_id,!0);return}this.renderedPage=page,this._focusOnForm(popup_id)},_focusOnForm(popup_id){setTimeout(()=>{var _a;const firstEl=(_a=document.querySelector(`#${popup_id}-desktop form`))==null?void 0:_a.querySelector("a, button, textarea, input
2:not([type=hidden]), select");firstEl?.focus()},150)},hideForm(){document.removeEventListener("keydown",this._onKeyDown),this.renderedPage="",this.address={},this.deleteId=null,this.editId=null,setTimeout(()=>{var _a;(_a=this.focusableEl)==null||_a.focus(),this.focusableEl=null},150)},updateCountry(e){const country=e.target;this.address.country=country.selectedOptions[0].text,this._updateProvince(country)},_updateProvince(country){Alpine.nextTick(()=>{this.province=JSON.parse(country?.selectedOptions[0].dataset.provinces||"[]")})}}),ANIMATION_DURATION=300,RangeSlider=(min,max,minValue,maxValue)=>({isLeftThumbActive:!1,isRightThumbActive:!1,isResetting:!1,min:Number(min),max:Number(max),minValue:Number(minValue),maxValue:Number(maxValue),onMinValueInput(){this.isLeftThumbActive=!0,this.minValue=Math.min(this.minValue,this.maxValue-1)},onMaxValueInput(){this.isRightThumbActive=!0,this.maxValue=Math.max(this.maxValue,this.minValue+1)},onValueChange(){this.isLeftThumbActive=!1,this.isRightThumbActive=!1,this.updateFilters()},onTrackClick(event){const trackPosition=event.target.getBoundingClientRect(),clickPosition=event.pageX-trackPosition.left,midpoint=this.minValue+(this.maxValue-this.minValue)/2,pxByUnit=(trackPosition.right-trackPosition.left)/(this.max-this.min),clickedValue=Math.round(clickPosition/pxByUnit);this.isResetting=!0,clickedValue>midpoint?this.maxValue=clickedValue:this.minValue=clickedValue,setTimeout(()=>{this.isResetting=!1,this.onValueChange()},ANIMATION_DURATION)},resetValues(){(!this.$event.detail.name||this.$event.detail.name===FILTER_PRICE||this.$event.detail.name===FILTER_PRICE_MIN)&&(this.isResetting=!0,this.minValue=this.min),(!this.$event.detail.name||this.$event.detail.name===FILTER_PRICE||this.$event.detail.name===FILTER_PRICE_MAX)&&(this.isResetting=!0,this.maxValue=this.max),setTimeout(()=>{this.isResetting=!1},ANIMATION_DURATION)}}),SCROLLBAR_AUTO_HIDE_CLASS="scrollbar-auto-hide",SCROLLBAR_AUTO_HIDE_ACTIVE_CLASS="scrollbar-auto-hide--active",SCROLLBAR_AUTO_HIDE_DELAY=900,scrollbarAutoHideTimers=new WeakMap,scrollbarAutoHidePositions=new WeakMap;function setScrollbarAutoHideActive(element){if(!element||!element.classList||element.scrollWidth<=element.clientWidth)return;element.classList.add(SCROLLBAR_AUTO_HIDE_ACTIVE_CLASS);const previousTimer=scrollbarAutoHideTimers.get(element);previousTimer&&window.clearTimeout(previousTimer),scrollbarAutoHideTimers.set(element,window.setTimeout(()=>{element.classList.remove(SCROLLBAR_AUTO_HIDE_ACTIVE_CLASS),scrollbarAutoHideTimers.delete(element)},SCROLLBAR_AUTO_HIDE_DELAY))}typeof document<"u"&&typeof window<"u"&&!window.__odScrollbarAutoHideInit&&(window.__odScrollbarAutoHideInit=!0,document.addEventListener("scroll",event=>{const target=event.target instanceof Element?event.target.closest(`.${SCROLLBAR_AUTO_HIDE_CLASS}`):null;if(!target)return;const currentScrollLeft=target.scrollLeft,previousScrollLeft=scrollbarAutoHidePositions.get(target);scrollbarAutoHidePositions.set(target,currentScrollLeft),!(previousScrollLeft===void 0&&currentScrollLeft===0)&&(previousScrollLeft!==void 0&&previousScrollLeft===currentScrollLeft||setScrollbarAutoHideActive(target))},{capture:!0,passive:!0}));const FEATURED_COLLECTION_SLIDER_SELECTOR=".featured-collection-section-slider",FEATURED_COLLECTION_MOBILE_QUERY="(max-width: 639px)",FEATURED_COLLECTION_HIDE_VIEW_ALL_ATTR="data-featured-collection-hide-view-all-mobile";let featuredCollectionHeaderRaf=null;function getFeaturedCollectionTitleMetrics(titleText){const style=window.getComputedStyle(titleText),fontSize=Number.parseFloat(style.fontSize)||16,lineHeight=Number.parseFloat(style.lineHeight)||fontSize*1.2,rect=titleText.getBoundingClientRect();return{lineCount:Math.round(rect.height/lineHeight),lineHeight,rect}}function updateFeaturedCollectionHeader(root=document){const isMobile2=window.matchMedia(FEATURED_COLLECTION_MOBILE_QUERY).matches;(root instanceof Element&&root.matches(FEATURED_COLLECTION_SLIDER_SELECTOR)?[root]:Array.from(root.querySelectorAll(FEATURED_COLLECTION_SLIDER_SELECTOR))).forEach(sli
2der=>{if(slider.removeAttribute(FEATURED_COLLECTION_HIDE_VIEW_ALL_ATTR),!isMobile2)return;const viewAll=slider.querySelector(".featured-collection__view-all-wrap"),titleText=slider.querySelector(".featured-collection__title-text");if(!viewAll||!titleText)return;const titleMetrics=getFeaturedCollectionTitleMetrics(titleText),isViewAllWrapped=viewAll.getBoundingClientRect().top>titleMetrics.rect.top+titleMetrics.lineHeight*.5;(titleMetrics.lineCount>1||isViewAllWrapped)&&slider.setAttribute(FEATURED_COLLECTION_HIDE_VIEW_ALL_ATTR,"true")})}function queueFeaturedCollectionHeaderUpdate(root=document){featuredCollectionHeaderRaf!==null&&window.cancelAnimationFrame(featuredCollectionHeaderRaf),featuredCollectionHeaderRaf=window.requestAnimationFrame(()=>{featuredCollectionHeaderRaf=null,updateFeaturedCollectionHeader(root)})}typeof document<"u"&&typeof window<"u"&&!window.__odFeaturedCollectionHeaderInit&&(window.__odFeaturedCollectionHeaderInit=!0,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>queueFeaturedCollectionHeaderUpdate(),{once:!0}):queueFeaturedCollectionHeaderUpdate(),window.addEventListener("resize",()=>queueFeaturedCollectionHeaderUpdate(),{passive:!0}),document.addEventListener("shopify:section:load",event=>queueFeaturedCollectionHeaderUpdate(event.target)),document.addEventListener("od:after-swap",()=>queueFeaturedCollectionHeaderUpdate()));const Slider=()=>({isPrevBtnDisabled:!0,isNextBtnDisabled:!1,currentSlideIndex:1,resizeObserver:null,slideWidth:null,config:{},autoplayInterval:null,deferredObserver:null,hasStarted:!1,startupTasks:[],debouncedHandleManualScroll:()=>{},queueStartupTask(callback){const task={rafId:null,timeoutId:null},cleanupTask=()=>{this.startupTasks=this.startupTasks.filter(item=>item!==task)},runTask=()=>{task.timeoutId=window.setTimeout(()=>{cleanupTask(),!(!this.hasStarted||!this.$root||!this.$refs.slider)&&callback()},0)};"requestAnimationFrame"in window?task.rafId=window.requestAnimationFrame(runTask):runTask(),this.startupTasks.push(task)},clearStartupTasks(){this.startupTasks.forEach(task=>{task.rafId!==null&&window.cancelAnimationFrame(task.rafId),task.timeoutId!==null&&window.clearTimeout(task.timeoutId)}),this.startupTasks=[]},configureAndStart(config){this.hasStarted||(this.config=config,this.hasStarted=!0,this.start(),this.queueStartupTask(()=>{this.play()}))},initWhenReady(config){this.config=config;const startNow=()=>{this.teardownDeferredStart(),this.configureAndStart(config)};if(!this.$root||!this.$refs.slider){startNow();return}const firstHomepageFeaturedCollectionSlider=document.querySelector("#MainContent .featured-collection-slider"),isFirstHomepageFeaturedCollectionSlider=!!document.querySelector(".od-index-header-spacer")&&firstHomepageFeaturedCollectionSlider===this.$root,rect=this.$root.getBoundingClientRect();if(isFirstHomepageFeaturedCollectionSlider||config.isEager||config.isAutoplay||rect.top<window.innerHeight+200){startNow();return}if(!("IntersectionObserver"in window)){startNow();return}const onInteraction=()=>startNow();this._deferredStartOnInteraction=onInteraction,["pointerenter","touchstart","focusin"].forEach(eventName=>{this.$root.addEventListener(eventName,onInteraction,{passive:!0,once:!0})}),this.deferredObserver=new IntersectionObserver(entries=>{entries.forEach(entry=>{!entry.isIntersecting&&entry.intersectionRatio<=0||startNow()})},{rootMargin:"400px 0px 400px 0px",threshold:.01}),this.deferredObserver.observe(this.$root)},teardownDeferredStart(){this.deferredObserver&&(this.deferredObserver.disconnect(),this.deferredObserver=null),this._deferredStartOnInteraction&&this.$root&&(["pointerenter","touchstart","focusin"].forEach(eventName=>{this.$root.removeEventListener(eventName,this._deferredStartOnInteraction)}),this._deferredStartOnInteraction=null)},play(){const{isAutoplay,autoplaySpeed=5e3}=this.config;isAutoplay&&(this.autoplayInterval&&window.clearInterval(this.autoplayInterval),this.autoplayInterval=window.setInterval(()=>{this.currentSlideIndex<this.$refs.slider.childElementCount?this.goToSlide(this.currentSlideIndex+1):this.goToSlide(1)},autoplaySpeed))},start(){const debouncedResizeHandler=Alpine.debounce(()=>{this.updateCachedValues(),this.handleManualScroll()},100);this.updateCachedValues(),this.debouncedHandleManualScroll=Alpine.debounce(()=>{this.handleManualScroll()},100),this.debouncedHandleManualScroll(),this.queueStartupTask(()=>{this.resizeObserver||!this.$refs.slider||(this.resizeObserver=new ResizeObserver(debouncedResizeHandler),this.resizeObserver.observe(this.$refs.slider))}),this.queueStartupTask(()=>{const{gap}=this.config,proxScrollTarget=(this.currentSlideIndex-1)*((this.slideWidth||1)+gap);this.$refs.slider.scrollTo({left:proxScrollTarget,behavior:"smooth"})})},destroy(){this.teardownDeferredStart(),this.clearStartupTasks(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.autoplayInterval&&(window.clearInterval(this.autoplayInterval),this.autoplayInterval=null)},updateCachedValues(){this.$refs.slider&&this.$refs.slider.childElementCount&&(this.slideWidth=this.$refs.slider.children[0].offsetWidth)},goToSlide(index,focus=!1){const{gap}=this.config,maxIndex=this.$refs.slider.childElementCount,validIndex=Math.max(1,Math.min(index,maxIndex)),proxScrollTarget=(validIndex-1)*((this.slideWidth||1)+gap);this.$refs.slider.scrollTo({left:proxScrollTarget,behavior:Alpine.store("main").isReducedMotion?"instant":"smooth"}),focus&&setTimeout(()=>{this.$refs.slider.children[index-1].querySelector(SELECTOR_LIST).focus()},Alpine.store("main").isReducedMotion?0:500),this.currentSlideIndex=validIndex},showNextSlide(){const nextIndex=this.currentSlideIndex+Math.floor(this.getSlidesAmountInView())<=this.$refs.slider.childElementCount?this.currentSlideIndex+Math.floor(this.getSlidesAmountInView()):this.$refs.slider.childElementCount;this.goToSlide(nextIndex),this.play()},showPrevSlide(){const prevIndex=this.currentSlideIndex-Math.floor(this.getSlidesAmountInView())>=1?this.currentSlideIndex-Math.floor(this.getSlidesAmountInView()):1;this.goToSlide(prevIndex),this.play()},handleManualScroll(){if(!this.$refs.slider)return;const{gap}=this.config,containerScrollLeft=this.$refs.slider.scrollLeft,currentSlideIndex=Math.ceil(containerScrollLeft/((this.slideWidth||1)+gap))+1;this.currentSlideIndex=currentSlideIndex,this.isNextBtnDisabled=currentSlideIndex>Math.ceil(this.$refs.slider.childElementCount-this.getSlidesAmountInView()),this.isPrevBtnDisabled=currentSlideIndex<=1},getSlidesAmountInView(){const{slidesAmountInView:{xs,sm,md,lg,xl,xxl}}=this.config,viewWidth=Math.max(document.documentElement.clientWidth||0,window.innerWidth||0),screenSm=640,screenMd=768,screenLg=1024,screenXl=1280;return viewWidth>=1536?xxl:viewWidth>=screenXl?xl:viewWidth>=screenLg?lg:viewWidth>=screenMd?md:viewWidth>=screenSm?sm:xs}}),CountdownTimer=(targetDateString="",isInfinite=!1,remainingChunk={days:0,hours:0,minutes:0,seconds:0})=>({targetDateString,isLoaded:!1,isFinished:!1,isInfinite,remainingChunk,init(){let target=new Date(this.targetDateString);const now=new Date;let remainingTime=Number(target)-Number(now);if(this.isInfinite)for(;target<now;)target=new Date(target.setDate(target.getDate()+14)),remainingTime=Number(target)-Number(now);if(remainingTime<=0){this.isFinished=!0,this.isLoaded=!0,this.remainingChunk={days:0,hours:0,minutes:0,seconds:0};return}this.isLoaded=!0;var timerId=setInterval(()=>{const now2=new Date,remainingTime2=Number(target)-Number(now2);remainingTime2<=0?(clearInterval(timerId),this.isFinished=!0):this.remainingChunk={days:Math.floor(remainingTime2/(1e3*60*60*24)),hours:Math.floor(remainingTime2/(1e3*60*60)%24),minutes:Math.floor(remainingTime2/1e3/60%60),seconds:Math.floor(remainingTime2/1e3%60)}},1e3)}}),TransitionImage=props=>({src:"",isImgLoaded:!1,init(){this.src||(this.isImgLoaded=!0),this.src=props.src;const{imageId:mainImageId}=props,mainImage=document.getElementById(mainImageId);mainImage&&(mainImage.complete?this.isImgLoaded=!0:mainImage.addEventListener("load",()=>{this.isImgLoaded=!0},{once:!0}))}}),ZOOM_RATIO=2,minScale=1,maxScale=3,getDistance=(touch1,touch2)=>{const dx=touch1.clientX-touch2.clientX,dy=touch1.clientY-touch2.clientY;return Math.sqrt(dx*dx+dy*dy)},ImageZoom=()=>
2({previousTouches:null,scale:1,translate:{x:0,y:0},resetTimeoutRef:null,reset:!1,init(){this.$watch("scale",()=>{Alpine.store("main").opacityOnZoom=Math.max(2-this.scale,0)})},zoomImage(e){if(Alpine.store("main").isMobile)return;const img=e.currentTarget.querySelector("img:not(.transition-image)"),overlayImage=document.createElement("img");overlayImage.setAttribute("src",img.src);const overlay=document.createElement("div");overlay.setAttribute("class","zoomed-img"),overlay.setAttribute("aria-hidden","true"),overlay.style.backgroundImage=`url('${img.src}')`,overlayImage.onload=()=>{img.parentElement.insertBefore(overlay,img)},overlay.onclick=event=>{event.stopPropagation(),overlay.remove()},overlay.onmousemove=event=>this.moveWithHover(img,event,overlay),overlay.onmouseleave=()=>overlay.remove(),this.moveWithHover(img,e,overlay)},moveWithHover(img,event,overlay){const ratio=img.height/img.width,container=event.currentTarget.getBoundingClientRect(),xPosition=event.clientX-container.left,yPosition=event.clientY-container.top,xPercent=`${xPosition/(img.clientWidth/100)}%`,yPercent=`${yPosition/(img.clientWidth*ratio/100)}%`;overlay.style.backgroundPosition=`${xPercent} ${yPercent}`,overlay.style.backgroundSize=`${img.width*ZOOM_RATIO}px`},onTouchStart(event){event.touches.length===2&&(event.preventDefault(),this.previousTouches=event.touches)},onTouchMove(event){if(event.touches.length===2&&this.previousTouches){event.preventDefault();const newDistance=getDistance(event.touches[0],event.touches[1]),oldDistance=getDistance(this.previousTouches[0],this.previousTouches[1]),scaleChange=newDistance/oldDistance,newScale=Math.min(maxScale,Math.max(minScale,this.scale*scaleChange)),midPoint={x:(event.touches[0].clientX+event.touches[1].clientX)/2,y:(event.touches[0].clientY+event.touches[1].clientY)/2},previousMidPoint={x:(this.previousTouches[0].clientX+this.previousTouches[1].clientX)/2,y:(this.previousTouches[0].clientY+this.previousTouches[1].clientY)/2},movementX=midPoint.x-previousMidPoint.x,movementY=midPoint.y-previousMidPoint.y;if(event.currentTarget){const rect=event.currentTarget.getBoundingClientRect(),xCenter=(rect.left+rect.right)/2,yCenter=(rect.top+rect.bottom)/2,xDiff=midPoint.x-xCenter,yDiff=midPoint.y-yCenter,scalingTranslateX=(this.translate.x-xDiff)*(newScale/this.scale)+xDiff,scalingTranslateY=(this.translate.y-yDiff)*(newScale/this.scale)+yDiff;this.translate={x:scalingTranslateX+movementX,y:scalingTranslateY+movementY}}this.scale=newScale,this.reset=!1,this.previousTouches=event.touches}},onTouchEnd(){this.previousTouches=null,this.resetAfterDelay()},onWheel(event){if(!event.ctrlKey)return;event.preventDefault();const scaleChange=1-event.deltaY*.01,newScale=Math.min(maxScale,Math.max(minScale,this.scale*scaleChange));if(event.currentTarget){const rect=event.currentTarget.getBoundingClientRect(),xCenter=(rect.left+rect.right)/2,yCenter=(rect.top+rect.bottom)/2,xDiff=event.clientX-xCenter,yDiff=event.clientY-yCenter,translateX=(this.translate.x-xDiff)*(newScale/this.scale)+xDiff,translateY=(this.translate.y-yDiff)*(newScale/this.scale)+yDiff;this.translate={x:translateX,y:translateY}}this.scale=newScale,this.reset=!1,this.resetAfterDelay(!0)},resetAfterDelay(wheel=!1){this.resetTimeoutRef!==null&&clearTimeout(this.resetTimeoutRef),this.resetTimeoutRef=window.setTimeout(()=>{this.scale=1,this.translate={x:0,y:0},this.reset=!0},wheel?300:0)}});let Sunrise={updateQuantity(line,qty){fetch("/cart/change.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({quantity:qty,line})}).then(response=>response.json()).then(data=>{const cartStore=window.Alpine&&Alpine.store&&Alpine.store("cart");cartStore&&typeof cartStore.applyCartState=="function"&&cartStore.applyCartState(data),window.dispatchEvent(new Event("cart-updated"))}).catch(error=>{console.error("Error:",error)})}};document.addEventListener("click",evt=>{if(!evt.target.closest("[data-open-login]"))return;evt.preventDefault();const loginUrl=`${window.Shopify?.routes?.root||"/"}account/login?return_url=/pages/my-library`;document.body.classList.add("is-navigating"),window.location.href=loginUrl});const LIGHTBOX_IMAGE_WAIT_MS=3e3;let lightboxOpenToken=0;function waitForLightboxImage(img){if(!img)return Promise.resolve();const decode=()=>typeof img.decode=="function"?img.decode().catch(()=>{}):Promise.resolve();return img.complete?decode():new Promise(resolve=>{img.addEventListener("load",resolve,{once:!0}),img.addEventListener("error",resolve,{once:!0})}).then(decode)}function waitForLightboxImages(root){const images=Array.from(root.querySelectorAll("img"));
2images.forEach(img=>{img.loading==="lazy"&&(img.loading="eager"),img.classList.remove("opacity-0")});const primary=root.querySelector(".od-product-lightbox__gallery img")||images[0];return Promise.race([waitForLightboxImage(primary),new Promise(resolve=>setTimeout(resolve,LIGHTBOX_IMAGE_WAIT_MS))])}function revealLightbox(overlay){overlay.style.display="flex",overlay.classList.remove("show"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{overlay.classList.add("show")})})}document.addEventListener("click",async evt=>{const btn=evt.target.closest(".info-button[data-handle][data-lightbox-view]");if(!btn)return;const handle=btn.getAttribute("data-handle"),view=btn.getAttribute("data-lightbox-view");if(!handle||!view)return;const overlay=document.getElementById("lightbox-overlay"),inner=document.getElementById("lightbox-inner-content");if(!overlay||!inner)return;const url=`/products/${handle}?view=${view}`,token=++lightboxOpenToken,progress=typeof nProgress<"u"?nProgress:null;progress&&progress.start();try{const res=await fetch(url,{credentials:"same-origin"});if(!res.ok)throw new Error("Unable to load lightbox.");const html=await res.text();if(token!==lightboxOpenToken||(overlay.classList.remove("show"),overlay.style.display="flex",inner.innerHTML=html,await waitForLightboxImages(inner),token!==lightboxOpenToken))return;revealLightbox(overlay)}catch(err){if(token!==lightboxOpenToken)return;console.error("Lightbox load error:",err),inner.innerHTML=`<p>Error loading info for ${handle}</p>`,revealLightbox(overlay)}finally{progress&&token===lightboxOpenToken&&progress.done()}});function closeLightbox(){const overlay=document.getElementById("lightbox-overlay"),inner=document.getElementById("lightbox-inner-content");!overlay||!inner||!overlay.classList.contains("show")||(overlay.classList.remove("show"),document.body.style.overflow="",setTimeout(()=>{overlay.classList.contains("show")||(overlay.style.display="none",inner.innerHTML="")},350))}if(document.addEventListener("click",evt=>{evt.target.closest(".lightbox-close, .lightbox-close-btn")&&closeLightbox()}),window.addEventListener("click",evt=>{const target=evt.target instanceof Element?evt.target:null;if(target){if(target.closest("#lightbox-overlay .opera-player-launch")){setTimeout(()=>{document.documentElement.classList.contains("od-csgate-open")||closeLightbox()},0);return}target.closest(".od-csgate__button")&&closeLightbox()}},!0),window.addEventListener("pushstate",closeLightbox),window.addEventListener("popstate",closeLightbox),(()=>{const MODULE_ID="od-membership-access";if(window[MODULE_ID])return;window[MODULE_ID]=!0;function ensureAccessRoot(){return window.ODMembershipAccess=window.ODMembershipAccess||{},window.ODMembershipAccess.state=window.ODMembershipAccess.state||{},window.ODMembershipAccess.config=window.ODMembershipAccess.config||{},window.ODMembershipAccess}function normalizeBoolean(value,fallback){if(typeof value=="boolean")return value;if(typeof value=="string"){if(value==="true")return!0;if(value==="false")return!1}return fallback}function normalizeObject(value){return value&&typeof value=="object"?value:null}function normalizeCustomerTier(value){const normalized=String(value??"").trim().toLowerCase();return["non_member","member","collector","patron"].includes(normalized)?normalized:"non_member"}function normalizePolicyAccess(value,allowedValues,fallback){const normalized=String(value??"").trim().toLowerCase();return allowedValues.includes(normalized)?normalized:fallback}function normalizeCustomerPlaybackPolicy(value){const row=normalizeObject(value)||{},purchaseDiscountPercent=Number(row.purchaseDiscountPercent);return{catalogueAccess:normalizePolicyAccess(row.catalogueAccess,["samples","compressed","lossless"],"samples"),comingSoonAccess:normalizePolicyAccess(row.comingSoonAccess,["none","samples","compressed","lossless"],"none"),purchaseDiscountPercent:Number.isFinite(purchaseDiscountPercent)&&purchaseDiscountPercent>=0&&purchaseDiscountPercent<=100?purchaseDiscountPercent:0}}function normalizePlaybackPolicy(value){const policy=normalizeObject(value);if(!policy)return null;const sourceTiers=normalizeObject(policy.tiers)||{},tiers={};return["non_member","member","collector","patron"].forEach(tier=>{tiers[tier]=normalizeCustomerPlaybackPolicy(sourceTiers[tier])}),Object.assign({},policy,{tiers})}
2function resolveCustomerPlaybackPolicy(playbackPolicy,customerTier){const tiers=normalizeObject(playbackPolicy&&playbackPolicy.tiers)||{};return normalizeCustomerPlaybackPolicy(tiers[normalizeCustomerTier(customerTier)])}function getCustomerTierValue(source){const customer=normalizeObject(source&&source.customer)||{};if(source&&source.customerTier!==void 0)return source.customerTier;if(source&&source.customer_tier!==void 0)return source.customer_tier;if(customer.customerTier!==void 0)return customer.customerTier;if(customer.customer_tier!==void 0)return customer.customer_tier}function hasCustomerTierValue(source){const customer=normalizeObject(source&&source.customer)||{};return!!(source&&(source.customerTier!==void 0||source.customer_tier!==void 0||customer.customerTier!==void 0||customer.customer_tier!==void 0))}function setCustomerAccessAttributes(state){const customerTier=normalizeCustomerTier(state&&state.customerTier),customerPlaybackPolicy=normalizeCustomerPlaybackPolicy(state&&state.customerPlaybackPolicy);document.documentElement.setAttribute("data-customer-tier",customerTier),document.documentElement.setAttribute("data-catalogue-access",customerPlaybackPolicy.catalogueAccess),document.documentElement.setAttribute("data-coming-soon-access",customerPlaybackPolicy.comingSoonAccess)}function isPolicyDateActive(value,compare){if(!value)return!0;const timestamp=Date.parse(String(value));return Number.isFinite(timestamp)?compare(timestamp):!1}function isGlobalCatalogueOverrideActive(policy){const normalizedPolicy=normalizeObject(policy),releasedCatalogue=normalizeObject(normalizedPolicy&&normalizedPolicy.releasedCatalogue),openHouse=normalizeObject(releasedCatalogue&&releasedCatalogue.openHouse)||{};if(!releasedCatalogue||releasedCatalogue.access!=="open_house")return!1;const now=Date.now();return isPolicyDateActive(openHouse.startsAt,timestamp=>timestamp<=now)&&isPolicyDateActive(openHouse.endsAt,timestamp=>timestamp>now)}function normalizeAccessPayload(payload){const source=payload&&typeof payload=="object"?payload:{},customer=source.customer&&typeof source.customer=="object"?source.customer:{},policy=normalizeObject(source.globalAccessPolicy)||normalizeObject(source.global_access_policy)||normalizeObject(source.policy),playbackPolicy=normalizePlaybackPolicy(source.playbackPolicy||source.playback_policy),customerTier=normalizeCustomerTier(getCustomerTierValue(source)),customerPlaybackPolicy=resolveCustomerPlaybackPolicy(playbackPolicy,customerTier),rawStatus=source.membershipStatus||source.membership_status||source.status||customer.membershipStatus||customer.membership_status||"",membershipStatus=String(rawStatus||"").trim().toLowerCase(),loggedIn=normalizeBoolean(source.loggedIn,normalizeBoolean(source.logged_in,normalizeBoolean(customer.loggedIn,normalizeBoolean(customer.logged_in,!1)))),acceptsMarketing=normalizeBoolean(source.acceptsMarketing,normalizeBoolean(source.accepts_marketing,normalizeBoolean(customer.acceptsMarketing,normalizeBoolean(customer.accepts_marketing,!1))));return{customerId:source.customerId||source.customer_id||customer.customerId||customer.customer_id||null,customerTier,loggedIn,acceptsMarketing,membershipStatus,memberStreamingEligible:normalizeBoolean(source.memberStreamingEligible,normalizeBoolean(source.member_streaming_eligible,membershipStatus==="active"||membershipStatus==="trialing")),discountEligible:normalizeBoolean(source.discountEligible,normalizeBoolean(source.discount_eligible,membershipStatus==="active")),globalCatalogueOverride:normalizeBoolean(source.globalCatalogueOverride,normalizeBoolean(source.global_catalogue_override,isGlobalCatalogueOverrideActive(policy))),globalAccessPolicy:policy,globalAccessPolicySource:source.globalAccessPolicySource||source.global_access_policy_source||source.source||null,globalAccessPolicyFallbackReason:source.globalAccessPolicyFallbackReason||source.global_access_policy_fallback_reason||source.fallbackReason||null,playbackPolicy,playbackPolicySource:source.playbackPolicySource||source.playback_policy_source||null,playbackPolicyFallbackReason:source.playbackPolicyFallbackReason||source.playback_policy_fallback_reason||null,customerPlaybackPolicy}}
2function getAccessState(){return normalizeAccessPayload(ensureAccessRoot().state)}function getCustomerId(){const accessRoot2=ensureAccessRoot(),stateCustomerId=accessRoot2&&accessRoot2.state?accessRoot2.state.customerId:null;if(stateCustomerId!=null&&String(stateCustomerId).trim()!=="")return String(stateCustomerId);const shopifyCustomerId=window.Shopify&&window.Shopify.customer?window.Shopify.customer.id:null;return shopifyCustomerId!=null&&String(shopifyCustomerId).trim()!==""?String(shopifyCustomerId):""}function setAccessState(nextState){const accessRoot2=ensureAccessRoot(),current=normalizeObject(accessRoot2.state)||{},update=normalizeObject(nextState)||{},merged=Object.assign({},current,update);hasCustomerTierValue(update)&&(merged.customerTier=getCustomerTierValue(update));const normalized=normalizeAccessPayload(merged);return accessRoot2.state=normalized,setCustomerAccessAttributes(normalized),document.dispatchEvent(new CustomEvent("od:membership-access-updated",{detail:normalized})),normalized}function getEndpoint(){return String((ensureAccessRoot().config||{}).endpoint||"").trim()}function getGlobalAccessPolicyEndpoint(){const config=ensureAccessRoot().config||{};return String(config.globalAccessPolicyEndpoint||config.global_access_policy_endpoint||"").trim()}function getLegacyStreamingPolicyEndpoint(primaryEndpoint){const config=ensureAccessRoot().config||{},configuredFallback=String(config.legacyStreamingPolicyEndpoint||config.legacy_streaming_policy_endpoint||"").trim();if(configuredFallback)return configuredFallback;const endpoint=String(primaryEndpoint||getGlobalAccessPolicyEndpoint()).trim();return endpoint?endpoint.replace("/global-access-policy","/streaming-policy"):""}function resolveEndpointUrl(endpoint){if(!endpoint)return"";try{return new URL(endpoint,window.location.origin).toString()}catch{return""}}function uniqueStrings(values){return values.filter((value,index)=>value&&values.indexOf(value)===index)}async function fetchJsonEndpoint(endpoint){const url=resolveEndpointUrl(endpoint);if(!url)throw new Error("Global access policy endpoint is invalid");const sameOrigin=new URL(url).origin===window.location.origin,response=await fetch(url,{method:"GET",mode:sameOrigin?"same-origin":"cors",credentials:sameOrigin?"same-origin":"omit",headers:{Accept:"application/json"}}),data=await response.json().catch(()=>({}));if(!response.ok||data.ok===!1)throw new Error(data.error||"Global access policy refresh failed");return data}function normalizeGlobalAccessPolicyState(data){const source=data&&typeof data=="object"?data:{},policy=normalizeObject(source.globalAccessPolicy)||normalizeObject(source.global_access_policy)||normalizeObject(source.policy),playbackPolicy=normalizePlaybackPolicy(source.playbackPolicy||source.playback_policy);if(!policy)throw new Error("Global access policy response is missing policy data");return{globalCatalogueOverride:isGlobalCatalogueOverrideActive(policy),globalAccessPolicy:policy,globalAccessPolicySource:source.globalAccessPolicySource||source.global_access_policy_source||source.source||null,globalAccessPolicyFallbackReason:source.globalAccessPolicyFallbackReason||source.global_access_policy_fallback_reason||source.fallbackReason||null,playbackPolicy,playbackPolicySource:source.playbackPolicySource||source.playback_policy_source||null,playbackPolicyFallbackReason:source.playbackPolicyFallbackReason||source.playback_policy_fallback_reason||null}}function getUnlockFlowUrl(){return String((ensureAccessRoot().config||{}).unlockFlowUrl||"/collections/free-streaming-titles#free-streaming-unlock-flow").trim()}function getLockedFreeStreamingCard(element){if(!element||typeof element.closest!="function")return null;const lockedTrigger=element.closest('[data-locked-play-trigger="true"]');if(!lockedTrigger)return null;const lockedCard=lockedTrigger.closest("[data-free-streaming-locked-trigger][data-lock-state]");return!lockedCard||!lockedCard.closest('[data-free-streaming-collection-page][data-collection-handle="free-streaming-titles"]')?null:lockedCard}function handleLockedFreeStreamingPlayTriggerEvent(event){const lockedCard=getLockedFreeStreamingCard(event&&event.target);if(!lockedCard)return!1;event&&typeof event.preventDefault=="function"&&event.preventDefault(),event&&typeof event.stopPropagation=="function"&&event.stopPropagation(),event&&typeof event.stopImmediatePropagation=="function"&&event.stopImmediatePropagation();const lockedTrigger=event.target.closest('[data-locked-play-trigger="true"]'),lastOpenedAt=lockedTrigger?Number(lockedTrigger.dataset.lockLightboxOpenedAt||0):0,now=Date.now();if(lockedTrigger){if(now-lastOpenedAt<400)return!0;lockedTrigger.dataset.lockLightboxOpenedAt=String(now)}return openAccessLightbox(lockedCard.getAttribute("data-lock-state")),!0}function getLightboxElements(){const overlay=document.getElementById("lightbox-overlay"),inner=document.getElementById("lightbox-inner-content");return{overlay,inner}}function hideLightbox(immediate){const{overlay,inner}=getLightboxElements();if(!(!overlay||!inner)){if(overlay.classList.remove("show"),document.body.style.overflow="",immediate){overlay.style.display="none",inner.innerHTML="";return}window.setTimeout(()=>{overlay.style.display="none",inner.innerHTML=""},350)}}function showLightbox(html){const{overlay,inner}=getLightboxElements();!overlay||!inner||(inner.innerHTML=html,overlay.style.display="flex",overlay.classList.remove("show"),document.body.style.overflow="hidden",requestAnimationFrame(()=>{requestAnimationFrame(()=>{overlay.classList.add("show")})}
2))}function getUnlockLightboxMarkup(){const unlockFlowTemplate=document.getElementById("free-streaming-unlock-flow-template");if(unlockFlowTemplate&&unlockFlowTemplate.content){const content=unlockFlowTemplate.content.firstElementChild?unlockFlowTemplate.content.firstElementChild.cloneNode(!0):null,form=content?content.querySelector("[data-free-streaming-unlock-form]"):null;if(!content)return`
3          <div class="lightbox-content od-access-lightbox" role="dialog" aria-modal="true" aria-labelledby="ODAccessUnlockFallbackHeading">
4            <button class="lightbox-close-btn" aria-label="Close lightbox">\u2715</button>
5            <div class="od-access-lightbox__content">
6              <h2 class="od-access-lightbox__title" id="ODAccessUnlockFallbackHeading">Unlock All 12 Recordings</h2>
7              <span class="od-access-lightbox__rule" aria-hidden="true"></span>
8              <div class="od-access-lightbox__body">
9                <p>Enable email updates to unlock full access to all 12 free recordings and hear about new releases, exclusive streaming titles, and special sales.</p>
10                <p>Use the unlock section on the page if the form does not appear here.</p>
11              </div>
12              <div class="od-access-lightbox__actions">
13                <a class="button button--filled-primary" href="${getUnlockFlowUrl()}">Go To Unlock Form</a>
14              </div>
15            </div>
16          </div>
17        `;if(content.removeAttribute("id"),content.removeAttribute("data-free-streaming-unlock-flow"),content.setAttribute("data-free-streaming-unlock-scope",""),content.classList.remove("content-wrapper","mx-auto","mb-8"),content.classList.add("od-free-streaming-unlock-lightbox-body"),form){const successState=document.createElement("div");successState.className="hidden od-access-lightbox__message od-access-lightbox__message--success",successState.setAttribute("data-unlock-success-state",""),successState.setAttribute("role","status"),successState.setAttribute("aria-live","polite"),successState.innerHTML="<p data-unlock-success-message>Thanks - your free-streaming access has been unlocked.</p><p>Refreshing your access now.</p>",form.parentNode.insertBefore(successState,form)}return`
18        <div class="lightbox-content od-access-lightbox od-access-lightbox--unlock" role="dialog" aria-modal="true" aria-labelledby="ODAccessUnlockHeading">
19          <button class="lightbox-close-btn" aria-label="Close lightbox">\u2715</button>
20          <div class="od-access-lightbox__content">
21            ${content.outerHTML}
22          </div>
23        </div>
24      `}const unlockFlow=document.getElementById("free-streaming-unlock-flow");if(unlockFlow){const unlockFormSelector="[data-free-streaming-unlock-form]",content=unlockFlow.cloneNode(!0),form=content.querySelector(unlockFormSelector);if(content.removeAttribute("id"),content.removeAttribute("hidden"),content.style.display="",content.removeAttribute("data-free-streaming-unlock-flow"),content.setAttribute("data-free-streaming-unlock-scope",""),content.classList.remove("content-wrapper","mx-auto","mb-8"),content.classList.add("od-free-streaming-unlock-lightbox-body"),form){const successState=document.createElement("div");successState.className="hidden od-access-lightbox__message od-access-lightbox__message--success",successState.setAttribute("data-unlock-success-state",""),successState.setAttribute("role","status"),successState.setAttribute("aria-live","polite"),successState.innerHTML="<p data-unlock-success-message>Thanks - your free-streaming access has been unlocked.</p><p>Refreshing your access now.</p>",form.parentNode.insertBefore(successState,form)}return`
25        <div class="lightbox-content od-access-lightbox od-access-lightbox--unlock" role="dialog" aria-modal="true" aria-labelledby="ODAccessUnlockHeading">
26          <button class="lightbox-close-btn" aria-label="Close lightbox">\u2715</button>
27          <div class="od-access-lightbox__content">
28            ${content.outerHTML}
29          </div>
30        </div>
31      `}return`
32      <div class="lightbox-content od-access-lightbox" role="dialog" aria-modal="true" aria-labelledby="ODAccessUnlockFallbackHeading">
33        <button class="lightbox-close-btn" aria-label="Close lightbox">\u2715</button>
34        <div class="od-access-lightbox__content">
35          <h2 class="od-access-lightbox__title" id="ODAccessUnlockFallbackHeading">Unlock All 12 Recordings</h2>
36          <span class="od-access-lightbox__rule" aria-hidden="true"></span>
37          <div class="od-access-lightbox__body">
38            <p>Enable email updates to unlock full access to all 12 free recordings and hear about new releases, exclusive streaming titles, and special sales.</p>
39            <p>Use the unlock section on the page if the form does not appear here.</p>
40          </div>
41          <div class="od-access-lightbox__actions">
42            <a class="button button--filled-primary" href="${getUnlockFlowUrl()}">Go To Unlock Form</a>
43          </div>
44        </div>
45      </div>
46    `}function openAccessLightbox(lockState){const{overlay,inner}=getLightboxElements();if(!overlay||!inner)return;const html=(lockState==="logged_in_not_opted_in"?"logged_in_not_opted_in":"logged_out")==="logged_out"?`
47      <div class="lightbox-content od-access-lightbox od-access-lightbox--login" role="dialog" aria-modal="true" aria-labelledby="ODAccessLoginHeading">
48        <button class="lightbox-close-btn" aria-label="Close lightbox">\u2715</button>
49        <div class="od-access-lightbox__content">
50          <h2 class="od-access-lightbox__title" id="ODAccessLoginHeading">Sign In to Keep Listening</h2>
51          <span class="od-access-lightbox__rule" aria-hidden="true"></span>
52          <div class="od-access-lightbox__body"><p>Sign in to your Opera Depot account to unlock all 12 free recordings.</p></div>
53          <div class="od-access-lightbox__actions"><a class="button button--filled-primary" href="/account/login">Sign In</a><a class="button button--outline-secondary" href="/account/register">Create Account</a></div>
54        </div>
55      </div>
56    `:getUnlockLightboxMarkup();showLightbox(html)}function rerenderFreeStreamingSections(){document.querySelectorAll("[data-free-streaming-section][data-section-id]").forEach(sectionEl=>{const sectionId=sectionEl.getAttribute("data-section-id");if(!sectionId||sectionEl.dataset.membershipRefreshing==="true")return;sectionEl.dataset.membershipRefreshing="true";const url=new URL(window.location.href);url.searchParams.set("section_id",sectionId),fetch(url.toString(),{credentials:"same-origin",headers:{"X-Requested-With":"XMLHttpRequest"}}).then(response=>{if(!response.ok)throw new Error("Unable to refresh section");return response.text()}).then(html=>{const template=document.createElement("template");template.innerHTML=html.trim();const replacement=template.content.querySelector("[data-free-streaming-section]")||template.content.firstElementChild;if(!replacement)throw new Error("Missing refreshed free streaming markup");sectionEl.replaceWith(replacement),window.Alpine&&typeof window.Alpine.initTree=="function"&&window.Alpine.initTree(replacement),window.ODStreamingVisualCardInit&&window.ODStreamingVisualCardInit(replacement)}).catch(error=>{console.warn("Free streaming section refresh failed:",error)}).finally(()=>{delete sectionEl.dataset.membershipRefreshing})})}async function refreshAccessState(options){const endpoint=getEndpoint();if(!endpoint)return getAccessState();const customerId=getCustomerId();if(!customerId)return getAccessState();const refreshUrl=new URL(endpoint,window.location.origin);refreshUrl.searchParams.set("customerId",customerId),console.log("[MembershipAccess] refreshing access",{url:refreshUrl.toString(),customerId});const response=await fetch(refreshUrl.toString(),{method:"GET",mode:"cors",credentials:"omit",headers:{Accept:"application/json"}});if(!response.ok)throw new Error("Membership refresh failed");const data=await response.json();console.log("[MembershipAccess] refresh response",{ok:response.ok,status:response.status,body:data});const nextState=setAccessState(data);return(!options||options.rerender!==!1)&&rerenderFreeStreamingSections(),nextState}let globalAccessPolicyRefreshPromise=null;async function refreshGlobalAccessPolicy(){return globalAccessPolicyRefreshPromise||(globalAccessPolicyRefreshPromise=(async()=>{const endpoint=getGlobalAccessPolicyEndpoint();if(!endpoint)return getAccessState();const endpoints=uniqueStrings([endpoint,getLegacyStreamingPolicyEndpoint(endpoint)]);let lastError=null;for(const candidateEndpoint of endpoints)try{const data=await fetchJsonEndpoint(candidateEndpoint),nextState=setAccessState(normalizeGlobalAccessPol
56icyState(data));return console.log("[GlobalAccessPolicy] refresh response",{endpoint:resolveEndpointUrl(candidateEndpoint),globalCatalogueOverride:nextState.globalCatalogueOverride,source:nextState.globalAccessPolicySource,fallbackReason:nextState.globalAccessPolicyFallbackReason}),nextState}catch(error){lastError=error}return console.warn("Global access policy refresh failed:",lastError),getAccessState()})().finally(()=>{globalAccessPolicyRefreshPromise=null}),globalAccessPolicyRefreshPromise)}let refreshTimer=null,globalAccessPolicyRefreshTimer=null;function queueRefresh(){getEndpoint()&&(window.clearTimeout(refreshTimer),refreshTimer=window.setTimeout(()=>{refreshAccessState().catch(error=>{console.warn("Membership refresh failed:",error)})},80))}function queueGlobalAccessPolicyRefresh(){getGlobalAccessPolicyEndpoint()&&(window.clearTimeout(globalAccessPolicyRefreshTimer),globalAccessPolicyRefreshTimer=window.setTimeout(()=>{refreshGlobalAccessPolicy().catch(error=>{console.warn("Global access policy refresh failed:",error)})},80))}document.addEventListener("click",event=>{if(handleLockedFreeStreamingPlayTriggerEvent(event))return;const lockedCard=event.target.closest("[data-free-streaming-locked-trigger]");lockedCard&&(event.preventDefault(),openAccessLightbox(lockedCard.getAttribute("data-lock-state")))},!0),document.addEventListener("keydown",event=>{if((event.key==="Enter"||event.key===" ")&&handleLockedFreeStreamingPlayTriggerEvent(event))return;const lockedCard=event.target.closest("[data-free-streaming-locked-trigger]");lockedCard&&(event.key!=="Enter"&&event.key!==" "||(event.preventDefault(),openAccessLightbox(lockedCard.getAttribute("data-lock-state"))))},!0),document.addEventListener("DOMContentLoaded",queueRefresh),document.addEventListener("DOMContentLoaded",queueGlobalAccessPolicyRefresh),document.addEventListener("shopify:page:load",queueRefresh),document.addEventListener("shopify:page:load",queueGlobalAccessPolicyRefresh),document.addEventListener("od:after-swap",queueRefresh),document.addEventListener("od:after-swap",queueGlobalAccessPolicyRefresh),document.addEventListener("od:main-content-replaced",queueRefresh),document.addEventListener("od:main-content-replaced",queueGlobalAccessPolicyRefresh),document.addEventListener("od:main-content-replaced",()=>{const accessRoot2=ensureAccessRoot(),normalized=getAccessState();accessRoot2.state=normalized,setCustomerAccessAttributes(normalized)}),document.addEventListener("visibilitychange",()=>{document.hidden||(queueRefresh(),queueGlobalAccessPolicyRefresh())});const accessRoot=ensureAccessRoot();accessRoot.getState=getAccessState,accessRoot.setState=setAccessState,accessRoot.refresh=refreshAccessState,accessRoot.refreshGlobalAccessPolicy=refreshGlobalAccessPolicy,window.ODRefreshMembershipAccess=refreshAccessState,window.ODRefreshGlobalAccessPolicy=refreshGlobalAccessPolicy;const initialState=getAccessState();accessRoot.state=initialState,setCustomerAccessAttributes(initialState)})(),(()=>{const MODULE_ID="free-streaming-unlock-flow";if(window[MODULE_ID])return;window[MODULE_ID]=!0;const FORM_SELECTOR="[data-free-streaming-unlock-form]",SUBMIT_SELECTOR="[data-unlock-submit]";console.log("unlock delegated handler active");function getMarketingOptInEndpoint(){const config=window.ODMembershipAccess&&window.ODMembershipAccess.config||{};return String(config.marketingOptInEndpoint||"").trim()}function getFormMarketingOptInEndpoint(form){if(!form)return getMarketingOptInEndpoint();const formEndpoint=form.getAttribute("data-marketing-opt-in-endpoint");return String(formEndpoint||getMarketingOptInEndpoint()).trim()}function setUnlockStatus(form,state,message){const status=form.querySelector("[data-unlock-status]");status&&(status.classList.remove("hidden","border-green-300","bg-green-50","text-green-900","border-yellow-300","bg-yellow-50","text-yellow-900","border-red-300","bg-red-50","text-red-900"),state==="success"?status.classList.add("border-green-300","bg-green-50","text-green-900"):state==="pending"?status.classList.add("border-yellow-300","bg-yellow-50","text-yellow-900"):status.classList.add("border-red-300","bg-red-50","text-red-900"),status.textContent=message)}function getUnlockElementInfo(element){return element?{tagName:element.tagName,type:element.getAttribute("type"),text:(element.textContent||"").trim(),formBound:!!element.closest(FORM_SELECTOR),unlockButtonBound:element.dataset.unlockButtonBound==="true"}:null}function closeUnlockLightbox(immediate){const overlay=document.getElementById("lightbox-overlay"),inner=document.getElementById("lightbox-inner-content");
56if(!(!overlay||!inner)){if(overlay.classList.remove("show"),document.body.style.overflow="",immediate){overlay.style.display="none",inner.innerHTML="";return}window.setTimeout(()=>{overlay.style.display="none",inner.innerHTML=""},350)}}async function refreshFreeStreamingCollectionPage(options){const currentPage=document.querySelector("[data-free-streaming-collection-page]");if(!currentPage)return;const response=await fetch(window.location.href,{credentials:"same-origin",headers:{"X-Requested-With":"XMLHttpRequest"}});if(!response.ok)throw new Error("Unable to refresh free streaming collection");const html=await response.text(),template=document.createElement("template");template.innerHTML=html.trim();const replacement=template.content.querySelector("[data-free-streaming-collection-page]");if(!replacement)throw new Error("Missing refreshed free streaming collection markup");currentPage.replaceWith(replacement),window.Alpine&&typeof window.Alpine.initTree=="function"&&window.Alpine.initTree(replacement),window.ODStreamingVisualCardInit&&window.ODStreamingVisualCardInit(replacement);const shouldScrollToUnlockFlow=!options||options.scrollToUnlockFlow!==!1,unlockFlow=replacement.querySelector("#free-streaming-unlock-flow");unlockFlow&&shouldScrollToUnlockFlow&&unlockFlow.scrollIntoView({behavior:"smooth",block:"start"})}function isFreeStreamingUnlockForm(form){return!!(form&&form.matches(FORM_SELECTOR)&&form.closest("[data-free-streaming-unlock-scope]"))}function showUnlockSuccessState(form,message){if(!form)return;const successState=form.parentElement?form.parentElement.querySelector("[data-unlock-success-state]"):null,successMessage=successState?successState.querySelector("[data-unlock-success-message]"):null;successMessage&&(successMessage.textContent=message||"Thanks - your free-streaming access has been unlocked."),successState&&(successState.classList.remove("hidden"),form.classList.add("hidden")),setUnlockStatus(form,"success",message||"Thanks - your free-streaming access has been unlocked.")}async function handleUnlockSubmit(form){try{if(!form||form.dataset.unlockSubmitting==="true")return;form.dataset.unlockSubmitting="true";const endpoint=getFormMarketingOptInEndpoint(form),customerId=window?.ODMembershipAccess?.state?.customerId||window?.Shopify?.customer?.id||null,consentField=form.querySelector('input[name="marketing_consent"]'),submitButton=form.querySelector(SUBMIT_SELECTOR),hasConsent=!!(consentField&&consentField.checked);if(console.log("unlock button clicked (safe)"),console.log("customerId resolved:",customerId),!hasConsent){setUnlockStatus(form,"error","Please confirm your email consent to continue.");return}if(!endpoint){console.error("[FreeStreamingUnlock] marketing endpoint missing"),setUnlockStatus(form,"error","The marketing opt-in endpoint is not configured in the test theme.");return}if(!customerId){console.error("[FreeStreamingUnlock] customerId missing"),setUnlockStatus(form,"error","Missing customerId");return}submitButton&&(submitButton.disabled=!0,submitButton.setAttribute("aria-busy","true")),console.log("marketing POST starting");const response=await fetch(endpoint,{method:"POST",mode:"cors",credentials:"omit",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({customerId})}),data=await response.json().catch(()=>({}));if(console.log("marketing POST response",{ok:response.ok,status:response.status,body:data}),!response.ok)throw console.log("membership refresh skipped: no subscribed status"),new Error(data.message||"Unable to update your email preferences right now.");if(data.status==="subscribed"){const successMessage=data.message||"Thanks - your free-streaming access has been unlocked.",isInLightbox=!!form.closest(".od-access-lightbox");showUnlockSuccessState(form,successMessage),data.access&&window.ODMembershipAccess&&typeof window.ODMembershipAccess.setState=="function"&&window.ODMembershipAccess.setState(data.access),typeof window.ODRefreshMembershipAccess=="function"&&(console.log("membership refresh starting"),await window.ODRefreshMembershipAccess({rerender:!0})),await refreshFreeStreamingCollectionPage({scrollToUnlockFlow:!isInLightbox}),isInLightbox&&window.setTimeout(()=>{closeUnlockLightbox(!1)},1200);return}if(console.log("membership refresh skipped: no subscribed status"),data.status==="pending"){setUnlockStatus(form,"pending",data.message||"Please check your email to confirm your subscription and unlock titles 6\u201312.");return}setUnlockStatus(form,"error",data.message||"We could not process your request. Please try again.")}catch(error){console.error("unlock fatal error",error),console.error("[FreeStreamingUnlock] marketing opt-in failed",error),setUnlockStatus(form,"error","Unlock failed (JS error)")}finally{delete form.dataset.unlockSubmitting;const submitButton=form?form.querySelector(SUBMIT_SELECTOR):null;submitButton&&(submitButton.disabled=!1,submitButton.removeAttribute("aria-busy"))}}document.addEventListener("click",event=>{if(!event.target||typeof event.target.closest!="function")return;const button=event.target.closest(SUBMIT_SELECTOR);if(!button)return;const form=button.closest(FORM_SELECTOR);if(!isFreeStreamingUnlockForm(form)){console.warn("[FreeStreamingUnlock] submit button clicked without unlock form",getUnlockElementInfo(button));return}console.log("unlock button clicked"),event.preventDefault(),event.stopPropagation(),typeof event.stopImmediatePropagation=="function"&&event.stopImmediatePropagation(),handleUnlockSubmit(form)},!0),document.addEventListener("click",event=>{const trigger=event.target.closest('a[href$="#free-streaming-unlock-flow"]');if(!trigger)return;const targetUrl=trigger.getAttribute("href")||"",target=new URL(targetUrl,window.location.origin);if(target.pathname===window.location.pathname&&target.hash==="#free-streaming-unlock-flow"){const unlockFlow=document.getElementById("free-streaming-unlock-flow");unlockFlow&&(event.preventDefault(),closeUnlockLightbox(!0),window.history.replaceState({},"",target.pathname+target.hash),unlockFlow.scrollIntoView({behavior:"smooth",block:"start"}))}})}
56)(),(function(){window.__operaPlayerLaunchBound||(window.__operaPlayerLaunchBound=!0,window.__operaPlayerLaunchOwnedByProductionBundle=!0,console.info("[Opera Player] app.js .opera-player-launch handler disabled; opera-depot-player.js owns Stream Recording clicks"))})(),(function(){const LETTERS="ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),state={products:null,fetchedAt:0,searchValue:"",newOnly:!1};window.__ComingSoon=state;function csFold(str){return str?str.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().trim():""}function csLetterFor(foldedTitle){const first=foldedTitle.charAt(0);return first>="a"&&first<="z"?first.toUpperCase():"#"}function csIsNew(publishedAt,nowMs){if(!publishedAt)return!1;const publishedMs=Date.parse(publishedAt);if(!Number.isFinite(publishedMs))return!1;const ageDays=(nowMs-publishedMs)/864e5;return ageDays>=0&&ageDays<=14}function csBuildRow(product){const parts=product.title.split(" - "),row=document.createElement("div");row.className="streaming-item",row.dataset.title=product.title.toLowerCase(),row.dataset.handle=product.handle,row.dataset.new=product.isNew?"true":"false";const playBtn=document.createElement("button");playBtn.type="button",playBtn.className="opera-player-launch listing-stream-button",playBtn.setAttribute("aria-label","Play"),playBtn.dataset.productHandle=product.handle,playBtn.innerHTML='<svg viewBox="0 0 48 48" width="40" height="40" xmlns="http://www.w3.org/2000/svg"><circle cx="24" cy="24" r="20" stroke="#330065" stroke-width="2" fill="white" /><polygon points="18,16 30,24 18,32" fill="#330065" /></svg>';const text=document.createElement("div");text.className="streaming-text";const titleWrap=document.createElement("div");titleWrap.className="scroll-container";const titleInner=document.createElement("div");titleInner.className="scroll-inner";const heading=document.createElement("h2"),strong=document.createElement("strong");if(strong.textContent=parts[0]||product.title,heading.appendChild(strong),product.isNew){const badge=document.createElement("span");badge.className="badge--new",badge.setAttribute("aria-label","New product"),badge.textContent="NEW",heading.appendChild(document.createTextNode(" ")),heading.appendChild(badge)}titleInner.appendChild(heading),titleWrap.appendChild(titleInner),text.appendChild(titleWrap);const subWrap=document.createElement("div");subWrap.className="scroll-container";const subInner=document.createElement("div");subInner.className="scroll-inner";const subtext=document.createElement("p");subtext.className="streaming-subtext",subtext.textContent=parts.slice(1).join(" - "),subInner.appendChild(subtext),subWrap.appendChild(subInner),text.appendChild(subWrap);const infoWrap=document.createElement("div");infoWrap.className="info-button-wrapper";const infoBtn=document.createElement("button");return infoBtn.className="info-button",infoBtn.setAttribute("aria-label","Info"),infoBtn.dataset.handle=product.handle,infoBtn.dataset.lightboxView="coming-soon-lightbox",infoBtn.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1zm0 12.93A5.93 5.93 0 1 1 8 2.07a5.93 5.93 0 0 1 0 11.86zM8.93 6.588l-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465-.598l.088-.416c-.2.176-.492.246-.686.246-.275 0-.375-.193-.304-.533zM9 4.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/></svg>',infoWrap.appendChild(infoBtn),row.appendChild(playBtn),row.appendChild(text),row.appendChild(infoWrap),row}function csGetEls(){return{container:document.getElementById("coming-soon-grid"),searchInput:document.getElementById("keyword-search"),clearBtn:document.getElementById("clear-search"),wrapper:document.getElementById("search-bar-wrapper"),newChip:document.getElementById("cs-new-filter"),rail:document.getElementById("cs-letter-rail"),countEl:document.getElementById("cs-result-count"),statusEl:document.getElementById("cs-status"),statusMessage:document.getElementById("cs-status-message"),retryBtn:document.getElementById("cs-retry")}}function csIsNewOnlyPage(els){return!!els.container&&els.container.dataset.csMode==="new"}function csRenderNewOnlyList(els){const newest=state.products.filter(product=>product.isNew).sort((a,b)=>(Date.parse(b.publishedAt)||0)-(Date.parse(a.publishedAt)||0)),fragment=document.createDocumentFragment();newest.forEach(product=>{product.row=csBuildRow(product),fragment.appendChild(product.row)}),els.container.innerHTML="",els.container.appendChild(fragment),newest.length===0?csShowStatus(els,"No new titles in the last 14 days.",!1):csHideStatus(els)}function csShowStatus(els,message,showRetry){els.statusEl&&(els.statusEl.hidden=!1,els.statusMessage&&(els.statusMessage.textContent=message),els.retryBtn&&(els.retryBtn.hidden=!showRetry))}function csHideStatus(els){els.statusEl&&(els.statusEl.hidden=!0)}async function csFetchIndex(indexUrl){const response=await fetch(indexUrl,{headers:{Accept:"application/json"}});if(!response.ok)throw new Error("index request failed: "+response.status);const data=await response.json();if(!data||data.ok!==!0||!Array.isArray(data.products))throw new Error("index response malformed");return data.products}function csPrepareProducts(rawProducts){const nowMs=Date.now(),products=rawProducts.map(raw=>{const title=String(raw.title||""),folded=csFold(title);return{title,handle:String(raw.handle||""),sku:raw.sku||null,publishedAt:raw.publishedAt||null,haystack:folded+" "+csFold(String(raw.sku||"")),letter:csLetterFor(folded),isNew:csIsNew(raw.publishedAt,nowMs),row:null,visible:!0}}),letterProducts=products.filter(p=>p.letter!=="#"),hashProducts=products.filter(p=>p.letter==="#");return letterProducts.concat(hashProducts)}function csRenderList(els){const fragment=document.createDocumentFragment(),headings={};let currentLetter=null;
56return state.products.forEach(product=>{if(product.letter!==currentLetter){currentLetter=product.letter;const headingEl=document.createElement("h3");headingEl.className="cs-letter-heading",headingEl.id="cs-letter-"+(currentLetter==="#"?"other":currentLetter),headingEl.textContent=currentLetter,headings[currentLetter]=headingEl,fragment.appendChild(headingEl)}product.row=csBuildRow(product),fragment.appendChild(product.row)}),els.container.innerHTML="",els.container.appendChild(fragment),headings}function csRenderRail(els,headings){if(!els.rail)return{};els.rail.innerHTML="";const railButtons={};return LETTERS.concat("#").forEach(letter=>{const button=document.createElement("button");button.type="button",button.textContent=letter,button.disabled=!headings[letter],button.setAttribute("aria-label",letter==="#"?"Jump to titles starting with a number or symbol":"Jump to "+letter),button.addEventListener("click",()=>{const heading=headings[letter];if(!heading||heading.hidden)return;const offset=csStickyOffset(els),top=heading.getBoundingClientRect().top+window.scrollY-offset-8;window.scrollTo({top,behavior:"auto"})}),railButtons[letter]=button,els.rail.appendChild(button)}),els.rail&&els.rail.parentElement!==document.body&&(els.rail.dataset.csPortaled="1",document.body.appendChild(els.rail)),railButtons}function csMobileHeaderOffset(){const raw=getComputedStyle(document.documentElement).getPropertyValue("--od-mobile-offset"),parsed=parseFloat(raw);return Number.isFinite(parsed)?parsed:56}function csStickyOffset(els){return!els.wrapper||window.innerWidth<768?csMobileHeaderOffset():(parseFloat(getComputedStyle(els.wrapper).top)||0)+els.wrapper.offsetHeight}function csEnsureBackToTop(){let btn=document.querySelector(".cs-back-to-top");return btn||(btn=document.createElement("button"),btn.type="button",btn.className="cs-back-to-top",btn.setAttribute("aria-label","Back to top"),btn.innerHTML='<svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true"><path d="M12 5l-7 7 1.4 1.4L11 8.8V19h2V8.8l4.6 4.6L19 12z" fill="currentColor"/></svg>',btn.addEventListener("click",()=>{window.scrollTo({top:0,behavior:"auto"})}),document.body.appendChild(btn)),btn}function csRemovePortaledUI(){document.querySelectorAll('.cs-letter-rail[data-cs-portaled="1"], .cs-back-to-top').forEach(el=>el.remove())}function csApplyFilters(els,headings,railButtons){const tokens=csFold(state.searchValue).split(/\s+/).filter(Boolean),filtering=tokens.length>0||state.newOnly,visibleByLetter={};let visibleCount=0;state.products.forEach(product=>{const matchesSearch=tokens.every(token=>product.haystack.includes(token)),matchesNew=!state.newOnly||product.isNew,visible=matchesSearch&&matchesNew;product.visible=visible,product.row&&(product.row.hidden=!visible),visible&&(visibleCount+=1,visibleByLetter[product.letter]=(visibleByLetter[product.letter]||0)+1)}),Object.keys(headings).forEach(letter=>{headings[letter].hidden=!visibleByLetter[letter]}),Object.keys(railButtons).forEach(letter=>{railButtons[letter].disabled=!visibleByLetter[letter]}),els.countEl&&(filtering?(els.countEl.hidden=!1,els.countEl.textContent=visibleCount+" of "+state.products.length+" titles"):els.countEl.hidden=!0),filtering&&visibleCount===0?csShowStatus(els,"No matching titles found.",!1):csHideStatus(els)}async function csLoadAndRender(els){const indexUrl=els.container.dataset.indexUrl||"/apps/library/coming-soon-index";if(!state.products||Date.now()-state.fetchedAt>3e5){csShowStatus(els,"Loading titles\u2026",!1);let rawProducts;try{rawProducts=await csFetchIndex(indexUrl)}catch(error){console.warn("[ComingSoon] index fetch failed:",error),csShowStatus(els,"Couldn't load the collection.",!0);return}state.products=csPrepareProducts(rawProducts),state.fetchedAt=Date.now()}if(csHideStatus(els),csIsNewOnlyPage(els)){csRenderNewOnlyList(els);return}const headings=csRenderList(els),railButtons=csRenderRail(els,headings);csApplyFilters(els,headings,railButtons),state.applyFilters=()=>csApplyFilters(els,headings,railButtons)}function initComingSoonPage(){const els=csGetEls(),container=els.container;if(!container||container.dataset.comingSoonBound==="1")return!!container;if(csIsNewOnlyPage(els))return container.dataset.comingSoonBound="1",csRemovePortaledUI(),els.retryBtn&&els.retryBtn.addEventListener("click",()=>
56{csLoadAndRender(els)}),csLoadAndRender(els),!0;if(!els.searchInput||!els.wrapper)return!1;console.log("\u{1F504} initComingSoonPage (index mode)"),container.dataset.comingSoonBound="1",document.querySelectorAll('.cs-letter-rail[data-cs-portaled="1"]').forEach(el=>{el!==els.rail&&el.remove()}),state.searchValue="",state.newOnly=!1;const updateStickyShadow=()=>{if(window.innerWidth<768){els.wrapper.classList.remove("is-stuck");return}const topOffset=parseFloat(getComputedStyle(els.wrapper).top)||0,stuck=els.wrapper.getBoundingClientRect().top<=topOffset+1;els.wrapper.classList.toggle("is-stuck",stuck)};window.__comingSoonStickyShadowHandler&&(window.removeEventListener("scroll",window.__comingSoonStickyShadowHandler),window.removeEventListener("resize",window.__comingSoonStickyShadowHandler)),window.__comingSoonStickyShadowHandler=updateStickyShadow,window.addEventListener("scroll",updateStickyShadow,{passive:!0}),window.addEventListener("resize",updateStickyShadow,{passive:!0}),updateStickyShadow();const backToTop=csEnsureBackToTop(),updateBackToTop=()=>{if(!document.body.contains(backToTop))return;const show=window.scrollY>800;show&&(backToTop.style.top=csStickyOffset(els)+10+"px"),backToTop.classList.toggle("cs-back-to-top--visible",show)};window.__comingSoonBackToTopHandler&&window.removeEventListener("scroll",window.__comingSoonBackToTopHandler),window.__comingSoonBackToTopHandler=updateBackToTop,window.addEventListener("scroll",updateBackToTop,{passive:!0}),updateBackToTop();let searchTimer=null;return els.searchInput.addEventListener("input",()=>{const wasEmpty=!state.searchValue.trim();state.searchValue=els.searchInput.value,wasEmpty&&state.searchValue.trim()&&state.newOnly&&(state.newOnly=!1,els.newChip&&els.newChip.setAttribute("aria-pressed","false")),els.clearBtn&&(els.clearBtn.style.display=state.searchValue.trim()?"block":"none"),clearTimeout(searchTimer),searchTimer=setTimeout(()=>{state.applyFilters&&state.applyFilters()},120)}),els.searchInput.addEventListener("keydown",event=>{event.key==="Enter"&&event.preventDefault()}),els.clearBtn&&els.clearBtn.addEventListener("click",()=>{els.searchInput.value="",state.searchValue="",els.clearBtn.style.display="none",state.applyFilters&&state.applyFilters(),els.searchInput.focus()}),els.newChip&&els.newChip.addEventListener("click",()=>{state.newOnly=!state.newOnly,els.newChip.setAttribute("aria-pressed",state.newOnly?"true":"false"),state.applyFilters&&state.applyFilters()}),els.retryBtn&&els.retryBtn.addEventListener("click",()=>{csLoadAndRender(els)}
56),csLoadAndRender(els),!0}const COMING_SOON_RETRY_EVERY_MS=150,COMING_SOON_RETRY_MAX_TRIES=20;function initComingSoonWithRetries(){let tries=0;const tick=()=>{tries+=1,document.getElementById("coming-soon-grid")||csRemovePortaledUI(),!initComingSoonPage()&&tries<COMING_SOON_RETRY_MAX_TRIES&&setTimeout(tick,COMING_SOON_RETRY_EVERY_MS)};tick()}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",initComingSoonWithRetries,{once:!0}):initComingSoonWithRetries(),["turbo:load","turbolinks:load","barba:after","swup:contentReplaced","pjax:complete","shopify:section:load","shopify:page:load","od:after-swap"].forEach(eventName=>document.addEventListener(eventName,()=>setTimeout(initComingSoonWithRetries,0))),window.addEventListener("popstate",initComingSoonWithRetries),new MutationObserver(()=>{const grid=document.getElementById("coming-soon-grid");grid&&!grid.dataset.comingSoonBound&&initComingSoonWithRetries()}).observe(document.documentElement,{childList:!0,subtree:!0})})(),(function(){const MODULE_KEY="__DefaultCollectionComingSoonDeferral_v1";if(window[MODULE_KEY])return;window[MODULE_KEY]=!0;const STORAGE_KEY="__default_collection_coming_soon_mode";let activeRoot=null,activeURL="",recheckTimer=null,initRetryTimer=null,urlObserver=null,lastObservedURL=`${location.pathname}${location.search}`;function getDefaultCollectionRoots(){return Array.from(document.querySelectorAll('#ProductGridContainer[data-default-collection-coming-soon-defer="true"]'))}function logDefaultComingSoon(message,details){details!==void 0?console.log(`[DefaultComingSoon] ${message}`,details):console.log(`[DefaultComingSoon] ${message}`)}function getCurrentDefaultCollectionRoot(){return getDefaultCollectionRoots()[0]||null}function getDefaultCollectionGrid(root){return root?root.querySelector("[data-content-wrapper]"):null}function getDefaultCollectionCurrentPage(root){return parseInt(root?.dataset.currentPage||"1",10)}function getDefaultCollectionTotalPages(root){return parseInt(root?.dataset.totalPages||"1",10)}function readDefaultComingSoonMode(){try{return window.localStorage.getItem(STORAGE_KEY)==="inline"?"inline":"defer"}catch{return"defer"}}function writeDefaultComingSoonMode(mode){try{window.localStorage.setItem(STORAGE_KEY,mode)}catch{}}function getDefaultComingSoonState(root){return root.__defaultComingSoonState||(root.__defaultComingSoonState={cardsByHandle:new Map,finalized:!1,mode:readDefaultComingSoonMode()}),root.__defaultComingSoonState}function resetDefaultComingSoonState(root){return root?(root.__defaultComingSoonState={cardsByHandle:new Map,finalized:!1,mode:readDefaultComingSoonMode()},root.__defaultComingSoonState):null}function getDefaultComingSoonSection(root){const ownerId=root?.getAttribute("data-default-coming-soon-owner");return ownerId?document.querySelector(`[data-default-coming-soon-section][data-default-coming-soon-owner="${CSS.escape(ownerId)}"]`):null}function getDefaultComingSoonGrid(root){return getDefaultComingSoonSection(root)?.querySelector("[data-default-coming-soon-grid]")||null}function getDefaultComingSoonToggleInputs(root){return Array.from(root.querySelectorAll("[data-default-coming-soon-mode-input]"))}function getDefaultComingSoonSwitcher(root){return root?.querySelector("[data-default-coming-soon-switcher]")||null}function dispatchDefaultComingSoonState(root,reason){if(!root)return;const state=getDefaultComingSoonState(root),section=getDefaultComingSoonSection(root);document.dispatchEvent(new CustomEvent("od:default-coming-soon-state",{detail:{root,reason,ownerId:root.getAttribute("data-default-coming-soon-owner")||"",mode:state.mode,finalized:state.finalized,ready:state.mode==="inline"||state.finalized,hidden:section?section.classList.contains("hidden"):!0}}))}function syncDefaultComingSoonToggle(root){const state=getDefaultComingSoonState(root);getDefaultComingSoonToggleInputs(root).forEach(input=>{input.checked=input.value===state.mode})}function syncDefaultComingSoonSwitcherVisibility(root){const switcher=getDefaultComingSoonSwitcher(root);if(!switcher)return;const state=getDefaultComingSoonState(root);switcher.classList.toggle("hidden",state.cardsByHandle.size===0)}function ensureDeferredPlaceholder(wrapper){let placeholder=wrapper.__defaultComingSoonPlaceholder;return placeholder||(placeholder=document.createElement("span"),placeholder.hidden=!0,placeholder.setAttribute("data-coming-soon-placeholder",""),placeholder.setAttribute("data-product-handle",wrapper.getAttribute("data-product-handle")||""),wrapper.__defaultComingSoonPlaceholder=placeholder,placeholder)}function rememberDeferredCard(root,wrapper){const state=getDefaultComingSoonState(root),handle=wrapper.getAttribute("data-product-handle")||"";if(!handle)return;const placeholder=ensureDeferredPlaceholder(wrapper);!placeholder.parentNode&&wrapper.parentNode&&wrapper.parentNode.insertBefore(placeholder,wrapper.nextSibling),wrapper.setAttribute("data-coming-soon-deferred","true"),state.cardsByHandle.set(handle,{card:wrapper,placeholder,s
56ortKey:wrapper.getAttribute("data-sort-key")||""})}function hydrateDeferredCardsFromSeparatedSection(root){const state=getDefaultComingSoonState(root),section=getDefaultComingSoonSection(root),targetGrid=getDefaultComingSoonGrid(root);!section||!targetGrid||(targetGrid.querySelectorAll(':scope > [data-default-collection-card][data-coming-soon="true"]').forEach(wrapper=>{const handle=wrapper.getAttribute("data-product-handle")||"";if(!handle||state.cardsByHandle.has(handle))return;const placeholder=root.querySelector(`[data-coming-soon-placeholder][data-product-handle="${CSS.escape(handle)}"]`)||ensureDeferredPlaceholder(wrapper);wrapper.__defaultComingSoonPlaceholder=placeholder,wrapper.setAttribute("data-coming-soon-deferred","true"),state.cardsByHandle.set(handle,{card:wrapper,placeholder,sortKey:wrapper.getAttribute("data-sort-key")||""})}),state.cardsByHandle.size&&logDefaultComingSoon("hydrated deferred cards from separated section",{deferredCount:state.cardsByHandle.size}))}function hydrateVisibleComingSoonCards(root){const state=getDefaultComingSoonState(root),grid=getDefaultCollectionGrid(root);grid&&grid.querySelectorAll(':scope > [data-default-collection-card][data-coming-soon="true"]').forEach(wrapper=>{const handle=wrapper.getAttribute("data-product-handle")||"";!handle||state.cardsByHandle.has(handle)||state.cardsByHandle.set(handle,{card:wrapper,placeholder:wrapper.__defaultComingSoonPlaceholder||null,sortKey:wrapper.getAttribute("data-sort-key")||""})})}function pullDeferredCardsFromMainGrid(root){if(getDefaultComingSoonState(root).mode!=="defer")return;const grid=getDefaultCollectionGrid(root);grid&&grid.querySelectorAll(':scope > [data-default-collection-card][data-coming-soon="true"]:not([data-coming-soon-deferred="true"])').forEach(wrapper=>{rememberDeferredCard(root,wrapper),wrapper.remove()})}function ensureComingSoonCardsAlpineBound(cards){!window.Alpine||typeof window.Alpine.initTree!="function"||cards.forEach(entry=>{const card=entry&&entry.card;if(!(!card||!card.isConnected||!Array.from(card.querySelectorAll("a")).some(anchor=>anchor.getAttributeNames().some(name=>name.startsWith("x-element-transition-trigger"))&&!anchor._odElementTransitionCleanup)))try{window.Alpine.initTree(card),logDefaultComingSoon("rebound Alpine on coming-soon card",{handle:card.getAttribute("data-product-handle")||""})}catch(error){console.warn("[DefaultCollection] Alpine rebind failed:",error)}})}function finalizeDeferredCards(root){const state=getDefaultComingSoonState(root),section=getDefaultComingSoonSection(root),targetGrid=getDefaultComingSoonGrid(root);if(console.log("[OD coming-soon-sort] finalize",{url:`${location.pathname}${location.search}`,deferredCount:state.cardsByHandle.size,hasSection:!!section,hasTargetGrid:!!targetGrid}),logDefaultComingSoon("finalizeDeferredCards called",{deferredCount:state.cardsByHandle.size,hasSection:!!section,hasTargetGrid:!!targetGrid,appendTarget:targetGrid}),!section||!targetGrid)return;const cards=Array.from(state.cardsByHandle.values()).sort((a,b)=>a.sortKey.localeCompare(b.sortKey));if(targetGrid.innerHTML="",!cards.length){section.classList.add("hidden"),state.finalized=!0,syncDefaultComingSoonSwitcherVisibility(root),dispatchDefaultComingSoonState(root,"finalized-empty");return}const fragment=document.createDocumentFragment();cards.forEach(entry=>fragment.appendChild(entry.card)),targetGrid.appendChild(fragment),section.classList.remove("hidden"),setTimeout(()=>ensureComingSoonCardsAlpineBound(cards),0),state.finalized=!0,syncDefaultComingSoonSwitcherVisibility(root),dispatchDefaultComingSoonState(root,"finalized"),logDefaultComingSoon("finalizeDeferredCards appended cards",{deferredCount:cards.length,appendTarget:targetGrid})}function hideDeferredCardsSection(root){const section=getDefaultComingSoonSection(root),targetGrid=getDefaultComingSoonGrid(root);targetGrid&&(targetGrid.innerHTML=""),section&&section.classList.add("hidden")}function isDefaultCollectionFullyLoaded(root){if(!root)return!1;const hasReachedLastPage=getDefaultCollectionCurrentPage(root)>=getDefaultCollectionTotalPages(root),isLoading=root.dataset.loading==="1";return hasReachedLastPage&&!isLoading}function scheduleDefaultCollectionRecheck(root){root&&(recheckTimer&&clearTimeout(recheckTimer),recheckTimer=setTimeout(()=>
56{recheckTimer=null,processDefaultCollectionRoot(root)},0))}function restoreDeferredCardsInline(root){const state=getDefaultComingSoonState(root);if(Array.from(state.cardsByHandle.values()).forEach(entry=>{const{card,placeholder}=entry;placeholder?.parentNode&&(placeholder.parentNode.replaceChild(card,placeholder),card.removeAttribute("data-coming-soon-deferred"))}),state.finalized=!1,hideDeferredCardsSection(root),window.Alpine&&typeof window.Alpine.initTree=="function")try{window.Alpine.initTree(getDefaultCollectionGrid(root))}catch(error){console.warn("[DefaultCollection] Alpine init failed:",error)}syncDefaultComingSoonSwitcherVisibility(root),dispatchDefaultComingSoonState(root,"restored-inline")}function deferInlineComingSoonCards(root){const state=getDefaultComingSoonState(root);state.finalized=!1,pullDeferredCardsFromMainGrid(root),maybeFinalizeDeferredCards(root,"toggle-defer")}function maybeFinalizeDeferredCards(root,reason="unknown"){const state=getDefaultComingSoonState(root);if(logDefaultComingSoon("maybeFinalizeDeferredCards called",{reason,deferredCount:state.cardsByHandle.size,finalized:state.finalized,mode:state.mode,currentPage:root?getDefaultCollectionCurrentPage(root):null,totalPages:root?getDefaultCollectionTotalPages(root):null,loading:root?.dataset.loading}),!state.finalized&&state.mode==="defer"&&root){if(!isDefaultCollectionFullyLoaded(root)){getDefaultCollectionCurrentPage(root)>=getDefaultCollectionTotalPages(root)&&scheduleDefaultCollectionRecheck(root);return}finalizeDeferredCards(root)}}function setDefaultComingSoonMode(root,mode){const state=getDefaultComingSoonState(root);if(state.mode!==mode){if(state.mode=mode==="inline"?"inline":"defer",state.finalized=!1,writeDefaultComingSoonMode(state.mode),syncDefaultComingSoonToggle(root),state.mode==="inline"){restoreDeferredCardsInline(root);return}deferInlineComingSoonCards(root)}}function bindDefaultComingSoonToggle(root){!root||root.dataset.defaultComingSoonToggleBound==="1"||(root.dataset.defaultComingSoonToggleBound="1",getDefaultComingSoonToggleInputs(root).forEach(input=>{input.addEventListener("change",()=>{input.checked&&setDefaultComingSoonMode(root,input.value)})}))}function processDefaultCollectionRoot(root){if(!root||root.getAttribute("data-default-collection-coming-soon-defer")!=="true"||!root.isConnected)return;bindDefaultComingSoonToggle(root),syncDefaultComingSoonToggle(root);const state=getDefaultComingSoonState(root);if(console.log("[OD coming-soon-sort] process root",{url:`${location.pathname}${location.search}`,currentPage:getDefaultCollectionCurrentPage(root),totalPages:getDefaultCollectionTotalPages(root),mode:state.mode,finalized:state.finalized,loading:root.dataset.loading}),state.mode==="defer"){if(hydrateDeferredCardsFromSeparatedSection(root),pullDeferredCardsFromMainGrid(root),syncDefaultComingSoonSwitcherVisibility(root),logDefaultComingSoon("initial/process stash count",{deferredCount:state.cardsByHandle.size,currentPage:getDefaultCollectionCurrentPage(root),totalPages:getDefaultCollectionTotalPages(root),loading:root.dataset.loading}),getDefaultCollectionTotalPages(root)<=1&&root.dataset.loading!=="1"){finalizeDeferredCards(root);return}}else hydrateVisibleComingSoonCards(root),syncDefaultComingSoonSwitcherVisibility(root),hideDeferredCardsSection(root),dispatchDefaultComingSoonState(root,"hidden-inline");maybeFinalizeDeferredCards(root,"process-root")}function initDefaultCollectionComingSoonDefer(options={}){const root=getCurrentDefaultCollectionRoot(),currentURL=`${location.pathname}${location.search}`;if(!root){activeRoot=null,activeURL=currentURL,options.force&&(initRetryTimer&&clearTimeout(initRetryTimer),initRetryTimer=setTimeout(()=>{initRetryTimer=null,initDefaultCollectionComingSoonDefer()},100));return}initRetryTimer&&(clearTimeout(initRetryTimer),initRetryTimer=null),(root!==activeRoot||currentURL!==activeURL)&&(activeRoot&&activeRoot!==root&&logDefaultComingSoon("page instance changed; previous root replaced",{previousURL:activeURL,nextURL:currentURL}),activeRoot=root,activeURL=currentURL,resetDefaultComingSoonState(root),hideDeferredCardsSection(root)),processDefaultCollectionRoot(root)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>initDefaultCollectionComingSoonDefer({force:!0}),{once:!0}):initDefaultCollectionComingSoonDefer({force:!0}),["shopify:page:load","shopify:section:load","turbo:load","pjax:complete","swup:contentReplaced","od:after-swap","od:main-content-replaced"].forEach(eventName=>document.addEventListener(eventName,()=>initDefaultCollectionComingSoonDefer({force:!0}))),document.addEventListener("pagination:updated",()=>initDefaultCollectionComingSoonDefer()),document.addEventListener("od:collection:pagination-settled",event=>{const root=event.detail?.root;root&&root.getAttribute("data-default-collection-coming-soon-defer")==="true"&&processDefaultCollectionRoot(root)}),window.addEventListener("popstate",()=>initDefaultCollectionComingSoonDefer({force:!0})),document.addEventListener("od:collection:grid-updated",event=>{const root=event.detail?.root;root&&root.getAttribute("data-default-collection-coming-soon-defer")==="true"&&processDefaultCollectionRoot(root)}),"MutationObserver"in window&&(urlObserver=new MutationObserver(()=>{const nextURL=`${location.pathname}${location.search}`;nextURL!==lastObservedURL&&(lastObservedURL=nextURL,initDefaultCollectionComingSoonDefer({force:!0}))}),urlObserver.observe(document.body,{childList:!0,subtree:!0}))})(),(function(){const MODULE_ID="__odCollectionGrid";if(window[MODULE_ID])return;window[MODULE_ID]=!0;let rootObserver=null,sentinelObserver=null,activeRoot=null;const PENDING_RESTORE_KEY="__odCollectionGridPendingRestore",PENDING_RESTORE_MAX_AGE_MS=300*1e3;function normalizeCollectionUrl(input=window.location.href){return new URL(input,window.location.origin).pathname}function readPendingRestore(){try{return JSON.parse(sessionStorage.getItem(PENDING_RESTORE_KEY)||"null")}catch{return null}}function clearPendingRestore(){sessionStorage.removeItem(PENDING_RESTORE_KEY)}function finishDeferredRestore(options={}){options.clearPending&&clearPendingRestore(),window.__odCollectionRestore&&window.__odCollectionRestore.finishDeferredReveal()}function getPendingRestoreForUrl(url=getRootUrl()){const pendingRestore=readPendingRestore();if(!pendingRestore)return null;const normalizedUrl=normalizeCollectionUrl(url);return normalizeCollectionUrl(pendingRestore.url)!==normalizedUrl||typeof pendingRestore.timestamp!="number"||Date.now()-pendingRestore.timestamp>PENDING_RESTORE_MAX_AGE_MS?null:pendingRestore}function getRootUrl(root=getRoot()){const collectionUrl=root?.dataset.collectionUrl||window.location.pathname;return normalizeCollectionUrl(collectionUrl)}function getRoot(){return document.querySelector('#ProductGridContainer[data-auto-pagination="collection"]')}function getSeparatedComingSoonSection(root=getRoot()){const ownerId=root?.getAttribute("data-default-coming-soon-owner");return ownerId?document.querySelector(`[data-default-coming-soon-section][data-default-coming-soon-owner="${CSS.escape(ownerId)}"]`):null}function getGrid(root=getRoot()){return root?root.querySelector("[data-content-wrapper]"):null}function getSentinel(root=getRoot()){return root?root.querySelector("[data-collection-sentinel]"):null}function getLoader(root=getRoot()){return root?root.querySelector("[data-collection-loader]"):null}function getCurrentPage(root=getRoot()){return parseInt(root?.dataset.currentPage||"1",10)}function getTotalPages(root=getRoot()){return parseInt(root?.dataset.totalPages||"1",10)}function hasMorePages(root=getRoot()){return getCurrentPage(root)<getTotalPages(root)}function getNextPageUrl(root,page){const url=new URL(window.location.href);return url.pathname=root.dataset.collectionUrl||window.location.pathname,page>1?url.searchParams.set("page",String(page)):url.searchParams.delete("page"),`${url.pathname}${url.search}`}function getProductCards(root=getRoot()){if(!root)return[];const mainCards=Array.from(root.querySelectorAll("[data-product-card]")),separatedCards=Array.from(getSeparatedComingSoonSection(root)?.querySelectorAll("[data-product-card]")||[]);return mainCards.concat(separatedCards)}function getPrimaryProductLink(card){if(!card)return null;const directChildLink=Array.from(card.children||[]).find(child=>child instanceof HTMLAnchorElement&&child.hasAttribute("href"));return directChildLink||card.querySelector("a[href]")}function getCardOrigin(card,root=getRoot()){if(!card||!root)return"main-grid";const separatedSection=getSeparatedComingSoonSection(root);return separatedSection&&separatedSection.contains(card)?"coming-soon":"main-grid"}function getCanonicalProductUrl(card){if(!card)return"";const handle=card.dataset.productHandle||"",rawUrl=card.dataset.productUrl||getPrimaryProductLink(card)?.getAttribute("href")||"";if(rawUrl)try{const parsed=new URL(rawUrl,window.location.origin),variant=parsed.searchParams.get("variant");if(parsed.pathname.includes("/products/")){const canonicalPath=handle?`/products/${handle}`:parsed.pathname;return variant?`${canonicalPath}?variant=${variant}`:canonicalPath}}catch{}return handle?`/products/${handle}`:rawUrl}function syncProductCardLink(card){if(!card)return;const primaryLink=getPrimaryProductLink(card);if(!primaryLink)return;const canonicalUrl=getCanonicalProductUrl(card);canonicalUrl&&(primaryLink.setAttribute("href",canonicalUrl),card.dataset.productUrl=canonicalUrl)}function syncProductCardLinks(root=getRoot()){getProductCards(root).forEach(syncProductCardLink)}function findCardByHandle(handle,root=getRoot()){return!handle||!root?null:root.querySelector(`[data-
56product-card][data-product-handle="${CSS.escape(handle)}"]`)||getSeparatedComingSoonSection(root)?.querySelector(`[data-product-card][data-product-handle="${CSS.escape(handle)}"]`)||null}function getAnchorForCard(card){return card?{handle:card.dataset.productHandle||"",topOffset:card.getBoundingClientRect().top,origin:getCardOrigin(card)}:null}function getCurrentComingSoonMode(root=getRoot()){if(!root||root.getAttribute("data-default-collection-coming-soon-defer")!=="true")return null;const checkedInput=root.querySelector("[data-default-coming-soon-mode-input]:checked");return checkedInput&&checkedInput.value==="inline"?"inline":"defer"}function setLoading(root,isLoading){const loader=getLoader(root);loader&&(loader.hidden=!isLoading)}function updateSentinel(root){const sentinel=getSentinel(root),wrap=sentinel?.closest("[data-collection-sentinel-wrap]");wrap&&wrap.classList.toggle("hidden",!hasMorePages(root))}async function nextFrame(){return new Promise(resolve=>requestAnimationFrame(()=>resolve()))}async function waitForLayout(frames=2){for(let i=0;i<frames;i+=1)await nextFrame()}function animateAppendedCards(cards){cards.length&&(cards.forEach(card=>card.classList.add("collection-card-enter")),requestAnimationFrame(()=>{requestAnimationFrame(()=>{cards.forEach(card=>card.classList.add("collection-card-enter-active"))})}))}async function loadNextPage(root=getRoot(),options={}){if(!root||root.dataset.loading==="1"||!hasMorePages(root))return!1;const nextPage=getCurrentPage(root)+1,nextPageUrl=getNextPageUrl(root,nextPage);root.dataset.loading="1",setLoading(root,!0);try{const cacheKey=nextPageUrl,html=typeof cachedResponses=="object"&&cachedResponses!==null&&cachedResponses[cacheKey]?cachedResponses[cacheKey]:typeof fetchAndCachePage=="function"?await fetchAndCachePage(nextPageUrl):await fetchPage(nextPageUrl),parsed=document.createElement("div");parsed.innerHTML=html;const nextRoot=parsed.querySelector('#ProductGridContainer[data-auto-pagination="collection"]'),nextGrid=nextRoot?.querySelector("[data-content-wrapper]"),grid=getGrid(root);if(!nextRoot||!nextGrid||!grid)return!1;let appendedCards=Array.from(nextGrid.children);if(root.getAttribute("data-default-collection-coming-soon-defer")==="true"&&(appendedCards=appendedCards.filter(card=>!card.hasAttribute("data-default-coming-soon-section"))),!appendedCards.length)return root.dataset.currentPage=String(nextPage),updateSentinel(root),!1;const fragment=document.createDocumentFragment();return appendedCards.forEach(card=>card.setAttribute("data-dynamic-card","true")),appendedCards.forEach(syncProductCardLink),appendedCards.forEach(card=>fragment.appendChild(card)),grid.appendChild(fragment),root.dataset.currentPage=nextRoot.dataset.currentPage||String(nextPage),root.dataset.totalPages=nextRoot.dataset.totalPages||root.dataset.totalPages,updateSentinel(root),options.silent||animateAppendedCards(appendedCards),document.dispatchEvent(new CustomEvent("pagination:updated",{detail:{currentPage:getCurrentPage(root),lastPage:getTotalPages(root)}})),document.dispatchEvent(new CustomEvent("od:collection:grid-updated",{detail:{root,reason:"pagination"}})),!0}catch(error){return console.error("Collection pagination error:",error),!1}finally{root.dataset.loading="0",setLoading(root,!1),document.dispatchEvent(new CustomEvent("od:collection:pagination-settled",{detail:{root,currentPage:getCurrentPage(root),lastPage:getTotalPages(root)}}))}}async function ensureRestoreTarget(root,restoreState){const targetPage=Math.max(restoreState.currentPage||1,1),targetHandle=restoreState.targetHandle||restoreState.anchor&&restoreState.anchor.handle;for(;getCurrentPage(root)<targetPage&&!(targetHandle&&findCardByHandle(targetHandle,root)||!await loadNextPage(root,{silent:!0})););}async function waitForRestoreAnchor(root,snapshot,timeoutMs=1200){const anchorHandle=snapshot?.anchor?.handle;if(!anchorHandle)return null;const existingCard=findCardByHandle(anchorHandle,root);return existingCard||new Promise(resolve=>{let settled=!1,observer=null,timeoutId=null;const finish=card=>{settled||(settled=!0,observer&&observer.disconnect(),timeoutId&&clearTimeout(timeoutId),resolve(card||null))},check=()=>{const card=findCardByHandle(anchorHandle,root);card&&finish(card)};if("MutationObserver"in window){observer=new MutationObserver(check),observer.observe(root,{childList:!0,subtree:!0});const separatedSection=getSeparatedComingSoonSection(root);separatedSection&&observer.observe(separatedSection,{childList:!0,subtree:!0})}timeoutId=setTimeout(()=>finish(findCardByHandle(anchorHandle,root)),timeoutMs),requestAnimationFrame(check)})}function isSeparatedComingSoonAnchorReady(root,snapshot){if(snapshot?.comingSoonMode==="inline"||(snapshot?.anchor?.origin||"main-grid")!=="coming-soon")return!0;const section=getSeparatedComingSoonSection(root);if(!section||section.classList.contains("hidden"))return!1;const card=findCardByHandle(snapshot.anchor?.handle,root);return!!(card&&section.contains(card))}async function waitForSeparatedComingSoonReady(root,snapshot,timeoutMs=2500){isSeparatedComingSoonAnchorReady(root,snapshot)||await new Promise(resolve=>{let settled=!1,timeoutId=null;const finish=()=>{settled||(settled=!0,timeoutId&&clearTimeout(timeoutId),document.removeEventListener("od:default-coming-soon-state",onState),resolve())},onState=event=>{const detail=event.detail||{};detail.root===root&&detail.ready&&isSeparatedComingSoonAnchorReady(root,snapshot)&&finish()};timeoutId=setTimeout(finish,timeoutMs),document.addEventListener("od:default-coming-soon-state",onState),isSeparatedComingSoonAnchorReady(root,snapshot)&&finish()})}function getRestoreScrollTop(root,snapshot){const fallbackTop=typeof snapshot.scrollY=="number"?snapshot.scrollY:0,anchor=snapsh
56ot.anchor;if(!anchor||!anchor.handle||typeof anchor.topOffset!="number")return fallbackTop;const card=findCardByHandle(anchor.handle,root);if(!card)return fallbackTop;const absoluteCardTop=window.scrollY+card.getBoundingClientRect().top;return Math.max(absoluteCardTop-anchor.topOffset,0)}async function stabilizeRestorePosition(root,snapshot){const anchor=snapshot?.anchor;if(!anchor||!anchor.handle||typeof anchor.topOffset!="number"||!findCardByHandle(anchor.handle,root))return;await new Promise(resolve=>{const startedAt=performance.now(),maxWaitMs=250,stableFrameTarget=3,tolerance=.5;let lastTop=null,stableFrames=0;const check=()=>{const currentCard=findCardByHandle(anchor.handle,root);if(!currentCard){resolve();return}const currentTop=currentCard.getBoundingClientRect().top;if(lastTop!==null&&Math.abs(currentTop-lastTop)<=tolerance?stableFrames+=1:stableFrames=0,lastTop=currentTop,stableFrames>=stableFrameTarget||performance.now()-startedAt>=maxWaitMs){resolve();return}requestAnimationFrame(check)};requestAnimationFrame(check)});const correctedTop=getRestoreScrollTop(root,snapshot);Math.abs(window.scrollY-correctedTop)>2&&window.scrollTo({top:correctedTop,behavior:"auto"})}async function restoreCollectionStateIfNeeded(root=getRoot()){if(!root||root.dataset.restored==="1"||root.dataset.restoring==="1")return!1;const pendingRestore=getPendingRestoreForUrl(getRootUrl(root));return pendingRestore?(root.dataset.restoring="1",syncProductCardLinks(root),await ensureRestoreTarget(root,pendingRestore),await waitForSeparatedComingSoonReady(root,pendingRestore),await waitForRestoreAnchor(root,pendingRestore),await waitForLayout(2),window.scrollTo({top:getRestoreScrollTop(root,pendingRestore),behavior:"auto"}),window.__odCollectionRestore&&window.__odCollectionRestore.finishDeferredReveal(),await waitForLayout(1),await stabilizeRestorePosition(root,pendingRestore),await waitForLayout(1),root.dataset.restoring="0",root.dataset.restored="1",clearPendingRestore(),!0):(finishDeferredRestore({clearPending:!0}),!1)}function observeSentinel(root=getRoot()){sentinelObserver&&(sentinelObserver.disconnect(),sentinelObserver=null);const sentinel=getSentinel(root);!root||!sentinel||(sentinelObserver=new IntersectionObserver(entries=>{entries.forEach(entry=>{!entry.isIntersecting||root.dataset.restoring==="1"||loadNextPage(root)})},{rootMargin:"1200px 0px 1200px 0px"}),sentinelObserver.observe(sentinel))}async function initRoot(root){if(root){activeRoot=root,syncProductCardLinks(root),updateSentinel(root);try{await restoreCollectionStateIfNeeded(root)}catch(error){console.error("Collection restore init error:",error)}finally{observeSentinel(root),updateSentinel(root)}}}function initCollectionAutoPagination(){const root=getRoot();if(!root){activeRoot=null,sentinelObserver&&(sentinelObserver.disconnect(),sentinelObserver=null),finishDeferredRestore();return}if(activeRoot!==root){initRoot(root);return}updateSentinel(root),observeSentinel(root)}function captureReturnAnchor(event){const root=getRoot();if(!root)return;const separatedSection=getSeparatedComingSoonSection(root),target=event.target instanceof Element?event.target:null,card=target?target.closest("[data-product-card]"):null;if(!card||!root.contains(card)&&!(separatedSection&&separatedSection.contains(card)))return;const primaryLink=getPrimaryProductLink(card);if(!primaryLink||(target?target.closest("a[href]"):null)!==primaryLink)return;syncProductCardLink(card);const anchor=getAnchorForCard(card);window.__odCollectionRestore?.setPending(getRootUrl(root),window.scrollY,{anchor,currentPage:getCurrentPage(root),targetHandle:anchor?.handle||card.dataset.productHandle||"",comingSoonMode:getCurrentComingSoonMode(root)})}document.addEventListener("click",captureReturnAnchor,!0),document.addEventListener("DOMContentLoaded",initCollectionAutoPagination),document.addEventListener("shopify:page:load",initCollectionAutoPagination),document.addEventListener("shopify:section:load",initCollectionAutoPagination),document.addEventListener("od:main-content-replaced",initCollectionAutoPagination),document.addEventListener("od:after-swap",initCollectionAutoPagination),window.addEventListener("pushstate",initCollectionAutoPagination),window.addEventListener("popstate",initCollectionAutoPagination),"MutationObserver"in window&&(rootObserver=new MutationObserver(()=>{initCollectionAutoPagination()}),rootObserver.observe(document.body,{childList:!0,subtree:!0})),window.__odCollectionRestore={shouldDeferScrollRestore(url){const pendingRestore=getPendingRestoreForUrl(url);if(!pendingRestore)return!1;const restorePageDepth=Math.max(pendingRestore.currentPage||1,1),restoreOrigin=pendingRestore.anchor?.origin||"main-grid";return restorePageDepth>1||restoreOrigin==="coming-soon"},beginDeferredReveal(url){this.pendingUrl=normalizeCollectionUrl(url),document.body.classList.add("od-collection-restore-pending")},setPending(url,scrollPosition,metadata={}){const existing=readPendingRestore(),normalizedUrl=normalizeCollectionUrl(url),merged=existing&&normalizeCollectionUrl(existing.url)===normalizedUrl?{...existing,...metadata}:{...metadata};sessionStorage.setItem(PENDING_RESTORE_KEY,JSON.stringify({...merged,timestamp:Date.now(),url:normalizedUrl,scrollPosition}))},finishDeferredReveal(){document.body.classList.remove("od-collection-restore-pending"),this.pendingUrl=null}}
56,document.readyState!=="loading"&&initCollectionAutoPagination()})(),(function(){"use strict";var NS="__OPERADEPOT_APP__";if(window[NS])return;var App=window[NS]={version:"2025-08-20",debug:!1};function log(){if(App.debug)try{console.debug.apply(console,arguments)}catch{}}window.requestIdleCallback=window.requestIdleCallback||function(cb,opts){var start=Date.now();return setTimeout(function(){cb({didTimeout:!1,timeRemaining:function(){return Math.max(0,50-(Date.now()-start))}})},opts&&opts.timeout||1)},window.cancelIdleCallback=window.cancelIdleCallback||function(id){clearTimeout(id)};function debounce(fn,wait){var t=0;return function(){var ctx=this,args=arguments;clearTimeout(t),t=setTimeout(function(){fn.apply(ctx,args)},wait)}}function throttle(fn,gapMs){var last=0;return function(){var now=Date.now();now-last<gapMs||(last=now,fn.apply(this,arguments))}}(function(){var KEY="__minorUXInstalled";if(!window[KEY]){window[KEY]=!0;try{var usingMouse=!1;document.addEventListener("mousedown",function(){usingMouse=!0,document.documentElement.classList.add("using-mouse")}),document.addEventListener("keydown",function(e){e.key==="Tab"&&(usingMouse=!1,document.documentElement.classList.remove("using-mouse"))})}catch{}}})()})(),!window.__releaseTabsBound){let activateTab2=function(wrapper,name,focus){tabsOf(wrapper).forEach(tab=>{const on=tab.dataset.tabTarget===name;tab.setAttribute("aria-selected",on?"true":"false"),tab.setAttribute("tabindex",on?"0":"-1"),on&&focus&&tab.focus({preventScroll:!0})}),panelsOf(wrapper).forEach(panel=>{panel.hidden=panel.dataset.tabPanel!==name})},selectedName2=function(wrapper){const tab=tabsOf(wrapper).find(t=>t.getAttribute("aria-selected")==="true");return tab?tab.dataset.tabTarget:null},stripLeadingNumber2=function(el){const walker=document.createTreeWalker(el,NodeFilter.SHOW_TEXT);let node;for(;node=walker.nextNode();)if(node.textContent.trim()){node.textContent=node.textContent.replace(TRACK_LINE,"");return}},splitDuration2=function(el){let last=null;const walker=document.createTreeWalker(el,NodeFilter.SHOW_TEXT);let node;for(;node=walker.nextNode();)node.textContent.trim()&&(last=node);if(!last)return"";const match=last.textContent.match(TRACK_DURATION);return match?(last.textContent=last.textContent.slice(0,match.index).replace(/\s+$/,""),match[1]):""},enhanceTracklist2=function(wrapper){const panel=wrapper.querySelector('[data-tab-panel="tracklist"]');!panel||panel.dataset.enhanced==="1"||(panel.dataset.enhanced="1",Array.from(panel.querySelectorAll("div, p")).forEach(block=>{if(block.querySelector("div, p, ol, ul, table")||!TRACK_LINE.test(block.textContent))return;const lines=[[]];Array.from(block.childNodes).forEach(node=>{node.nodeName==="BR"?lines.push([]):lines[lines.length-1].push(node)});const list=document.createElement("ol");list.className="release-tracks";let lastTitle=null;lines.forEach(nodes=>{const text=nodes.map(n=>n.textContent).join("").trim();if(!text)return;const numMatch=text.match(TRACK_LINE);if(!numMatch&&lastTitle){const sub=document.createElement("span");sub.className="release-tracks__sub",nodes.forEach(n=>sub.appendChild(n.cloneNode(!0))),lastTitle.appendChild(sub);return}const row=document.createElement("li");row.className="release-tracks__row";const num=document.createElement("span");num.className="release-tracks__num";const title=document.createElement("span");title.className="release-tracks__title",nodes.forEach(n=>title.appendChild(n.cloneNode(!0))),numMatch&&(num.textContent=numMatch[1],stripLeadingNumber2(title)),row.append(num,title);const duration=splitDuration2(title);if(duration){const dur=document.createElement("span");dur.className="release-tracks__dur",dur.textContent=duration,row.appendChild(dur)}list.appendChild(row),lastTitle=title}),list.children.length&&block.replaceWith(list)}),panel.querySelectorAll("h1.title-header").forEach(h=>h.remove()),panel.querySelectorAll(".section-heading[style]").forEach(h=>h.removeAttribute("style")))},hydrate2=function(wrapper){enhanceTracklist2(wrapper);const tabs=tabsOf(wrapper);if(!tabs.length)return;let name=selectedName2(wrapper);(!name||!tabs.some(t=>t.dataset.tabTarget===name))&&(name=(tabs.find(t=>t.dataset.tabTarget==="description")||tabs[0]).dataset.tabTarget),activateTab2(wrapper,name,!1)},hydrateAll2=function(root){const scope=root&&root.querySelectorAll?root:document;scope instanceof Element&&scope.matches("[data-product-tabs]")&&hydrate2(scope),scope.querySelectorAll("[data-product-tabs]").forEach(hydrate2)};var activateTab=activateTab2,selectedName=selectedName2,stripLeadingNumber=stripLeadingNumber2,splitDuration=splitDuration2,enhanceTracklist=enhanceTracklist2,hydrate=hydrate2,hydrateAll=hydrateAll2;window.__releaseTabsBound=!0;const TRACK_LINE=/^\s*(\d+)[.)]\s*/,TRACK_DURATION=/[\s–—-]*(\d+:\d{2}(?::\d{2})?)\s*$/,tabsOf=wrapper=>Array.from(wrapper.querySelectorAll('[role="tab"][data-tab-target]')),panelsOf=wrapper=>Array.from(wrapper.querySelectorAll("[data-tab-panel]"));document.addEventListener("click",e=>{if(!(e.target instanceof Element))return;const tab=e.target.closest('[role="tab"][data-tab-target]');if(!tab)return;const wrapper=tab.closest("[data-product-tabs]");wrapper&&(e.preventDefault(),activateTab2(wrapper,tab.dataset.tabTarget,!1))}),document.addEventListener("keydown",e=>{if(!(e.target instanceof Element))return;const tab=e.target.closest('[role="tab"][data-tab-target]');if(!tab)return;const wrapper=tab.closest("[data-product-tabs]");if(!wrapper)return;const tabs=tabsOf(wrapper),index=tabs.indexOf(tab);let next=null;if(e.key==="ArrowRight")next=tabs[(index+1)%tabs.length];else if(e.key==="ArrowLeft")next=tabs[(index-1+tabs.length)%tabs.length];else if(e.key==="Home")next=tabs[0];else if(e.key==="End")next=tabs[tabs.length-1];else if(e.key==="Enter"||e.key===" "){e.preventDefault(),activateTab2(wrapper,tab.dataset.tabTarget,!1);return}else return;e.preventDefault(),activateTab2(wrapper,next.dataset.tabTarget,!0)});const runInit=()=>hydrateAll2(document);document.readyState==="loading"?document.addEventListener("DOMContentLoaded",runInit,{once:!0}
56):runInit(),document.addEventListener("shopify:page:load",runInit),document.addEventListener("shopify:section:load",e=>hydrateAll2(e.target)),window.addEventListener("popstate",runInit),["turbo:load","page:load","pjax:complete","swup:contentReplaced"].forEach(evt=>window.addEventListener(evt,runInit)),new MutationObserver(mutations=>{for(const m of mutations)for(const node of m.addedNodes)node instanceof HTMLElement&&(node.matches("[data-product-tabs]")&&hydrate2(node),node.querySelectorAll?.("[data-product-tabs]").forEach(hydrate2))}).observe(document.documentElement,{childList:!0,subtree:!0})}(function(){function paint(n){const wrap=document.querySelector("#od-desktop-header a.swym-wishlist .od-icon-wrap");if(!wrap)return;wrap.classList.contains("od-has-badge")||wrap.classList.add("od-has-badge");let badge=wrap.querySelector(".swym-wishlist-header-counter");badge||(badge=document.createElement("span"),badge.className="od-cart-badge od-wishlist-badge swym-wishlist-header-counter",badge.setAttribute("aria-live","polite"),wrap.appendChild(badge)),badge.textContent=n>9?"9+":n||"",badge.style.display=n>0?"inline-flex":"none"}try{paint(Alpine.store("wishlist")?.count||0)}catch{}document.addEventListener("alpine:init",()=>{Alpine.effect(()=>paint(Alpine.store("wishlist").count))}),document.addEventListener("shopify:section:load",()=>{try{paint(Alpine.store("wishlist").count)}catch{}})})(),(function(){function normalize(str){return(str||"").toLowerCase().replace(/[^\w\s]/g," ").replace(/\s+/g," ").trim()}function initCustomerLibrarySearch(){const input=document.getElementById("keyword-search"),clearBtn=document.getElementById("clear-search"),items=Array.from(document.querySelectorAll(".purchased-item"));if(!input||!items.length)return!1;if(input.dataset.bound==="1")return!0;input.dataset.bound="1";function runSearch(keyword){const tokens=normalize(keyword).split(" ").filter(Boolean);items.forEach(el=>{const title=normalize(el.dataset.title),match=tokens.length===0?!0:tokens.every(t=>title.includes(t));el.style.display=match?"":"none"})}return input.addEventListener("keydown",e=>{e.key==="Enter"&&(e.preventDefault(),runSearch(input.value),clearBtn&&(clearBtn.style.display=normalize(input.value)?"block":"none"))}),clearBtn&&(clearBtn.addEventListener("click",()=>{input.value="",runSearch(""),clearBtn.style.display="none"}),clearBtn.style.display="none"),console.log("\u{1F4DA} Customer library search initialized"),!0}function initWithRetries(){let tries=0;const tick=()=>{tries+=1,!initCustomerLibrarySearch()&&tries<20&&setTimeout(tick,150)};tick()}document.addEventListener("DOMContentLoaded",initWithRetries),document.addEventListener("shopify:page:load",initWithRetries),document.addEventListener("shopify:section:load",initWithRetries),document.addEventListener("od:after-swap",initWithRetries);let lastPath=location.pathname;new MutationObserver(()=>{location.pathname!==lastPath&&(lastPath=location.pathname,initWithRetries())}).observe(document.body,{childList:!0,subtree:!0})})(),(function(){const MODULE_ID="customer-library-loader";if(window[MODULE_ID])return;window[MODULE_ID]=!0;function initCustomerLibrary(){const grid=document.getElementById("library-grid"),status=document.getElementById("library-status"),loadingIndicator=document.getElementById("library-loading-indicator"),input=document.getElementById("keyword-search"),clearBtn=document.getElementById("clear-search"),viewInputs=document.querySelectorAll('input[name="library-view"]'),viewNote=document.getElementById("library-view-note");if(!grid||!status)return!1;if(grid.dataset.bound==="1")return!0;grid.dataset.bound="1";const endpoint=(grid.dataset.libraryEndpoint||"").trim();function resolveLibraryEndpointUrl(){if(!endpoint)return"";const resolvedUrl=new URL(endpoint,window.location.origin),customerId=window.Shopify&&window.Shopify.customer&&window.Shopify.customer.id?String(window.Shopify.customer.id).trim():"",needsDirectCustomerParam=resolvedUrl.pathname==="/api/library"||resolvedUrl.pathname.endsWith("/api/library");return customerId&&needsDirectCustomerParam&&!resolvedUrl.searchParams.has("customerId")&&!resolvedUrl.searchParams.has("logged_in_customer_id")&&resolvedUrl.searchParams.set("customerId",customerId),resolvedUrl.toString()}const state={selectedView:"alphabetical",query:"",libraryData:null,libraryPromise:null,nextOffset:0,hasMore:!0,isLoading:!1,requestId:0};function showStatus(message){status.innerHTML="",status.style.display="block",status.textContent=message}function hideStatus(){status.style.display="none"}function showLoading(){loadingIndicator&&(loadingIndicator.style.display="block")}function hideLoading(){loadingIndicator&&(loadingIndicator.style.display="none")}function isNearBottom(){return window.innerHeight+window.scrollY>=document.documentElement.scrollHeight-800}function getActiveView(){return state.query.trim()?"alphabetical":state.selectedView}function getBatchLimit(){return getActiveView()==="order"?8:32}function normalizeLibraryText(value){return value?value.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().trim():""}function escapeHtml(value){return String(value??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function readLibraryString(value){return String(value??"").trim()}function readLibrarySku(item){return readLibraryString(item&&(item.playlist_id||item.playlistId||item.catalogueNumber||item.catalogue_number||item.sku))}function getPurchasedStateItems(libraryData){const byHandle=new Map;function addItem(item,orderContext){if(!item||!item.handle)return;const handle=readLibraryString(item.handle);handle&&byHandle.set(handle,{handle,sku:readLibraryString(item.sku),catalogueNumber:readLibraryString(item.catalogueNumber||item.playlistId||item.sku),purchaseDate:readLibraryString(item.purchaseDate||item.purchase_date||item.orderDate||item.order_date||orderContext&&orderContext.orderDate),purchaseDateDisplay:readLibraryString(item.purchaseDateDisplay||item.purchase_date_display||item.orderDateDisplay||item.order_date_display||orderContext&&orderContext.orderDateDisplay)})}
56return(libraryData.alphabeticalRecordings||[]).forEach(addItem),(libraryData.groupedByOrder||[]).forEach(function(group){const orderContext={orderDate:readLibraryString(group&&(group.orderDate||group.order_date)),orderDateDisplay:readLibraryString(group&&(group.orderDateDisplay||group.order_date_display))};(group.recordings||[]).forEach(function(item){addItem(item,orderContext)})}),Array.from(byHandle.values())}function findPurchasedStateItem(handle){const state2=window.ODCustomerLibraryPurchases,normalizedHandle=readLibraryString(handle);return!state2||!normalizedHandle||!Array.isArray(state2.items)?null:state2.items.find(function(item){return item&&item.handle===normalizedHandle})||null}function ensurePurchasedBadge(target){if(!target||target.querySelector(".od-purchased-badge"))return;const badge=document.createElement("span");badge.className="od-purchased-badge",badge.textContent="Purchased",target.appendChild(badge)}function markPurchasedLaunchButton(button,purchase){!button||!purchase||(button.dataset.purchasedTitle="true",purchase.catalogueNumber&&(button.dataset.catalogueNumber=purchase.catalogueNumber),purchase.sku&&(button.dataset.sku=purchase.sku))}function applyPurchasedBadgesFromLibraryState(root){const scope=root||document,state2=window.ODCustomerLibraryPurchases;if(!state2||!Array.isArray(state2.items)||!state2.items.length)return;scope.querySelectorAll("[data-product-handle]").forEach(function(element){const handle=element.getAttribute("data-product-handle"),purchase=findPurchasedStateItem(handle);if(!purchase)return;element.classList&&element.classList.contains("opera-player-launch")&&markPurchasedLaunchButton(element,purchase);const card=element.closest("[data-product-card], .product-list-item, .streaming-visual-card");card&&(card.setAttribute("data-purchased-title","true"),card.setAttribute("data-catalogue-number",purchase.catalogueNumber||purchase.sku||""),card.setAttribute("data-sku",purchase.sku||purchase.catalogueNumber||""),!card.classList.contains("library-card")&&!card.classList.contains("library-streaming-card")&&ensurePurchasedBadge(card))});const configuredHandle=window.OperaDepotPlayerConfig&&window.OperaDepotPlayerConfig.productHandle,productPurchase=findPurchasedStateItem(configuredHandle),streamContainer=document.getElementById("stream-button-container");productPurchase&&streamContainer&&(streamContainer.setAttribute("data-purchased-title","true"),streamContainer.querySelectorAll(".opera-player-launch[data-product-handle]").forEach(function(button){markPurchasedLaunchButton(button,productPurchase)}),typeof window.ODApplyProductPagePurchase=="function"&&window.ODApplyProductPagePurchase(productPurchase))}function publishPurchasedLibraryState(libraryData){const items=getPurchasedStateItems(libraryData);window.ODCustomerLibraryPurchases={handles:items.map(function(item){return item.handle}),items,updatedAt:new Date().toISOString()},window.ODApplyPurchasedBadges=applyPurchasedBadgesFromLibraryState,document.dispatchEvent(new CustomEvent("od:customer-library-purchases-updated",{detail:window.ODCustomerLibraryPurchases})),applyPurchasedBadgesFromLibraryState(document)}function getCardTitleLines(title){const parts=String(title||"").trim().split(" - "),mainTitle=(parts.shift()||"").trim(),subtitle=parts.join(" - ").trim();return{mainTitle,subtitle}}function normalizeLibraryCard(item,orderContext){const title=String(item&&item.title?item.title:"").trim(),handle=String(item&&(item.handle||item.product_handle)||"").trim(),skuText=readLibrarySku(item),playlistId=readLibraryString(item&&(item.playlist_id||item.playlistId||skuText)),imageUrl=String(item&&(item.image_url||item.imageUrl||item.image)||"").trim(),searchTerms=normalizeLibraryText(item&&item.search_terms?item.search_terms:`${title} ${skuText}`);return{title,handle,sku:skuText,playlistId,catalogueNumber:skuText||playlistId,orderId:readLibraryString(orderContext&&orderContext.orderId),imageUrl,canPlay:item&&item.can_play!==!1,lockState:item&&item.lock_state?String(item.lock_state):"",lockReason:item&&item.lock_reason?String(item.lock_reason):"",normalizedTitle:normalizeLibraryText(item&&item.normalized_title?item.normalized_title:title),searchTerms}}function normalizeOrderGroup(group){return{orderId:String(group&&group.orderId?group.orderId:""),orderName:String(group&&group.orderName?group.orderName:""),orderDate:String(group&&group.orderDate?group.orderDate:""),orderDateDisplay:String(group&&group.orderDateDisplay?group.orderDateDisplay:""),recordings:Array.isArray(group&&group.recordings)?group.recordings.map(function(item){return normalizeLibraryCard(item,{orderId:group.orderId})}):[]}}function buildStreamingCardHtml(item){const titleLines=getCardTitleLines(item.title),rootAttributes=['class="product-list-item streaming-visual-card library-streaming-card"',"data-streaming-gradient-card",'data-purchased-title="true"'];
56item.handle&&rootAttributes.push(`data-product-handle="${escapeHtml(item.handle)}"`),item.sku&&rootAttributes.push(`data-sku="${escapeHtml(item.sku)}"`),item.catalogueNumber&&rootAttributes.push(`data-catalogue-number="${escapeHtml(item.catalogueNumber)}"`),item.playlistId&&rootAttributes.push(`data-playlist-id="${escapeHtml(item.playlistId)}"`),item.canPlay||(item.lockState&&(rootAttributes.push("data-free-streaming-locked-trigger"),rootAttributes.push(`data-lock-state="${escapeHtml(item.lockState)}"`)),item.lockReason&&rootAttributes.push(`data-lock-reason="${escapeHtml(item.lockReason)}"`),rootAttributes.push(`data-product-title="${escapeHtml(item.title)}"`),rootAttributes.push('role="button"'),rootAttributes.push('tabindex="0"'),rootAttributes.push(`aria-label="Unlock streaming for ${escapeHtml(item.title)}"`));const titleHtml=titleLines.subtitle?`<div class="title-line-1 streaming-visual-card__title-line streaming-visual-card__title-line--primary">${escapeHtml(titleLines.mainTitle)}</div><div class="title-line-2 streaming-visual-card__title-line streaming-visual-card__title-line--secondary">${escapeHtml(titleLines.subtitle)}</div>`:`<div class="title-line-1 streaming-visual-card__title-line streaming-visual-card__title-line--primary">${escapeHtml(item.title)}</div>`,infoHtml=item.canPlay?`<button type="button" class="player-switcher-info-button info-button streaming-visual-card__info-button" aria-label="More Info" data-handle="${escapeHtml(item.handle)}" data-lightbox-view="player-switcher-lightbox"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" class="info-icon" aria-hidden="true"><path fill="currentColor" d="M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1zm0 12.93A5.93 5.93 0 1 1 8 2.07a5.93 5.93 0 0 1 0 11.86zM8.93 6.588l-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465-.598l.088-.416c-.2.176-.492.246-.686.246-.275 0-.375-.193-.304-.533zM9 4.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/></svg><span>More Info</span></button>`:'<span class="streaming-visual-card__placeholder-button" aria-hidden="true">Unlock Full Access</span>',playAttributes=['type="button"','class="play-icon opera-player-launch streaming-visual-card__play-button"',`data-product-handle="${escapeHtml(item.handle)}"`,'data-purchased-title="true"',`aria-label="Play ${escapeHtml(item.title)}"`];item.sku&&playAttributes.push(`data-sku="${escapeHtml(item.sku)}"`),item.catalogueNumber&&playAttributes.push(`data-catalogue-number="${escapeHtml(item.catalogueNumber)}"`),item.playlistId&&playAttributes.push(`data-playlist-id="${escapeHtml(item.playlistId)}"`);const playHtml=item.canPlay&&item.handle?`<button ${playAttributes.join(" ")}><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5.2 3v18l14-9z" /></svg></button>`:`<button type="button" class="play-icon streaming-visual-card__play-button streaming-visual-card__play-button--locked" data-locked-play-trigger="true" aria-label="Unlock streaming for ${escapeHtml(item.title)}"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5.2 3v18l14-9z" /></svg></button>`;return`
57        <article ${rootAttributes.join(" ")}>
58          <div class="streaming-visual-card__media">
59            <div class="streaming-visual-card__image-glow">
60              <img
61                src="${escapeHtml(item.imageUrl)}"
62                alt="${escapeHtml(item.title)}"
63                class="streaming-visual-card__image"
64                loading="lazy"
65                crossorigin="anonymous"
66              >
67            </div>
68          </div>
69	          <div class="streaming-visual-card__body">
70	            <div class="streaming-visual-card__title-wrap">
71	              ${titleHtml}
72	            </div>
73            <div class="streaming-visual-card__actions">
74              ${infoHtml}
75              <div class="streaming-visual-card__play-wrap player-switcher-card__play-wrap">
76                ${playHtml}
77              </div>
78            </div>
79          </div>
80        </article>
81      `}function buildOrderGroupHtml(group){const cardsHtml=group.recordings.map(buildStreamingCardHtml).join("");return`
82        <section class="library-order-group">
83          <div class="library-order-header">
84            <h2 class="library-order-title">${escapeHtml(group.orderName)}</h2>
85            <p class="library-order-date">Placed ${escapeHtml(group.orderDateDisplay)}</p>
86          </div>
87          <div class="library-order-grid">
88            ${cardsHtml}
89          </div>
90        </section>
91      `}function renderHtmlBatch(html){if(!html)return;const template=document.createElement("template");template.innerHTML=html,grid.appendChild(template.content)}function finalizeRenderedLibrary(scope){window.ODStreamingVisualCardInit&&requestAnimationFrame(function(){window.ODStreamingVisualCardInit(scope||grid)})}async function ensureLibraryData(){const requestUrl=resolveLibraryEndpointUrl();if(!requestUrl)throw new Error("Customer library endpoint is not configured in Theme settings.");return state.libraryData?state.libraryData:(state.libraryPromise||(state.libraryPromise=fetch(requestUrl,{method:"GET",credentials:"same-origin",headers:{Accept:"application/json"}}).then(async function(response){const contentType=response.headers.get("content-type")||"",rawText=await response.text();if(!contentType.includes("application/json"))throw new Error("Expected JSON but received HTML or another response type.");const data=JSON.parse(rawText);if(!response.ok||data.ok===!1)throw new Error(data.error||"Failed to load your library");const normalized={alphabeticalRecordings:Array.isArray(data.alphabeticalRecordings)?data.alphabeticalRecordings.map(normalizeLibraryCard):[],groupedByOrder:Array.isArray(data.groupedByOrder)?data.groupedByOrder.map(normalizeOrderGroup):[]};return state.libraryData=normalized,publishPurchasedLibraryState(normalized),normalized}).finally(function(){state.libraryPromise=null})),state.libraryPromise)}function updateViewNote(){viewNote&&(viewNote.style.display=state.query.trim()?"block":"none")}function getAlphabeticalSearchResults(){const libraryData=state.libraryData;if(!libraryData)return[];const tokens=normalizeLibraryText(state.query).split(/\s+/).filter(
91Boolean);return tokens.length?libraryData.alphabeticalRecordings.filter(function(item){return tokens.every(function(token){return item.searchTerms.indexOf(token)!==-1})}):libraryData.alphabeticalRecordings}function getRenderSource(){const libraryData=state.libraryData;return libraryData?state.query.trim()?getAlphabeticalSearchResults():state.selectedView==="order"?libraryData.groupedByOrder:libraryData.alphabeticalRecordings:[]}async function loadNextBatch(replace){if(state.isLoading||!state.hasMore&&!replace)return;const requestId=++state.requestId;state.isLoading=!0,replace||showLoading(),replace&&(state.nextOffset=0,state.hasMore=!0,grid.innerHTML="");try{if(await ensureLibraryData(),requestId!==state.requestId)return;const renderSource=getRenderSource(),batchItems=renderSource.slice(state.nextOffset,state.nextOffset+getBatchLimit()),activeView=getActiveView();if(replace&&!batchItems.length){grid.innerHTML="",showStatus("No recordings found in your library."),state.hasMore=!1,hideLoading();return}const html=activeView==="order"?batchItems.map(buildOrderGroupHtml).join(""):batchItems.map(buildStreamingCardHtml).join("");renderHtmlBatch(html),finalizeRenderedLibrary(grid),state.nextOffset+=batchItems.length,state.hasMore=state.nextOffset<renderSource.length,grid.children.length&&hideStatus(),updateViewNote(),isNearBottom()&&state.hasMore&&loadNextBatch(!1)}catch(error){showStatus(error&&error.message?error.message:"Unable to load your library.")}finally{requestId===state.requestId&&(state.isLoading=!1,hideLoading())}}function runSearch(nextQuery){state.query=(nextQuery||"").trim(),state.nextOffset=0,state.hasMore=!0,state.requestId+=1,state.isLoading=!1,grid.innerHTML="",status.textContent="",showStatus("Loading your library..."),updateViewNote(),loadNextBatch(!0)}function updateSearchIconState(){if(!input||!clearBtn)return;const hasText=input.value.trim().length>0;clearBtn.style.display=hasText?"flex":"none";const icon=document.querySelector(".library-search-icon");icon&&(icon.style.display=hasText?"none":"flex")}function setupSearch(){input&&(updateSearchIconState(),input.addEventListener("input",function(){updateSearchIconState(),runSearch(input.value)}),clearBtn&&clearBtn.addEventListener("click",function(){input.value="",updateSearchIconState(),runSearch(""),input.focus()}))}function setupViewToggle(){viewInputs.length&&viewInputs.forEach(function(inputEl){inputEl.addEventListener("change",function(){inputEl.checked&&(state.selectedView=inputEl.value,updateViewNote(),state.query.trim()||(state.nextOffset=0,state.hasMore=!0,state.requestId+=1,state.isLoading=!1,grid.innerHTML="",showStatus("Loading your library..."),loadNextBatch(!0)))})})}function setupLazyScroll(){window.removeEventListener("scroll",window.__libraryScrollHandler),window.__libraryScrollHandler=function(){state.isLoading||!state.hasMore||isNearBottom()&&loadNextBatch(!1)},window.addEventListener("scroll",window.__libraryScrollHandler,{passive:!0})}function setupPressedStates(){const selectors=".product-list-item .play-icon, .product-list-item .info-button, .product-list-item .player-switcher-info-button";function getPressable(target){return target&&target.closest?target.closest(selectors):null}function clearPressed(){grid.querySelectorAll(".is-pressed").forEach(function(el){el.classList.remove("is-pressed")})}grid.addEventListener("pointerdown",function(evt){const target=getPressable(evt.target);target&&(clearPressed(),target.classList.add("is-pressed"))}),["pointerup","pointercancel","pointerleave","click"].forEach(function(eventName){grid.addEventListener(eventName,function(){clearPressed()})})}function initLibraryPage(){showStatus("Loading your library..."),updateViewNote(),setupSearch(),setupViewToggle(),setupPressedStates(),setupLazyScroll(),loadNextBatch(!0)}return initLibraryPage(),!0}function initCustomerLibraryWithRetries(){let tries=0;const maxTries=30;function tryInit(){initCustomerLibrary()||(tries+=1,tries<maxTries&&setTimeout(tryInit,100))}tryInit()}document.addEventListener("DOMContentLoaded",initCustomerLibraryWithRetries),document.addEventListener("shopify:page:load",initCustomerLibraryWithRetries
91),document.addEventListener("od:after-swap",initCustomerLibraryWithRetries),document.addEventListener("DOMContentLoaded",function(){window.ODApplyPurchasedBadges&&window.ODApplyPurchasedBadges(document)}),document.addEventListener("shopify:page:load",function(){window.ODApplyPurchasedBadges&&window.ODApplyPurchasedBadges(document)}),document.addEventListener("od:after-swap",function(){window.ODApplyPurchasedBadges&&window.ODApplyPurchasedBadges(document)}),window.addEventListener("pushstate",initCustomerLibraryWithRetries),window.addEventListener("popstate",initCustomerLibraryWithRetries)})(),(function(){const MODULE_ID="od-product-purchase-awareness";if(window[MODULE_ID])return;window[MODULE_ID]=!0;const STREAM_LABEL="Stream Recording",SAMPLE_LABEL="Sample Recording",BUTTON_SELECTOR="[data-product-stream-button], #stream-button-container .opera-player-launch[data-product-handle]",LABEL_SELECTOR="[data-product-stream-label], #stream-button-container .stream-label",BADGE_SELECTOR="[data-product-purchased-badge]",PRODUCT_PLAYER_TOAST_SUPPRESSION_CLASS="od-product-page-player-toast-suppressed",RETRY_EVERY_MS=120,RETRY_MAX_TRIES=20;let libraryLookupPromise=null,queuedMutationHydration=!1,lastObservedPath=location.pathname+location.search;function readString(value){return String(value??"").trim()}function normalizePresentationAccess(value,allowedValues,fallback){const normalized=readString(value).toLowerCase();return allowedValues.includes(normalized)?normalized:fallback}function getAccessRoot(){return window.ODMembershipAccess=window.ODMembershipAccess||{},window.ODMembershipAccess.state=window.ODMembershipAccess.state||{},window.ODMembershipAccess.config=window.ODMembershipAccess.config||{},window.ODMembershipAccess}function getAccessState(){const accessRoot=getAccessRoot();let state=accessRoot.state||{};if(typeof accessRoot.getState=="function")try{state=accessRoot.getState()||state}catch{state=accessRoot.state||{}}const customerPlaybackPolicy=state.customerPlaybackPolicy&&typeof state.customerPlaybackPolicy=="object"?state.customerPlaybackPolicy:{};return{customerPlaybackPolicy:{catalogueAccess:normalizePresentationAccess(customerPlaybackPolicy.catalogueAccess,["samples","compressed","lossless"],"samples"),comingSoonAccess:normalizePresentationAccess(customerPlaybackPolicy.comingSoonAccess,["none","samples","compressed","lossless"],"none")}}}function getCustomerId(){const accessRoot=getAccessRoot(),stateCustomerId=accessRoot.state?accessRoot.state.customerId:null;if(readString(stateCustomerId))return readString(stateCustomerId);const shopifyCustomerId=window.Shopify&&window.Shopify.customer?window.Shopify.customer.id:null;return readString(shopifyCustomerId)?readString(shopifyCustomerId):""}function normalizeRoot(root){return root&&(root.nodeType===Node.ELEMENT_NODE||root.nodeType===Node.DOCUMENT_NODE||root.nodeType===Node.DOCUMENT_FRAGMENT_NODE)?root:document}function elementMatches(element,selector){return!!(element&&element.nodeType===Node.ELEMENT_NODE&&typeof element.matches=="function"&&element.matches(selector))}function uniqueElements(elements){return elements.filter(function(element,index){return element&&elements.indexOf(element)===index})}function queryScoped(root,selector){const scope=normalizeRoot(root),elements=[];return elementMatches(scope,selector)&&elements.push(scope),typeof scope.querySelectorAll=="function"&&scope.querySelectorAll(selector).forEach(function(element){elements.push(element)}),uniqueElements(elements)}function syncProductPagePlayerToastSuppression(){if(!document.body||typeof document.querySelector!="function")return;const hasProductPagePlayer=!!document.querySelector("#stream-button-container .opera-player-launch[data-product-handle]");document.body.classList.toggle(PRODUCT_PLAYER_TOAST_SUPPRESSION_CLASS,hasProductPagePlayer)}function elementProductHandle(element){return readString(element&&element.getAttribute&&element.getAttribute("data-product-handle"))}function getFirstProductHandle(root){const buttons=queryScoped(root,BUTTON_SELECTOR);for(let index=0;index<buttons.length;index+=1){const handle=elementProductHandle(buttons[index]);if(handle)return handle}const badges=queryScoped(root,BADGE_SELECTOR);for(let index=0;
91index<badges.length;index+=1){const handle=elementProductHandle(badges[index]);if(handle)return handle}return""}function labelBelongsToProduct(label,productHandle){const streamContainer=label&&label.closest?label.closest("#stream-button-container"):null;if(!streamContainer)return!0;const button=streamContainer.querySelector(".opera-player-launch[data-product-handle]"),buttonHandle=elementProductHandle(button);return!buttonHandle||buttonHandle===productHandle}function badgeBelongsToProduct(badge,productHandle){const badgeHandle=elementProductHandle(badge);return!badgeHandle||badgeHandle===productHandle}function buttonBelongsToProduct(button,productHandle){const buttonHandle=elementProductHandle(button);return!buttonHandle||buttonHandle===productHandle}function isTruthyDataValue(value){const normalized=readString(value).toLowerCase();return normalized==="true"||normalized==="1"||normalized==="yes"}function hasProductClassification(button,datasetKey,attributeName){return!button||!button.dataset?!1:isTruthyDataValue(button.dataset[datasetKey])||isTruthyDataValue(button.getAttribute(attributeName))}function hasFreeStreamingButton(button){return hasProductClassification(button,"productFreeStreaming","data-product-free-streaming")}function hasComingSoonButton(button){return hasProductClassification(button,"productComingSoon","data-product-coming-soon")}function hasPurchasedButton(button){return!button||!button.dataset?!1:isTruthyDataValue(button.dataset.purchasedTitle)||isTruthyDataValue(button.getAttribute("data-purchased-title"))}function getProductContext(root){let scope=normalizeRoot(root),productHandle=getFirstProductHandle(scope);if(!productHandle&&scope!==document&&(scope=document,productHandle=getFirstProductHandle(scope)),!productHandle)return null;const buttons=queryScoped(scope,BUTTON_SELECTOR).filter(function(button){return buttonBelongsToProduct(button,productHandle)}),labels=queryScoped(scope,LABEL_SELECTOR).filter(function(label){return labelBelongsToProduct(label,productHandle)}),badges=queryScoped(scope,BADGE_SELECTOR).filter(function(badge){return badgeBelongsToProduct(badge,productHandle)}),streamContainers=uniqueElements(buttons.map(function(button){return button.closest?button.closest("#stream-button-container"):null})),freeStreamingProduct=buttons.some(hasFreeStreamingButton),comingSoonProduct=buttons.some(hasComingSoonButton);return!buttons.length&&!badges.length&&scope!==document?getProductContext(document):{root:scope,productHandle,buttons,labels,badges,streamContainers,freeStreamingProduct,comingSoonProduct}}function getCustomerLibraryEndpoint(){const config=getAccessRoot().config||{};return readString(config.customerLibraryEndpoint||config.customer_library_endpoint||"/apps/library")}function resolveLibraryEndpointUrl(){const endpoint=getCustomerLibraryEndpoint();if(!endpoint)return"";const resolvedUrl=new URL(endpoint,window.location.origin),pathname=resolvedUrl.pathname.replace(/\/+$/,""),customerId=getCustomerId(),needsDirectCustomerParam=pathname==="/api/library"||pathname.endsWith("/api/library");return customerId&&needsDirectCustomerParam&&!resolvedUrl.searchParams.has("customerId")&&!resolvedUrl.searchParams.has("logged_in_customer_id")&&resolvedUrl.searchParams.set("customerId",customerId),resolvedUrl.toString()}function setProductStreamLabel(context,label){const resolvedLabel=label===STREAM_LABEL?STREAM_LABEL:SAMPLE_LABEL;context.labels.forEach(function(labelElement){labelElement.textContent=resolvedLabel}),context.buttons.forEach(function(button){button.setAttribute("aria-label",resolvedLabel)})}function applyInitialProductStreamLabel(context){if(!context)return;const accessState=getAccessState();if(context.buttons.some(hasPurchasedButton)||context.freeStreamingProduct){setProductStreamLabel(context,STREAM_LABEL);return}const customerPlaybackPolicy=accessState.customerPlaybackPolicy,accessValue=readString(context.comingSoonProduct?customerPlaybackPolicy.comingSoonAccess:customerPlaybackPolicy.catalogueAccess).toLowerCase();setProductStreamLabel(context,accessValue==="compressed"||accessValue==="lossless"?STREAM_LABEL:SAMPLE_LABEL)}function formatDateDisplay(value){const rawValue=readString(value);if(!rawValue)return"";const timestamp=Date.parse(rawValue);if(!Number.isFinite(timestamp))return rawValue;try{return new Intl.DateTimeFormat(void 0,{month:"long",day:"numeric",year:"numeric"}).format(new Date(timestamp))}catch{return rawValue}}function readPurchaseDateDisplay(item,orderContext){const directDisplay=readString(item.purchaseDateDisplay||item.purchase_date_display||item.orderDateDisplay||item.order_date_display);if(directDisplay)return directDisplay;const directDate=readString(item.purchaseDate||item.purchase_date||item.orderDate||item.order_date);if(directDate)return formatDateDisplay(directDate);const orderDisplay=readString(orderContext&&orderContext.orderDateDisplay);return orderDisplay||formatDateDisplay(orderContext&&orderContext.orderDate)}function readLibrarySku(item){return readString(item&&(item.playlist_id||item.playlistId||item.catalogueNumber||item.catalogue_number||item.sku))}function normalizePurchasedItem(item,orderContext){const handle=readString(item&&(item.handle||item.product_handle||item.productHandle));if(!handle)return null;const sku=readLibrarySku(item);return{handle,sku:readString(item&&item.sku)||sku,catalogueNumber:readString(item&&(item.catalogueNumber||item.catalogue_number||item.playlistId||item.playlist_id))||sku,purchaseDate:readString(item&&(item.purchaseDate||item.purchase_date||item.orderDate||item.order_date))||readString(orderContext&&orderContext.orderDate),purchaseDateDisplay:readPurchaseDateDisplay(item||{},orderContext||{})}}function collectPurchasedItems(libraryData){const source=libraryData&&typeof libraryData=="object"?libraryData:{},byHandle=new Map;function addItem(item,orderContext){const purchase=normalizePurchasedItem(item,orderContext);if(!purchase)return;const existing=byHandle.get(purchase.handle);(!existing||!existing.purchaseDateDisplay&&purchase.purchaseDateDisplay)&&byHandle.set(purchase.handle,purchase)}
91return(source.alphabeticalRecordings||[]).forEach(function(item){addItem(item,null)}),(source.groupedByOrder||[]).forEach(function(group){const orderContext={orderDate:readString(group&&(group.orderDate||group.order_date)),orderDateDisplay:readString(group&&(group.orderDateDisplay||group.order_date_display))};(group&&group.recordings||[]).forEach(function(item){addItem(item,orderContext)})}),Array.from(byHandle.values())}function publishPurchasedState(libraryData){const items=collectPurchasedItems(libraryData),state={handles:items.map(function(item){return item.handle}),items,updatedAt:new Date().toISOString()};return window.ODCustomerLibraryPurchases=state,document.dispatchEvent(new CustomEvent("od:customer-library-purchases-updated",{detail:state})),state}function findPurchasedStateItem(handle,state){const purchaseState=state||window.ODCustomerLibraryPurchases,normalizedHandle=readString(handle);return!purchaseState||!normalizedHandle||!Array.isArray(purchaseState.items)?null:purchaseState.items.find(function(item){return item&&item.handle===normalizedHandle})||null}function markPurchasedLaunchButton(button,purchase){!button||!purchase||(button.dataset.purchasedTitle="true",purchase.catalogueNumber&&(button.dataset.catalogueNumber=purchase.catalogueNumber),purchase.sku&&(button.dataset.sku=purchase.sku))}function setProductPurchaseBadge(context,purchase){if(!purchase){context.badges.forEach(function(badge){badge.hidden=!0,badge.textContent="",badge.removeAttribute("data-purchased-title")});return}const badgeText=purchase.purchaseDateDisplay?"Purchased on "+purchase.purchaseDateDisplay:"Purchased";context.badges.forEach(function(badge){badge.textContent=badgeText,badge.hidden=!1,badge.setAttribute("data-purchased-title","true")})}function clearProductPurchaseMarkers(context){context.buttons.forEach(function(button){delete button.dataset.purchasedTitle,delete button.dataset.catalogueNumber,delete button.dataset.sku}),context.streamContainers.forEach(function(streamContainer){streamContainer.removeAttribute("data-purchased-title"),streamContainer.removeAttribute("data-catalogue-number"),streamContainer.removeAttribute("data-sku")}),setProductPurchaseBadge(context,null)}function applyProductPagePurchaseState(context,state){if(!context)return null;const purchase=findPurchasedStateItem(context.productHandle,state);return purchase?(context.buttons.forEach(function(button){markPurchasedLaunchButton(button,purchase)}),context.streamContainers.forEach(function(streamContainer){streamContainer.setAttribute("data-purchased-title","true")}),setProductStreamLabel(context,STREAM_LABEL),setProductPurchaseBadge(context,purchase),purchase):(clearProductPurchaseMarkers(context),applyInitialProductStreamLabel(context),null)}async function ensurePurchasedState(){const existingState=window.ODCustomerLibraryPurchases;if(existingState&&Array.isArray(existingState.items))return existingState;const requestUrl=resolveLibraryEndpointUrl();return requestUrl?(libraryLookupPromise||(libraryLookupPromise=fetch(requestUrl,{method:"GET",credentials:"same-origin",headers:{Accept:"application/json"}}).then(async function(response){const data=await response.json();if(!response.ok||data.ok===!1)throw new Error(data.error||"Failed to load customer library purchases");return publishPurchasedState(data)}).catch(function(error){return console.warn("[ProductPurchaseAwareness] ownership lookup failed",error),null}).finally(function(){libraryLookupPromise=null})),libraryLookupPromise):null}function hydratePurchasedProductState(root){syncProductPagePlayerToastSuppression();const context=getProductContext(root||document);if(!context)return!1;if(applyInitialProductStreamLabel(context),!getCustomerId())return clearProductPurchaseMarkers(context),applyInitialProductStreamLabel(context),!0;const cachedState=window.ODCustomerLibraryPurchases;return cachedState&&Array.isArray(cachedState.items)?(applyProductPagePurchaseState(context,cachedState),!0):(clearProductPurchaseMarkers(context),ensurePurchasedState().then(function(state){if(!state)return;const freshContext=getProductContext(document);freshContext&&applyProductPagePurchaseState(freshContext,state)}),!0)}function hydratePurchasedProductStateWithRetries(root){let attempts=0;function attempt(){hydratePurchasedProductState(root||document)||(attempts+=1,attempts<RETRY_MAX_TRIES&&setTimeout(attempt,RETRY_EVERY_MS))}attempt()}function queuePurchasedProductHydration(root){setTimeout(function(){hydratePurchasedProductStateWithRetries(root||document)},0)}function eventHydrationRoot(event){return event&&event.target&&event.target!==document?event.target:document.getElementById("MainContent")||document}window.ODApplyProductPagePurchase=function(purchase){if(!purchase)return null;const existingState=window.ODCustomerLibraryPurchases&&Array.isArray(window.ODCustomerLibraryPurchases.items)?window.ODCustomerLibraryPurchases:null,
91state=existingState?Object.assign({},existingState,{items:existingState.items.some(function(item){return item&&item.handle===purchase.handle})?existingState.items:existingState.items.concat(purchase),handles:existingState.handles&&existingState.handles.indexOf(purchase.handle)!==-1?existingState.handles:(existingState.handles||[]).concat(purchase.handle)}):{handles:[purchase.handle],items:[purchase],updatedAt:new Date().toISOString()};window.ODCustomerLibraryPurchases=state;const context=getProductContext(document);return applyProductPagePurchaseState(context,state)},window.ODHydratePurchasedProductState=hydratePurchasedProductState,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",function(){hydratePurchasedProductStateWithRetries(document)}):hydratePurchasedProductStateWithRetries(document),document.addEventListener("shopify:page:load",function(event){hydratePurchasedProductStateWithRetries(eventHydrationRoot(event))}),document.addEventListener("shopify:section:load",function(event){hydratePurchasedProductStateWithRetries(eventHydrationRoot(event))}),document.addEventListener("od:after-swap",function(event){hydratePurchasedProductStateWithRetries(eventHydrationRoot(event))}),document.addEventListener("od:main-content-replaced",function(event){hydratePurchasedProductStateWithRetries(eventHydrationRoot(event))}),document.addEventListener("od:membership-access-updated",function(){hydratePurchasedProductStateWithRetries(document)}),document.addEventListener("od:customer-library-purchases-updated",function(event){const context=getProductContext(document);context&&applyProductPagePurchaseState(context,event&&event.detail)}),window.addEventListener("pushstate",function(){queuePurchasedProductHydration(document)}),window.addEventListener("popstate",function(){queuePurchasedProductHydration(document)}),new MutationObserver(function(mutations){const currentPath=location.pathname+location.search;let shouldHydrate=currentPath!==lastObservedPath;shouldHydrate&&(lastObservedPath=currentPath),shouldHydrate||(shouldHydrate=mutations.some(function(mutation){return Array.from(mutation.addedNodes||[]).some(function(node){return elementMatches(node,BUTTON_SELECTOR)||elementMatches(node,BADGE_SELECTOR)||!!(node&&node.querySelector&&node.querySelector(BUTTON_SELECTOR+", "+BADGE_SELECTOR))})})),!(!shouldHydrate||queuedMutationHydration)&&(queuedMutationHydration=!0,setTimeout(function(){queuedMutationHydration=!1,hydratePurchasedProductStateWithRetries(document)},0))}).observe(document.body,{childList:!0,subtree:!0})})(),(()=>{const MODULE_ID="streaming-card-bootstrap";if(window[MODULE_ID])return;window[MODULE_ID]=!0;const STREAMING_CARD_SELECTOR="[data-streaming-gradient-card]",RETRY_EVERY_MS=120,RETRY_MAX_TRIES=20;var mutationInitTimer=null,mutationInitRoot=null;function getStreamingCardRoot(root){var scope=root||document;return scope===document?document:scope.matches&&scope.matches(STREAMING_CARD_SELECTOR)?scope.parentElement||document:scope.querySelector&&scope.querySelector(STREAMING_CARD_SELECTOR)?scope:document}function initStreamingCards(root){var scope=getStreamingCardRoot(root),cards=scope.querySelectorAll(STREAMING_CARD_SELECTOR);return cards.length?(window.ODStreamingVisualCardInit&&window.ODStreamingVisualCardInit(scope),!0):!1}function initStreamingCardsWithRetries(root){var attempts=0;function attempt(){initStreamingCards(root)||(attempts+=1,attempts<RETRY_MAX_TRIES&&setTimeout(attempt,RETRY_EVERY_MS))}attempt()}function getAddedStreamingCardRoot(node){return!node||node.nodeType!==1?null:node.matches&&node.matches(STREAMING_CARD_SELECTOR)?node.parentElement||document:node.querySelector&&node.querySelector(STREAMING_CARD_SELECTOR)?node:null}function getMutationStreamingCardRoot(mutations){for(var mutationIndex=0;mutationIndex<mutations.length;mutationIndex+=1)for(var addedNodes=mutations[mutationIndex].addedNodes||[],nodeIndex=0;nodeIndex<addedNodes.length;nodeIndex+=1){var root=getAddedStreamingCardRoot(addedNodes[nodeIndex]);if(root)return root}return null}function mergeMutationInitRoot(root){if(!mutationInitRoot){mutationInitRoot=root||document;return}if(!(!root||root===mutationInitRoot)&&!(mutationInitRoot.contains&&mutationInitRoot.contains(root))){if
91(root.contains&&root.contains(mutationInitRoot)){mutationInitRoot=root;return}mutationInitRoot=document}}function queueMutationStreamingCardsInit(root){mergeMutationInitRoot(root),window.clearTimeout(mutationInitTimer),mutationInitTimer=window.setTimeout(function(){var rootToInit=mutationInitRoot||document;mutationInitTimer=null,mutationInitRoot=null,initStreamingCardsWithRetries(rootToInit)},80)}document.addEventListener("DOMContentLoaded",function(){initStreamingCardsWithRetries(document)}),document.addEventListener("shopify:page:load",function(){initStreamingCardsWithRetries(document)}),document.addEventListener("shopify:section:load",function(event){initStreamingCardsWithRetries(event&&event.target||document)}),document.addEventListener("od:after-swap",function(event){initStreamingCardsWithRetries(event&&event.target||document)}),window.addEventListener("popstate",function(){initStreamingCardsWithRetries(document)}),new MutationObserver(function(mutations){var root=getMutationStreamingCardRoot(mutations);root&&queueMutationStreamingCardsInit(root)}).observe(document.body,{childList:!0,subtree:!0})})(),(()=>{const MODULE_ID="player-switcher-pressed-states";if(window[MODULE_ID])return;window[MODULE_ID]=!0;function initPlayerSwitcherPressedStates(){document.querySelectorAll(".player-switcher-grid").forEach(function(grid){if(grid.dataset.pressBound==="1")return;grid.dataset.pressBound="1";const selectors=".play-icon, .player-switcher-info-button";function getPressable(target){return target&&target.closest?target.closest(selectors):null}function clearPressed(){grid.querySelectorAll(".is-pressed").forEach(function(el){el.classList.remove("is-pressed")})}grid.addEventListener("pointerdown",function(evt){const target=getPressable(evt.target);target&&(clearPressed(),target.classList.add("is-pressed"))}),["pointerup","pointercancel","pointerleave","click"].forEach(function(eventName){grid.addEventListener(eventName,function(){clearPressed()})})})}document.addEventListener("DOMContentLoaded",initPlayerSwitcherPressedStates),document.addEventListener("shopify:page:load",initPlayerSwitcherPressedStates),document.addEventListener("od:after-swap",initPlayerSwitcherPressedStates),window.addEventListener("pushstate",initPlayerSwitcherPressedStates),window.addEventListener("popstate",initPlayerSwitcherPressedStates)})(),(()=>{const MODULE_ID="od-homepage-lazy-sections";if(window[MODULE_ID])return;window[MODULE_ID]=!0;const KEEP_INITIAL_SECTIONS=4,OBSERVER_ROOT_MARGIN="1400px 0px 1400px 0px",INITIAL_VIEWPORT_BUFFER=900,SECTION_LAZY_SELECTORS=["[data-free-streaming-section]"],state={observer:null,entries:new Map,lastKey:""};function isHomePage(){return!!document.querySelector(".od-index-header-spacer")}function hasHomepageLazyDisableFlag(){try{return new URLSearchParams(window.location.search).get("od_disable_home_lazyload")==="1"}catch{return!1}}function getHomepageSections(){const main=document.getElementById("MainContent");return main?Array.from(main.children).filter(node=>node instanceof HTMLElement&&/^shopify-section-/.test(node.id)):[]}function getSectionInstanceId(node){return!(node instanceof HTMLElement)||!node.id?"":node.id.replace(/^shopify-section-/,"")}function measureSectionHeight(node){if(!(node instanceof HTMLElement))return 320;const rect=node.getBoundingClientRect(),computed=window.getComputedStyle(node),measured=Math.max(rect.height||0,node.offsetHeight||0,parseFloat(computed.minHeight)||0);return Math.round(measured||320)}function isNearInitialViewport(node){if(!(node instanceof HTMLElement))return!1;const rect=node.getBoundingClientRect(),viewportHeight=window.innerHeight||document.documentElement.clientHeight||0;return rect.bottom>=-INITIAL_VIEWPORT_BUFFER&&rect.top<=viewportHeight+INITIAL_VIEWPORT_BUFFER}function isSectionLazyEligible(sectionEl){return sectionEl instanceof HTMLElement?SECTION_LAZY_SELECTORS.some(selector=>!!sectionEl.querySelector(selector)):!1}function buildPlaceholder(sectionId,height){const placeholder=document.createElement("div");return placeholder.className="shopify-section od-homepage-lazy-placeholder",placeholder.setAttribute("data-homepage-lazy-managed","true"),placeholder.setAttribute("data-homepage-lazy-placeholder",""),placeholder.setAttribute("data-section-id",sectionId),placeholder.setAttribute("aria-hidden","true"),placeholder.style.display="block",placeholder.style.minHeight=`${height}px`,placeholder.style.contain="layout paint style",placeholder.style.contentVisibility="auto",placeholder.style.containIntrinsicSize=`${height}px`,placeholder}function cloneScript(script){const replacement=document.createElement("script");
91return Array.from(script.attributes).forEach(attribute=>{replacement.setAttribute(attribute.name,attribute.value)}),replacement.textContent=script.textContent,replacement}function activateInsertedScripts(root){root instanceof HTMLElement&&root.querySelectorAll("script").forEach(script=>{if(script.dataset.homepageLazyExecuted==="true")return;const replacement=cloneScript(script);replacement.dataset.homepageLazyExecuted="true",script.replaceWith(replacement)})}function dispatchSectionLifecycleEvents(sectionEl,sectionId){sectionEl instanceof HTMLElement&&["shopify:section:load","shopify:section:render"].forEach(eventName=>{sectionEl.dispatchEvent(new CustomEvent(eventName,{bubbles:!0,detail:{sectionId}}))})}function scheduleHydrationStep(callback){const run=()=>{window.setTimeout(callback,0)};if("requestAnimationFrame"in window){window.requestAnimationFrame(run);return}run()}function runHydrationQueue(tasks){const queue=Array.isArray(tasks)?tasks.slice():[],runNext=()=>{const task=queue.shift();if(typeof task=="function"){try{task()}catch(error){console.warn("[HomepageLazySections] Hydration step failed:",error)}queue.length&&scheduleHydrationStep(runNext)}};queue.length&&scheduleHydrationStep(runNext)}function hydrateInsertedSection(sectionEl,sectionId){sectionEl.setAttribute("data-homepage-lazy-managed","true"),runHydrationQueue([()=>activateInsertedScripts(sectionEl),()=>{window.Alpine&&typeof window.Alpine.initTree=="function"&&window.Alpine.initTree(sectionEl)},()=>{const paymentButton=window.Shopify&&window.Shopify.PaymentButton;paymentButton&&typeof paymentButton.init=="function"&&paymentButton.init()},()=>{window.ODStreamingVisualCardInit&&window.ODStreamingVisualCardInit(sectionEl)},()=>dispatchSectionLifecycleEvents(sectionEl,sectionId)])}function getSectionSelector(sectionId){const safeId=`shopify-section-${sectionId}`;return window.CSS&&typeof window.CSS.escape=="function"?`#${window.CSS.escape(safeId)}`:`[id="${safeId.replace(/"/g,'\\"')}"]`}function parseSectionMarkup(html,sectionId){const template=document.createElement("template");return template.innerHTML=html.trim(),template.content.querySelector(getSectionSelector(sectionId))||template.content.firstElementChild}async function fetchSection(sectionId){const url=new URL(window.location.href);url.searchParams.delete("section_id"),url.searchParams.set("section_id",sectionId);const response=await fetch(url.toString(),{credentials:"same-origin",headers:{"X-Requested-With":"XMLHttpRequest"}});if(!response.ok)throw new Error(`Unable to fetch section ${sectionId}`);const html=await response.text(),markup=parseSectionMarkup(html,sectionId);if(!(markup instanceof HTMLElement))throw new Error(`Missing section markup for ${sectionId}`);return markup}function clearObserver(){state.observer&&(state.observer.disconnect(),state.observer=null)}function resetState(){clearObserver(),state.entries.clear(),state.lastKey=""}async function loadDeferredSection(entry){if(!(!entry||entry.loading||entry.loaded)){entry.loading=!0,state.observer&&state.observer.unobserve(entry.placeholder);try{const sectionEl=await fetchSection(entry.sectionId);entry.loaded=!0,entry.placeholder.isConnected&&(entry.placeholder.replaceWith(sectionEl),hydrateInsertedSection(sectionEl,entry.sectionId))}catch(error){console.warn("[HomepageLazySections] Falling back to server-rendered section:",error),entry.placeholder.isConnected&&entry.fallback instanceof HTMLElement&&(entry.placeholder.replaceWith(entry.fallback),hydrateInsertedSection(entry.fallback,entry.sectionId))}finally{state.entries.delete(entry.sectionId),entry.loading=!1}}}function deferSection(sectionEl){const sectionId=getSectionInstanceId(sectionEl);if(!sectionId||state.entries.has(sectionId))return;const placeholder=buildPlaceholder(sectionId,measureSectionHeight(sectionEl)),entry={sectionId,placeholder,fallback:sectionEl,loaded:!1,loading:!1};state.entries.set(sectionId,entry),sectionEl.replaceWith(placeholder),state.observer.observe(placeholder)}function buildObserver(){return"IntersectionObserver"in window?new IntersectionObserver(entries=>
91{entries.forEach(observerEntry=>{if(!observerEntry.isIntersecting&&observerEntry.intersectionRatio<=0)return;const sectionId=observerEntry.target.getAttribute("data-section-id");sectionId&&loadDeferredSection(state.entries.get(sectionId))})},{rootMargin:OBSERVER_ROOT_MARGIN,threshold:.01}):null}function initHomepageLazySections(){if(window.Shopify&&window.Shopify.designMode||!isHomePage()||hasHomepageLazyDisableFlag()){resetState();return}const pageKey=`${location.pathname}${location.search}`;if(state.lastKey===pageKey&&document.querySelector("[data-homepage-lazy-managed]"))return;resetState();const sections=getHomepageSections();if(sections.length<=KEEP_INITIAL_SECTIONS){state.lastKey=pageKey;return}if(state.observer=buildObserver(),!state.observer){state.lastKey=pageKey;return}let hasDeferredSection=!1;sections.slice(KEEP_INITIAL_SECTIONS).forEach(sectionEl=>{isSectionLazyEligible(sectionEl)&&(isNearInitialViewport(sectionEl)||(deferSection(sectionEl),hasDeferredSection=!0))}),hasDeferredSection||clearObserver(),state.lastKey=pageKey}function scheduleHomepageLazySectionsInit(){const run=()=>initHomepageLazySections(),scheduleAfterLoad=()=>{if("requestIdleCallback"in window){requestIdleCallback(run,{timeout:800});return}requestAnimationFrame(run)};if(document.readyState==="complete"){scheduleAfterLoad();return}window.addEventListener("load",scheduleAfterLoad,{once:!0})}scheduleHomepageLazySectionsInit(),document.addEventListener("shopify:page:load",initHomepageLazySections),document.addEventListener("od:after-swap",initHomepageLazySections),window.addEventListener("pushstate",initHomepageLazySections),window.addEventListener("popstate",initHomepageLazySections)})(),(()=>{const MODULE_ID="od-homepage-composite-lazy-blocks";if(window[MODULE_ID])return;window[MODULE_ID]=!0;const ROOT_MARGIN="1200px 0px 1200px 0px";function isHomePage(){return!!document.querySelector(".od-index-header-spacer")}function hasHomepageLazyDisableFlag(){try{return new URLSearchParams(window.location.search).get("od_disable_home_lazyload")==="1"}catch{return!1}}function getSections(root){const scope=root&&root.querySelectorAll?root:document;return scope instanceof HTMLElement&&scope.matches("[data-home-composite-section]")?[scope]:Array.from(scope.querySelectorAll("[data-home-composite-section]"))}function hydrateBlock(blockRoot){blockRoot instanceof HTMLElement&&(window.Alpine&&typeof window.Alpine.initTree=="function"&&window.Alpine.initTree(blockRoot),document.dispatchEvent(new CustomEvent("od:homepage-composite:block:load",{detail:{blockId:blockRoot.getAttribute("data-block-id")||"",sectionId:blockRoot.closest("[data-home-composite-section]")?.getAttribute("data-section-id")||""}})))}function loadPlaceholder(placeholder,observer){if(!(placeholder instanceof HTMLElement)||placeholder.dataset.loaded==="true")return;placeholder.dataset.loaded="true",observer&&observer.unobserve(placeholder);const templateId=placeholder.getAttribute("data-template-id");if(!templateId)return;const template=document.getElementById(templateId),replacement=template&&template.content&&template.content.firstElementChild?template.content.firstElementChild.cloneNode(!0):null;replacement instanceof HTMLElement&&(replacement.setAttribute("data-block-id",placeholder.getAttribute("data-block-id")||""),placeholder.replaceWith(replacement),template&&template.remove(),hydrateBlock(replacement))}function initSection(section){if(!(section instanceof HTMLElement)||section.dataset.compositeLazyReady==="true")return;const placeholders=Array.from(section.querySelectorAll("[data-home-composite-placeholder]"));if(section.dataset.compositeLazyReady="true",!placeholders.length)return;if(!("IntersectionObserver"in window)){placeholders.forEach(placeholder=>loadPlaceholder(placeholder));return}const observer=new IntersectionObserver(entries=>{entries.forEach(entry=>{!entry.isIntersecting&&entry.intersectionRatio<=0||loadPlaceholder(entry.target,observer)})},{rootMargin:ROOT_MARGIN,threshold:.01});placeholders.forEach(placeholder=>observer.observe(placeholder))}function initHomepageCompositeLazyBlocks(root){const sections=getSections(root);if(isHomePage()&&hasHomepageLazyDisableFlag()){sections.forEach(section=>{Array.from(section.querySelectorAll("[data-home-composite-placeholder]")).forEac
91h(placeholder=>{loadPlaceholder(placeholder)}),section.dataset.compositeLazyReady="true"});return}sections.forEach(initSection)}document.addEventListener("DOMContentLoaded",function(){initHomepageCompositeLazyBlocks(document)}),document.addEventListener("shopify:page:load",function(){initHomepageCompositeLazyBlocks(document)}),document.addEventListener("shopify:section:load",function(event){initHomepageCompositeLazyBlocks(event&&event.target||document)}),document.addEventListener("od:after-swap",function(event){initHomepageCompositeLazyBlocks(event&&event.target||document)}),window.addEventListener("pushstate",function(){initHomepageCompositeLazyBlocks(document)}),window.addEventListener("popstate",function(){initHomepageCompositeLazyBlocks(document)})})(),(()=>{const MODULE_ID="od-editorial-newsletter-ajax";if(window[MODULE_ID])return;window[MODULE_ID]=!0;const SECTION_SELECTOR="[data-editorial-newsletter-section]",FORM_SELECTOR="[data-editorial-newsletter-form]",FALLBACK_FORM_SELECTOR=`${SECTION_SELECTOR} .editorial-newsletter__form`,FEEDBACK_SELECTOR="[data-editorial-newsletter-feedback]",SUBMIT_SELECTOR="[data-editorial-newsletter-submit]",DEBUG_QUERY_PARAM="od_newsletter_debug",DEFAULT_SUCCESS_MESSAGE="Thank you. You're on the list.",DEFAULT_ERROR_MESSAGE="Please check your email address and try again.",UNKNOWN_RESPONSE_MESSAGE="We could not confirm the subscription. Please try again.",ADDITIONAL_VERIFICATION_MESSAGE="An additional verification step is required. Please try again.",CAPTCHA_READY_EVENT="od:newsletter-captcha-ready",CAPTCHA_TIMEOUT_MS=2e4,CAPTCHA_TOKEN_SELECTOR=['input[name="h-captcha-response"]','textarea[name="h-captcha-response"]','input[name="g-recaptcha-response"]','textarea[name="g-recaptcha-response"]','input[name="recaptcha-v3-token"]'].join(",");function isDebugEnabled(){try{return window.OD_NEWSLETTER_DEBUG===!0||new URLSearchParams(window.location.search).has(DEBUG_QUERY_PARAM)}catch{return window.OD_NEWSLETTER_DEBUG===!0}}function debugLog(message,details){if(isDebugEnabled()){if(details===void 0){console.info("[OD Newsletter]",message);return}console.info("[OD Newsletter]",message,details)}}function debugWarn(message,details){if(isDebugEnabled()){if(details===void 0){console.warn("[OD Newsletter]",message);return}console.warn("[OD Newsletter]",message,details)}}debugLog("controller initialization");function normalizeText(element){return element&&element.textContent?element.textContent.replace(/\s+/g," ").trim():""}function getForms(root){const scope=root&&typeof root.querySelectorAll=="function"?root:document,forms=new Set;return scope.matches&&(scope.matches(FORM_SELECTOR)||scope.matches(FALLBACK_FORM_SELECTOR))&&forms.add(scope),scope.querySelectorAll(FORM_SELECTOR).forEach(form=>forms.add(form)),scope.querySelectorAll(FALLBACK_FORM_SELECTOR).forEach(form=>forms.add(form)),Array.from(forms).filter(form=>form instanceof HTMLFormElement)}function getSection(form){return form.closest(SECTION_SELECTOR)||form.closest(".shopify-section")}function getSectionId(form){const section=getSection(form);return section?section.dataset&&section.dataset.editorialNewsletterSection?section.dataset.editorialNewsletterSection:section.id?section.id.replace(/^shopify-section-/,""):"":""}function getFeedback(form){const section=getSection(form);return section?section.querySelector(FEEDBACK_SELECTOR):form.querySelector(FEEDBACK_SELECTOR)}function getSubmitButton(form){return form.querySelector(SUBMIT_SELECTOR)||form.querySelector('button[type="submit"]')}function getCaptchaTokenFields(form){return form?Array.from(form.querySelectorAll(CAPTCHA_TOKEN_SELECTOR)).filter(field=>field instanceof HTMLInputElement||field instanceof HTMLTextAreaElement):[]}function hasCaptchaToken(form){return getCaptchaTokenFields(form).some(field=>String(field.value||"").trim().length>0)}function isShopifyCaptchaForm(form){return form?form.getAttribute("data-shopify-captcha")==="true"||form.dataset.cptcha==="true"||form.dataset.hcaptchaBound==="true"||form.dataset.recaptchaBound==="true":!1}function getCaptchaDebugInfo(form){return form?{hasShopifyCaptchaAttribute:form.getAttribute("data-shopify-captcha")==="true",dataCptcha:form.dataset.cptcha||"",hcaptchaBound:form.dataset.hcaptchaBound||"",recaptchaBound:form.dataset.recaptchaBound||"",bridgeInstalled:form.dataset.odNewsletterCaptchaBridge==="true",tokenFields:getCaptchaTokenFields(form).map(field=>({name:field.name||"",tagName:field.tagName,valueLength:String(field.value||"").length}))}:{}}function installCaptchaSubmitBridge(form){if(!(!form||form.getAttribute("data-shopify-captcha")!=="true")&&form.dataset.odNewsletterCaptchaBridge!=="true")try{form.submit=function(){debugLog("shopify captcha submit bridge invoked",getCaptchaDebugInfo(form)),form.dataset.odNewsletterCaptchaReady="true",form.dispatchEvent(new CustomEvent(CAPTCHA_READY_EVENT))},form.dataset.odNewsletterCaptchaBridge="true",debugLog("shopify captcha submit bridge installed",getCaptchaDebugInfo(form))}catch(error){debugWarn("shopify captcha submit bridge failed",{name:error&&error.
91name?error.name:"Error",message:error&&error.message?error.message:""})}}function waitForCaptchaReady(form,timeoutMs=CAPTCHA_TIMEOUT_MS){return isShopifyCaptchaForm(form)?hasCaptchaToken(form)?Promise.resolve({ready:!0,reason:"token-present"}):new Promise(resolve=>{let finished=!1,observer=null,timer=null;const cleanup=()=>{form.removeEventListener(CAPTCHA_READY_EVENT,onCaptchaReady),form.removeEventListener("input",onFieldChange,!0),form.removeEventListener("change",onFieldChange,!0),observer&&observer.disconnect(),timer&&window.clearTimeout(timer)},finish=(ready,reason)=>{finished||(finished=!0,cleanup(),resolve({ready,reason}))},checkForToken=reason=>{hasCaptchaToken(form)&&finish(!0,reason)};function onCaptchaReady(){window.setTimeout(()=>{checkForToken("captcha-submit-bridge")},0)}function onFieldChange(){checkForToken("captcha-field-change")}form.addEventListener(CAPTCHA_READY_EVENT,onCaptchaReady),form.addEventListener("input",onFieldChange,!0),form.addEventListener("change",onFieldChange,!0),"MutationObserver"in window&&(observer=new MutationObserver(()=>checkForToken("captcha-field-added")),observer.observe(form,{childList:!0,subtree:!0})),timer=window.setTimeout(()=>{finish(hasCaptchaToken(form),hasCaptchaToken(form)?"captcha-timeout-with-token":"captcha-timeout")},timeoutMs)}):Promise.resolve({ready:!0,reason:"not-protected"})}function getFormDebugInfo(form){const section=getSection(form);return{sectionId:getSectionId(form),formId:form.id||"",action:form.action||"",method:form.method||"",hasDataMarker:form.hasAttribute("data-editorial-newsletter-form"),hasFeedback:!!getFeedback(form),hasSubmitButton:!!getSubmitButton(form),sectionRootId:section&&section.id?section.id:"",captcha:getCaptchaDebugInfo(form)}}function setButtonState(button,isLoading,originalMarkup){if(button){if(isLoading){button.disabled=!0,button.textContent="Joining...";return}button.disabled=!1,typeof originalMarkup=="string"&&(button.innerHTML=originalMarkup)}}function setFeedback(form,type,message){const feedback=getFeedback(form);feedback&&(feedback.hidden=!message,feedback.textContent=message||"",feedback.classList.remove("editorial-newsletter__message--success","editorial-newsletter__message--error"),feedback.setAttribute("role",type==="error"?"alert":"status"),type==="success"&&feedback.classList.add("editorial-newsletter__message--success"),type==="error"&&feedback.classList.add("editorial-newsletter__message--error"))}function hideRenderedMessages(form){form.querySelectorAll(".editorial-newsletter__message:not([data-editorial-newsletter-feedback])").forEach(message=>{message.hidden=!0})}function addFeedbackDescription(form){const feedback=getFeedback(form),emailInput=form.querySelector('input[name="contact[email]"]');if(!feedback||!feedback.id||!emailInput)return;const describedBy=(emailInput.getAttribute("aria-describedby")||"").split(/\s+/).filter(Boolean);describedBy.includes(feedback.id)||(describedBy.push(feedback.id),emailInput.setAttribute("aria-describedby",describedBy.join(" ")))}function getPostedStateFromUrl(url){if(!url)return"";try{const responseUrl=new URL(url,window.location.href);if(responseUrl.searchParams.get("customer_posted")==="true"||responseUrl.searchParams.get("contact_posted")==="true")return"success"}catch{return""}return""}function findResponseScope(doc,sectionId){if(!doc)return null;if(sectionId){const sectionRoot=doc.getElementById(`shopify-section-${sectionId}`);if(sectionRoot)return sectionRoot;const section=doc.querySelector(`[data-editorial-newsletter-section="${sectionId}"]`);if(section)return section.closest(".shopify-section")||section}const markedForm=doc.querySelector(FORM_SELECTOR);if(markedForm)return markedForm.closest(".shopify-section")||markedForm.closest(SECTION_SELECTOR)||markedForm;const editorialForm=doc.querySelector(FALLBACK_FORM_SELECTOR);if(editorialForm)return editorialForm.closest(".shopify-section")||editorialForm.closest(SECTION_SELECTOR)||editorialForm;const contactForm=doc.getElementById("contact_form")||doc.querySelector('form[action*="/contact"]');return contactForm?contactForm.closest(".shopify-section")||contactForm:null}function getResponseUrlMarkers(responseUrl){try{const url=new URL(responseUrl,window.location.href);return{path:url.pathname,isChallengeUrl:/\/challenge(?:\/|$)/.test(url.pathname)}}catch{return{path:"",isChallengeUrl:!1}}}function getResponseMarkers(doc,scope,responseUrl,sectionId,postedState,responseMeta={}){const responseUrlMarkers=getResponseUrlMarkers(responseUrl),bodyText=doc&&doc.body&&doc.body.textContent?doc.body.textContent:"",errorSelector='.editorial-newsletter__message--error, .errors, [role="alert"]',successSelector=".editorial-newsletter__message--success, .newsletter-form__message--success, .form__message--success",challengeSelector='.shopify-challenge__container, .shopify-challenge__button, form[action*="/challenge"]',activeCaptchaErrorSelector=".shopify-challenge__message, .h-captcha[data-error], [data-captcha-error]",hasCloudflareChallengeMarkup=!!(doc&&(doc.querySelector('#challenge-error-text, .cf-injected-html, script[src*="/cdn-cgi/challenge-platform/"]')||/window\._cf_chl_opt|Your connection needs to be verified before you can proceed/i.test(bodyText))),cfMitigated=String(responseMeta.cfMitigated||"").toLowerCase(),responseStatus=Number(responseMeta.status)||0;return{sectionId:sectionId||"",postedState,responseStatus,responsePath:responseUrlMarkers.path,cfMitigated,hasExactSectionRoot:!!(sectionId&&doc&&doc.getElementById(`shopify-section-${sectionId}`)),hasEditorialSection:!!(doc&&doc.querySelector(SECTION_SELECTOR)),hasMarkedForm:!!(doc&&doc.querySelector(FORM_SELECTOR)),hasEditorialForm:!!(doc&&doc.querySelector(FALLBACK_FORM_SELECTOR)),hasContactForm:!!(doc&&(doc.getElementById("contact_form")||doc.querySelector('form[action*="/contact"]'))),hasScope:!!scope,hasScopedSuccess:!!(scope&&scope.querySelector(successSelector)),hasAnySuccess:!!(doc&&doc.querySelector(successSelector)),hasNewsletterSuccessText:/thanks for subscribing/i.test(bodyText),hasScopedError:!!(scope&&scope.querySelector(errorSelector)),hasAnyError:!!(doc&&doc.querySelector(errorSelector)),hasChallengeMarkup:!!(doc&&doc.querySelector(challengeSelector)),hasCloudflareChallengeMarkup,hasActiveCaptchaError:!!(doc&&doc.querySelector(activeCaptchaErrorSelector)),isChallengeUrl:responseUrlMarkers.isChallengeUrl,isChallengeResponse:cfMitigated==="challenge"||responseStatus===403&&hasCloudflareChallengeMarkup}}function parseShopifyResponse(html,responseUrl,sectionId,responseMeta={}){const postedState=getPostedStateFromUrl(responseUrl),doc=new DOMParser().parseFromString(html,"text/html"),scope=findResponseScope(doc,sectionId),markers=getResponseMarkers(doc,scope,responseUrl,sectionId,postedState,responseMeta);if(debugLog("response markers",markers),scope){const error=scope.querySelector('.editorial-newsletter__message--error, [role="alert"], .errors');if(error)return{status:"error",message:normalizeText(error)||DEFAULT_ERROR_MESSAGE,markers};if(scope.querySelector(".editorial-newsletter__message--success, .newsletter-form__message--success, .form__message--success"))return{status:"success",message:DEFAULT_SUCCESS_MESSAGE,markers}}if(doc.querySelector(".editorial-newsletter__message--success, .newsletter-form__message--success, .form__message--success")||postedState==="success"||markers.hasNewsletterSuccessText)return{status:"success",message:DEFAULT_SUCCESS_MESSAGE,markers};if(markers.hasChallengeMarkup||markers.hasCloudflareChallengeMarkup||markers.isChallengeUrl||markers.isChallengeResponse)return{status:"challenge",reason:markers.isChallengeUrl?"challenge-url":markers.hasCloudflareChallengeMarkup||markers.isChallengeResponse?"cloudflare-challenge":"challenge-markup",markers};if(markers.hasScopedError||markers.hasActiveCaptchaError){const error=scope&&scope.querySelector('.editorial-newsletter__message--error, [role="alert"], .errors')||doc.querySelector('.editorial-newsletter__message--error, [role="alert"], .errors, .shopify-challenge__message, [data-captcha-error]');return{status:"error",message:normalizeText(error)||DEFAULT_ERROR_MESSAGE,markers}}return{status:"unknown",message:UNKNOWN_RESPONSE_MESSAGE,markers}}function isFormValid(form){return typeof form.checkValidity=="function"&&!form.checkValidity()?(typeof form.reportValidity=="function"&&form.reportValidity(),!1):!0}function bindForm(form){if(!form)return;if(installCaptchaSubmitBridge(form),form.dataset.editorialNewsletterAjaxInit==="true"){debugLog("submit listener already attached",getFormDebugInfo(form));return}form.dataset.editorialNewsletterAjaxInit="true";const submitButton=getSubmitButton(form),originalButtonMarkup=submitButton?submitButton.innerHTML:"";let isSubmitting=!1;const handler=async event=>{if(debugLog("submit event received",getFormDebugInfo(form)),isSubmitting){event.preventDefault(),debugWarn("duplicate submit prevented");return}const isValid=isFormValid(form);if(debugLog("native validity result",{isValid}),!isValid)return;event.preventDefault(),debugLog("preventDefault reached",{defaultPrevented:event.defaultPrevented}),isSubmitting=!0,form.setAttribute("aria-busy","true"),hideRenderedMessages(form),setFeedback(form,"",""),setButtonState(submitButton,!0,originalButtonMarkup);const scrollX=window.scrollX,scrollY=window.scrollY;try{debugLog("captcha state before wait",getCaptchaDebugInfo(form));const captchaResult=await waitForCaptchaReady(form);if(debugLog("captcha wait result",{...captchaResult,captcha:getCaptchaDebugInfo(form)}),!captchaResult.ready){setFeedback(form,"error",ADDITIONAL_VERIFICATION_MESSAGE),addFeedbackDescription(form),window.scrollTo(scrollX,scrollY);return}debugLog("fetch started",{action:form.action,method:(form.method||"post").toUpperCase()});const response=await fetch(form.action,{method:(form.method||"post").toUpperCase(),body:new FormData(form),credentials:"same-origin",headers:{Accept:"text/html"}}),responseMeta={status:response.status,url:response.url,redirected:response.redirected,contentType:response.headers.get("content-type")||"",cfMitigated:response.headers.get("cf-mitigated")||""};debugLog("fetch response",responseMeta);const html=await response.text(),result=parseShopifyResponse(html,response.url,getSectionId(form),responseMeta),emailInput=form.querySelector('input[name="contact[email]"]');if(result.status==="success"){debugLog("success detected",result.markers||{}),setFeedback(form,"success",result.message||DEFAULT_SUCCESS_MESSAGE),emailInput&&(emailInput.value="",emailInput.removeAttribute("aria-invalid")),window.scrollTo(scrollX,scrollY);return}if(result.status==="error"){debugLog("errors detected",result.markers||{}),setFeedback(form,"error",result.message||DEFAULT_ERROR_MESSAGE),addFeedbackDescription(form),emailInput&&emailInput.setAttribute("aria-invalid","true");const feedback=getFeedback(form);feedback&&typeof feedback.focus=="function"&&(feedback.setAttribute("tabindex","-1"),feedback.focus({preventScroll:!0})),window.scrollTo(scrollX,scrollY);return}if(result.status==="challenge"){debugWarn("captcha/challenge detected",result.markers||{}),setFeedback(form,"error",ADDITIONAL_VERIFICATION_MESSAGE),addFeedbackDescription(form),window.scrollTo(scrollX,scrollY);return}else{debugWarn("unknown HTML response; showing inline error without native fallback",result.markers||{}),setFeedback(form,"error",result.message||UNKNOWN_RESPONSE_MESSAGE),addFeedbackDescription(form),window.scrollTo(scrollX,scrollY);return}}catch(error){debugWarn("fetch failed;
91 showing inline retry error",{name:error&&error.name?error.name:"Error",message:error&&error.message?error.message:""}),setFeedback(form,"error","We could not reach Shopify. Please try again."),addFeedbackDescription(form)}finally{isSubmitting=!1,form.removeAttribute("aria-busy"),setButtonState(submitButton,!1,originalButtonMarkup)}};form.addEventListener("submit",handler),debugLog("submit listener attached",getFormDebugInfo(form))}function initEditorialNewsletterAjax(root){const forms=getForms(root);debugLog("forms found",{count:forms.length}),forms.forEach(form=>{debugLog("form found",getFormDebugInfo(form)),bindForm(form)})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>initEditorialNewsletterAjax(document),{once:!0}):initEditorialNewsletterAjax(document),document.addEventListener("shopify:page:load",()=>initEditorialNewsletterAjax(document)),document.addEventListener("shopify:section:load",event=>initEditorialNewsletterAjax(event&&event.target||document)),document.addEventListener("od:after-swap",event=>initEditorialNewsletterAjax(event&&event.target||document)),window.addEventListener("pageshow",()=>initEditorialNewsletterAjax(document))})(),window.Sunrise=Sunrise,document.addEventListener("alpine:init",()=>{Alpine.plugin(Portal),Alpine.plugin(StickyScroll),Alpine.plugin(module_default$1),Alpine.plugin(module_default),Alpine.plugin(TransitionPlugin),Alpine.plugin(ElementIntersection),Alpine.plugin(Pagination),Alpine.plugin(Accessibility),Alpine.store("popup",PopupStore),Alpine.store("main",Main),Alpine.store("resizable",ResizableStore),Alpine.store("productList",ProductListStore),Alpine.store("cart",CartStore),Alpine.data("TransitionPreview",TransitionPreview),Alpine.data("BeforeAfter",BeforeAfter),Alpine.data("ProductList",ProductList),Alpine.data("Filters",Filters),Alpine.data("ProductPage",ProductPage),Alpine.data("Dropdown",Dropdown),Alpine.data("Search",Search),Alpine.data("Accordion",Accordion),Alpine.data("Address",Address),Alpine.data("RangeSlider",RangeSlider),Alpine.data("Slider",Slider),Alpine.data("CountdownTimer",CountdownTimer),Alpine.data("TransitionImage",TransitionImage),Alpine.data("ImageZoom",ImageZoom)}),document.addEventListener("click",evt=>{const moreBtn=evt.target.closest("[data-od-more]");if(!moreBtn)return;const root=moreBtn.closest("[data-od-reviews]"),hidden=root.querySelectorAll(".od-review--hidden"),reveal=Math.min(10,hidden.length);for(let i=0;i<reveal;i++)hidden[i].classList.remove("od-review--hidden");root.querySelectorAll(".od-review--hidden").length===0&&moreBtn.parentElement.remove()}),document.addEventListener("change",evt=>{const sortSel=evt.target.closest("[data-od-sort]");if(!sortSel)return;const list=sortSel.closest("[data-od-reviews]").querySelector("[data-od-list]"),cards=Array.from(list.querySelectorAll("[data-od-review]")),mode=sortSel.value;cards.sort((a,b)=>{const ra=+a.dataset.rating,rb=+b.dataset.rating,da=+a.dataset.date,db=+b.dataset.date;return mode==="highest"?rb-ra||db-da:mode==="lowest"?ra-rb||db-da:mode==="oldest"?da-db:db-da});const shownCount=list.querySelectorAll("[data-od-review]:not(.od-review--hidden)").length,avatarPalette=["plum","sage","gold"];cards.forEach((card,i)=>{card.classList.toggle("od-review--hidden",i>=shownCount);const avatar=card.querySelector(".od-review__avatar");avatar&&(avatarPalette.forEach(c=>avatar.classList.remove("od-review__avatar--"+c)),avatar.classList.add("od-review__avatar--"+avatarPalette[i%3])),list.appendChild(card)})}),(()=>{if(window.__odShowcaseShuffle)return;window.__odShowcaseShuffle=!0;const shuffleShowcases=()=>{document.querySelectorAll("[data-od-showcase-track]:not([data-od-shuffled])").forEach(track=>{track.setAttribute("data-od-shuffled","true");const cards=Array.from(track.children);for(let i=cards.length-1;i>0;i--){const j=Math.floor(Math.random()*(i+1));[cards[i],cards[j]]=[cards[j],cards[i]]}const displayCount=Number(track.dataset.odDisplayCount)||cards.length,drawn=cards.slice(0,displayCount),rest=cards.slice(displayCount),isTop=card=>!!card.querySelector(".od-top-reviewer");drawn.filter(isTop).concat(drawn.filter(card=>!isTop(card)),rest).forEach((card,i)=>{card.hidden=i>=displayCount,track.appendChild(card)}),track.scrollLeft=0})};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",shuffleShowcases,{once:!0}):shuffleShowcases(),["od:main-content-replaced","od:after-swap","shopify:page:load","shopify:section:load"].forEach(eventName=>{document.addEventListener(eventName,()=>setTimeout(shuffleShowcases,0))}),window.addEventListener("popstate",()=>setTimeout(shuffleShowcases,0))})(),document.addEventListener("click",evt=>{const arrow=evt.target.closest("[data-od-showcase-prev], [data-od-showcase-next]");if(!arrow)return;const track=arrow.closest("[data-od-showcase]")?.querySelector("[data-od-showcase-track]");if(!track)return;const card=track.querySelector(".od-showcase__card"),step=card?card.getBoundingClientRect().width+17:track.clientWidth*.8,direction=arrow.hasAttribute("data-od-showcase-prev")?-1:1,reducedMotion=window.matchMedia("(prefers-reduced-motion: reduce)").matches;track.scrollBy({left:direction*step,behavior:reducedMotion?"auto":"smooth"})});function odLoadTurnstile(){return window.turnstile&&typeof window.turnstile.render=="function"?Promise.resolve(window.turnstile):new Promise((resolve,reject)=>{let script=document.querySelector('script[data-od-turnstile-script="true"]');script||(script=document.createElement("script"),script.src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",script.async=!0,script.setAttribute("data-od-turnstile-script","true"),document.head.appendChild(script)),script.addEventListener("load",()=>resolve(window.turnstile),{once:!0}),script.addEventListener("error",()=>reject(new Error("turnstile load failed")),{once:!0}),window.turnstile&&typeof window.turnstile.render=="function"&&resolve(window.turnstile)})}function odReviewFormParts(el){const root=el.closest("[data-od-reviews]");return root?{root,btn:root.querySelector("[data-od-write]"),wrap:root.querySelector("[data-od-form-wrap]"),heading:root.querySelector("[data-od-form-heading]")}:null}function odRenderReviewTurnstile(root){const container=root.querySelector("[data-od-turnstile]");container&&container.dataset.rendered&&!container.dataset.widgetId&&!container.firstElementChild&&(container.dataset.rendered=""),!(!container||container.dataset.rendered)&&(container.dataset.rendered="true",odLoadTurnstile().then(turnstile=>{try{const widgetId=turnstile.render(container,{sitekey:root.dataset.turnstileSitekey,callback:()=>{container.dataset.solved="true"},"expired-callback":()=>{container.dataset.solved=""},"error-callback":code=>{container.dataset.lastError=String(code||"unknown")}});widgetId?container.dataset.widgetId=widgetId:(container.dataset.lastError="render returned no widget id",container.dataset.rendered="")}catch(e){container.dataset.lastError="render threw: "+(e&&e.message?e.message:String(e)),container.dataset.rendered=""}}).catch(e=>{container.dataset.lastError="script: "+(e&&e.message?e.message:String(e)),container.dataset.rendered=""}))}function odAfterHeightTransition(wrap,callback,timeoutMs){let done=!1;const finish=()=>{done||(done=!0,wrap.removeEventListener("transitionend",onEnd),callback())},onEnd=event=>{event.target===wrap&&event.propertyName==="height"&&finish()};wrap.addEventListener("transitionend",onEnd),setTimeout(finish,timeoutMs)}function odOpenReviewForm(parts){const{root,btn,wrap,heading}=parts;if(!wrap||wrap.dataset.odAnimating||!wrap.hidden)return;btn.setAttribute("aria-expanded","true"),odRenderReviewTurnstile(root);const settle=()=>{const target=heading||wrap,rect=target.getBoundingClientRect();(rect.top<0||rect.top>window.innerHeight*.8)&&target.scrollIntoView({block:"nearest",behavior:"smooth"}),heading&&heading.focus({preventScroll:!0})};if(window.matchMedia("(prefers-reduced-motion: reduce)").matches){btn.hidden=!0,wrap.hidden=!1,wrap.classList.add("is-open"),settle();return}wrap.dataset.odAnimating="true",btn.classList.add("od-review-cta--hiding"),setTimeout(()=>{btn.hidden=!0,btn.classList.remove("od-review-cta--hiding"),wrap.hidden=!1;const targetHeight=wrap.scrollHeight;wrap.style.height="0px",wrap.classList.add("is-animating"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{wrap.style.height=targetHeight+"px",wrap.classList.add("is-open")})}),odAfterHeightTransition(wrap,()=>{wrap.classList.remove("is-animating"),wrap.style.height="",delete wrap.dataset.odAnimating,settle()},600)},140)}function odCloseReviewForm(parts){const{btn,wrap}=parts;if(!(!wrap||wrap.hidden||wrap.dataset.odAnimating)){if(btn.setAttribute("aria-expanded","fal
91se"),window.matchMedia("(prefers-reduced-motion: reduce)").matches){wrap.hidden=!0,wrap.classList.remove("is-open"),btn.hidden=!1,btn.focus({preventScroll:!0});return}wrap.dataset.odAnimating="true",wrap.style.height=wrap.scrollHeight+"px",wrap.classList.add("is-animating"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{wrap.classList.remove("is-open"),wrap.style.height="0px"})}),odAfterHeightTransition(wrap,()=>{wrap.hidden=!0,wrap.classList.remove("is-animating"),wrap.style.height="",delete wrap.dataset.odAnimating,btn.hidden=!1,btn.classList.add("od-review-cta--showing"),requestAnimationFrame(()=>{requestAnimationFrame(()=>btn.classList.remove("od-review-cta--showing"))}),btn.focus({preventScroll:!0})},500)}}document.addEventListener("click",evt=>{const writeBtn=evt.target.closest("[data-od-write]"),cancelBtn=evt.target.closest("[data-od-form-cancel]");if(!writeBtn&&!cancelBtn)return;const parts=odReviewFormParts(writeBtn||cancelBtn);!parts||!parts.wrap||!parts.btn||(cancelBtn||!parts.wrap.hidden?odCloseReviewForm(parts):odOpenReviewForm(parts))}),document.addEventListener("keydown",evt=>{if(evt.key!=="Escape")return;const wrap=document.querySelector("[data-od-form-wrap]:not([hidden])");if(!wrap)return;const parts=odReviewFormParts(wrap);parts&&parts.btn&&odCloseReviewForm(parts)}),document.addEventListener("change",evt=>{const starField=evt.target.closest("[data-od-star-input]");if(!starField)return;const inputs=Array.from(starField.querySelectorAll("input")),checkedIndex=inputs.findIndex(input=>input.checked);inputs.forEach((input,i)=>{const label=starField.querySelector(`label[for="${input.id}"]`);label&&label.classList.toggle("is-filled",i<=checkedIndex)})}),document.addEventListener("submit",async evt=>{const form=evt.target.closest("[data-od-form]");if(!form)return;evt.preventDefault();const root=form.closest("[data-od-reviews]");if(form.dataset.odSubmitting==="1")return;const productHandle=root.dataset.productHandle,message=form.querySelector("[data-od-form-message]"),showMessage=(text,kind)=>{message.textContent=text,message.hidden=!1,message.className=`od-review-form__message od-review-form__message--${kind}`},data=new FormData(form);if(!data.get("rating")){showMessage("Please choose an overall rating.","error");return}const turnstileContainer=form.querySelector("[data-od-turnstile]"),submitBtn=form.querySelector('button[type="submit"]'),readTurnstileToken=()=>{const input=turnstileContainer?.querySelector('input[name="cf-turnstile-response"]');let token=input&&input.value||"";if(!token&&window.turnstile&&turnstileContainer?.dataset.widgetId)try{token=window.turnstile.getResponse(turnstileContainer.dataset.widgetId)||""}catch{}return token},quietSuccess=root.hasAttribute("data-od-quiet-success"),submitLabel=submitBtn.textContent;form.dataset.odSubmitting="1",submitBtn.disabled=!0,submitBtn.textContent="Submitting\u2026";const turnstileToken=readTurnstileToken();turnstileToken||console.warn("[OD reviews] submitting without Turnstile token",{script:!!window.turnstile,widgetId:turnstileContainer?.dataset.widgetId||null,lastError:turnstileContainer?.dataset.lastError||null}),quietSuccess||showMessage("Submitting\u2026","success");try{const result=await(await fetch(root.dataset.submitEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({productHandle,rating:Number(data.get("rating")),soundRating:data.get("soundRating")?Number(data.get("soundRating")):null,title:data.get("title")||"",body:data.get("body")||"",name:data.get("name")||"",email:data.get("email")||"",turnstileToken})})).json().catch(()=>({}));result.ok?(form.reset(),form.querySelectorAll(".is-filled").forEach(el=>el.classList.remove("is-filled")),quietSuccess?message.hidden=!0:showMessage(result.status==="published"?"Thank you! Your review has been published \u2014 reload the page to see it.":"Thank you! Your review has been received and is awaiting approval.","success"),form.dispatchEvent(new CustomEvent("od:review-submitted",{bubbles:!0,detail:{status:result.status,productHandle,reviewId:result.reviewId||"",rating:Number(data.get("rating")),soundRating:data.get("soundRating")?Number(data.get("soundRating")):null,title:String(data.get("title")||""),body:String(data.get("body")||"")}}))):showMessage(result.message||"Something went wrong \u2014 please try again.","error")}catch{showMessage("Could not reach the server \u2014 please try again.","error")}finally{if(delete form.dataset.odSubmitting,submitBtn.disabled=!1,submitBtn.textContent=submitLabel,window.turnstile&&turnstileContainer?.dataset.widgetId)try{window.turnstile.reset(turnstileContainer.dataset.widgetId)}catch{}}}),(function(){const MODULE_ID="od-review-dashboard";if(window[MODULE_ID])return;window[MODULE_ID]=!0;const RETRY_EVERY_MS=150,RETRY_MAX_TRIES=20,SWIPE_MIN_PX=48,state={root:null,items:[],customer:null,index:0,reviewCount:0,myReviews:[],historyShown:10,editingIndex:null,drafts:{},lastFocus:null,animating:!1},boundRoots=new WeakSet,reducedMotion=()=>window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;function escapeHtml(value){return String(value??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function normalizeTitle(raw){return String(raw||"").replace(/[\s\u00a0\u2007\u202f]+/g," ").trim()}function titleHtml(raw){const title=normalizeTitle(raw),colon=title.indexOf(": ");if(colon===-1){const dash2=title.indexOf(" - ");return dash2===-1?escapeHtml(title):'<span class="od-dash-title__composer">'+escapeHtml(title.slice(0,dash2))+"</span><br>"+escapeHtml(title.slice(dash2+3))}const composer=title.slice(0,colon),rest=title.slice(colon+2),dash=rest.indexOf(" - "),work=dash===-1?rest:rest.slice(0,dash),details=dash===-1?"":rest.slice(dash+3);return'<span class="od-dash-title__composer">'+escapeHtml(composer)+':</span> <em class="od-dash-title__work">'+escapeHtml(work)+"</em>
91"+(details?"<br>"+escapeHtml(details):"")}function coverHtml(item){return item.imageUrl?'<img src="'+escapeHtml(item.imageUrl)+'" alt="'+escapeHtml("Cover of "+item.title)+'">':'<span class="od-dash-cover__empty" aria-hidden="true">Opera Depot</span>'}function orderLine(item){const name=String(item.orderName||""),label=name?"Order "+(name.charAt(0)==="#"?name:"#"+name):"",date=item.purchaseDateDisplay?"Ordered on "+item.purchaseDateDisplay:"";return[label,date].filter(Boolean).join(" \xB7 ")}function topReviewerHtml(){return'<span class="od-top-reviewer"><span class="od-top-reviewer__diamond" role="img" aria-label="Diamond">&#128142;</span><span>Top Reviewer</span></span>'}function renderContribution(){const slot=state.root.querySelector("[data-od-dash-contribution]");if(!slot)return;const count=state.reviewCount;if(count<1){slot.hidden=!0;return}const top=count>25;slot.innerHTML='<div class="od-contribution" aria-label="'+count+" reviews shared"+(top?", Top Reviewer":"")+'"><strong class="od-contribution__number">'+count+'</strong><span class="od-contribution__label">reviews shared</span><span class="od-contribution__thanks">Thank you for contributing</span>'+(top?topReviewerHtml():"")+"</div>",slot.hidden=!1}function starFieldset(idPrefix,name,legend,extraClass,required){let inputs="";for(let i=1;i<=5;i++)inputs+='<input type="radio" id="'+idPrefix+"-"+i+'" name="'+name+'" value="'+i+'"'+(required?" required":"")+'><label for="'+idPrefix+"-"+i+'" aria-label="'+i+" star"+(i>1?"s":"")+'">\u2605</label>';return'<fieldset class="od-review-form__stars'+(extraClass?" "+extraClass:"")+'" data-od-star-input><legend>'+legend+"</legend>"+inputs+"</fieldset>"}const CHEVRON_LEFT='<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true" focusable="false"><path d="M15 5l-7 7 7 7" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>',CHEVRON_RIGHT='<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true" focusable="false"><path d="M9 5l7 7-7 7" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>';function shellHtml(customer,submitEndpoint){return'<div class="od-dash-left" data-od-dash-left><section class="od-dash-carousel" aria-roledescription="carousel" aria-label="Recordings awaiting your review"><div class="od-dash-frame" data-od-dash-frame><button type="button" class="od-dash-arrow od-dash-arrow--prev" data-od-dash-prev aria-label="Previous recording">'+CHEVRON_LEFT+'</button><div class="od-dash-peek od-dash-peek--prev2" data-od-dash-peek-prev2 aria-hidden="true"></div><div class="od-dash-peek od-dash-peek--prev" data-od-dash-peek-prev aria-hidden="true"></div><div class="od-dash-peek od-dash-peek--next2" data-od-dash-peek-next2 aria-hidden="true"></div><div class="od-dash-peek" data-od-dash-peek aria-hidden="true"></div><div class="od-dash-cover" data-od-dash-cover></div><button type="button" class="od-dash-arrow od-dash-arrow--next" data-od-dash-next aria-label="Next recording">'+CHEVRON_RIGHT+'</button></div></section><div class="od-dash-product" data-od-dash-product aria-live="polite"><p class="od-dash-title" data-od-dash-title></p><p class="od-dash-order" data-od-dash-order></p></div></div><section class="od-dash-form" data-od-reviews data-od-quiet-success data-product-handle="" data-submit-endpoint="'+escapeHtml(submitEndpoint)+'"><div class="od-dash-form-panel"><h2 class="od-review-form-panel__heading od-dash-form__heading" data-od-form-heading tabindex="-1">Share Your Experience</h2><p class="od-dash-form__sub">A star rating alone is welcome, and reviews may be written in any language.</p><form class="od-review-form" data-od-form novalidate><input type="hidden" name="name" value="'+escapeHtml(customer.displayName||customer.firstName)+'"><input type="hidden" name="email" value="'+escapeHtml(customer.email)+'">'+starFieldset("od-dash-rate","rating","Overall rating","od-dash-stars--overall",!0)+starFieldset("od-dash-sound","soundRating","Sound quality <em>(optional)</em>","od-review-form__stars--sound",!1)+'<label class="od-review-form__field"><span>Review title <em>(optional)</em></span><input type="text" name="title" maxlength="200"></label><label class="od-review-form__field"><span>Your review <em>(optional)</em></span><textarea name="body" rows="5" maxlength="6000"></textarea></label><p class="od-review-form__message" data-od-form-message hidden></p><div class="od-review-form__actions"><button type="submit" class="od-review-form__submit">Submit Review</button></div></form></div></section>'}function dialogHtml(){return'<div class="od-dash-overlay" data-od-dash-overlay hidden><div class="od-dash-dialog" role="dialog" aria-modal="true" aria-labelledby="od-dash-dialog-title"><h2 class="od-dash-dialog__heading" id="od-dash-dialog-title" data-od-dash-dialog-heading>Thank You for Sharing</h2><p class="od-dash-dialog__msg" data-od-dash-dialog-msg>Your review has been posted. Would you like to review another recording?</p><div class="od-dash-dialog__actions"><button type="button" class="od-review-form__submit od-dash-dialog__primary" data-od-dash-another>Review Another</button><button type="button" class="od-dash-dialog__secondary" data-od-dash-finish>I&rsquo;m Finished</button></div></div></div>'}function emptyHtml(){return'<div class="od-dash-empty"><h2 class="od-dash-empty__heading">You&rsquo;re All Caught Up</h2><p>Thank you for sharing your thoughts with the Opera Depot community.</p></div>'}
91function currentForm(){return state.root?state.root.querySelector("[data-od-form]"):null}function saveDraft(){const item=state.items[state.index],form=currentForm();if(!item||!form)return;const data=new FormData(form),draft={rating:data.get("rating")||"",soundRating:data.get("soundRating")||"",title:String(data.get("title")||""),body:String(data.get("body")||"")};draft.rating||draft.soundRating||draft.title.trim()||draft.body.trim()?state.drafts[item.handle]=draft:delete state.drafts[item.handle]}function applyStarFill(form){form.querySelectorAll("[data-od-star-input]").forEach(field=>{const inputs=Array.from(field.querySelectorAll("input")),checkedIndex=inputs.findIndex(input=>input.checked);inputs.forEach((input,i)=>{const label=field.querySelector('label[for="'+input.id+'"]');label&&label.classList.toggle("is-filled",checkedIndex>-1&&i<=checkedIndex)})})}function restoreForm(handle){const form=currentForm();if(!form)return;form.reset();const message=form.querySelector("[data-od-form-message]");message&&(message.hidden=!0);const draft=state.drafts[handle];if(draft){["rating","soundRating"].forEach(name=>{if(!draft[name])return;const input=form.querySelector('input[name="'+name+'"][value="'+draft[name]+'"]');input&&(input.checked=!0)});const titleInput=form.elements.namedItem("title"),bodyInput=form.elements.namedItem("body");titleInput&&(titleInput.value=draft.title),bodyInput&&(bodyInput.value=draft.body)}applyStarFill(form)}function lockInfoHeight(){const root=state.root;if(!root||!document.contains(root))return;const info=root.querySelector("[data-od-dash-product]");if(!info)return;if(!state.items.length){info.style.minHeight="";return}const probe=document.createElement("div");probe.className=info.className,probe.style.cssText="position:absolute;left:0;visibility:hidden;pointer-events:none;min-height:0;width:"+info.getBoundingClientRect().width+"px;",info.parentElement.appendChild(probe);let max=0;state.items.forEach(item=>{probe.innerHTML='<p class="od-dash-title">'+titleHtml(item.title)+'</p><p class="od-dash-order">'+escapeHtml(orderLine(item))+"</p>",max=Math.max(max,probe.offsetHeight)}),probe.remove(),info.style.minHeight=max+"px"}let infoResizeTimer=null;window.addEventListener("resize",()=>{clearTimeout(infoResizeTimer),infoResizeTimer=setTimeout(lockInfoHeight,150)});function renderCurrent(){const root=state.root,item=state.items[state.index];if(!item)return;root.querySelector("[data-od-dash-cover]").innerHTML=coverHtml(item);const fillPeek=(sel,peekItem)=>{const el=root.querySelector(sel);el&&(peekItem?(el.innerHTML=coverHtml(peekItem),el.hidden=!1):(el.innerHTML="",el.hidden=!0))};fillPeek("[data-od-dash-peek]",state.items[state.index+1]),fillPeek("[data-od-dash-peek-next2]",state.items[state.index+2]),fillPeek("[data-od-dash-peek-prev]",state.items[state.index-1]),fillPeek("[data-od-dash-peek-prev2]",state.items[state.index-2]),root.querySelector("[data-od-dash-title]").innerHTML=titleHtml(item.title),root.querySelector("[data-od-dash-order]").textContent=orderLine(item);const formRoot=root.querySelector("[data-od-reviews]");formRoot&&(formRoot.dataset.productHandle=item.handle);const prevBtn=root.querySelector("[data-od-dash-prev]"),nextBtn=root.querySelector("[data-od-dash-next]");prevBtn&&(prevBtn.hidden=state.index===0),nextBtn&&(nextBtn.hidden=state.index>=state.items.length-1);const prevItem=state.items[state.index-1];if(prevItem&&prevItem.imageUrl){const img=new Image;img.src=prevItem.imageUrl}}function goTo(newIndex,dir){if(state.animating||newIndex<0||newIndex>=state.items.length||newIndex===state.index)return;saveDraft();const root=state.root,cover=root.querySelector("[data-od-dash-cover]"),info=root.querySelector("[data-od-dash-product]"),finishSwap=()=>{state.index=newIndex,renderCurrent(),restoreForm(state.items[newIndex].handle)};if(reducedMotion()){finishSwap();return}state.animating=!0;const sceneEls=()=>[cover,info].concat(Array.from(root.querySelectorAll(".od-dash-peek > *"))),out=dir>0?"is-exit-left":"is-exit-right",inn=dir>0?"is-enter-right":"is-enter-left",outgoing=sceneEls();outgoing.forEach(el=>el.classList.add(out)),setTimeout(()=>{state.animating=!1},500),setTimeout(()=>{finishSwap(),outgoing.forEach(el=>el.classList.remove(out));const incoming=sceneEls();incoming.forEach(el=>el.classList.add(inn)),requestAnimationFrame(()=>requestAnimationFrame(()=>{incoming.forEach(el=>el.classList.add("is-enter-active")),setTimeout(()=>{incoming.forEach(el=>el.classList.remove(inn,"is-enter-active"))},270)}))},200)}function bindSwipe(frame){let startX=0,startY=0,tracking=!1;frame.addEventListener("touchstart",evt=>{if(evt.touches.length!==1){tracking=!1;return}tracking=!0,startX=evt.touches[0].clientX,startY=evt.touches[0].clientY},{passive:!0}),frame.addEventListener("touchend",evt=>{if(!tracking)return;tracking=!1;const touch=evt.changedTouches[0],dx=touch.clientX-startX,dy=touch.clientY-startY;Math.abs(dx)<SWIPE_MIN_PX||Math.abs(dx)<Math.abs(dy)*1.2||(dx<0?goTo(state.index+1,1):goTo(state.index-1,-1))},{passive:!0})}function overlayEl(){return document.querySelector("[data-od-dash-overlay]")}function confettiBurst(overlay){if(reducedMotion())return;const canvas=document.createElement("canvas");canvas.className="od-dash-confetti",canvas.setAttribute("aria-hidden","true"),overlay.appendChild(canvas),canvas.width=window.innerWidth,canvas.height=window.innerHeight;const ctx=canvas.getContext("2d"),colors=["#c59625","#f4ad17","#330065","#7a5ba8","#e8d9ef","#d9c591"],pieces=Array.from({length:150},()=>({x:Math.random()*canvas.width,y:-30-Math.random()*canvas.height*.6,w:
915+Math.random()*6,h:8+Math.random()*8,vx:-1.4+Math.random()*2.8,vy:2.2+Math.random()*3.2,rot:Math.random()*Math.PI,vr:-.14+Math.random()*.28,color:colors[Math.floor(Math.random()*colors.length)]})),started=performance.now(),DURATION=3800,tick=now=>{if(!canvas.isConnected)return;const elapsed=now-started;ctx.clearRect(0,0,canvas.width,canvas.height),ctx.globalAlpha=elapsed>DURATION-700?Math.max(0,(DURATION-elapsed)/700):1,pieces.forEach(piece=>{piece.x+=piece.vx,piece.y+=piece.vy,piece.rot+=piece.vr,ctx.save(),ctx.translate(piece.x,piece.y),ctx.rotate(piece.rot),ctx.fillStyle=piece.color,ctx.fillRect(-piece.w/2,-piece.h/2,piece.w,piece.h),ctx.restore()}),elapsed<DURATION?requestAnimationFrame(tick):canvas.remove()};requestAnimationFrame(tick)}function openDialog(messageText,options){const overlay=overlayEl();if(!overlay)return;const celebrate=!!(options&&options.celebrate),dialog=overlay.querySelector(".od-dash-dialog"),heading=overlay.querySelector("[data-od-dash-dialog-heading]");dialog.classList.toggle("od-dash-dialog--celebrate",celebrate),heading.innerHTML=celebrate?'<span class="od-dash-dialog__gem" aria-hidden="true">&#128142;</span>You&rsquo;re a Top Reviewer!':"Thank You for Sharing",overlay.querySelector("[data-od-dash-dialog-msg]").textContent=messageText;const another=overlay.querySelector("[data-od-dash-another]");another.hidden=state.items.length===0,state.lastFocus=document.activeElement,overlay.hidden=!1,reducedMotion()?overlay.classList.add("is-open"):requestAnimationFrame(()=>requestAnimationFrame(()=>overlay.classList.add("is-open"))),celebrate&&confettiBurst(overlay),(another.hidden?overlay.querySelector("[data-od-dash-finish]"):another).focus()}function closeDialog(focusTarget){const overlay=overlayEl();if(!overlay||overlay.hidden)return;overlay.classList.remove("is-open");const confetti=overlay.querySelector(".od-dash-confetti");confetti&&confetti.remove(),reducedMotion()?overlay.hidden=!0:setTimeout(()=>{overlay.hidden=!0},220);const target=focusTarget||state.lastFocus;target&&document.contains(target)&&typeof target.focus=="function"&&target.focus({preventScroll:!0}),state.lastFocus=null}function renderEmpty(){const list=state.root.querySelector("[data-od-dashboard-list]");list.innerHTML=emptyHtml()}function historyStars(rating,cls){return'<span class="'+cls+'" aria-label="'+rating+' out of 5 stars">'+"\u2605".repeat(rating)+"\u2606".repeat(5-rating)+"</span>"}function updateEndpoint(){const base=(state.root.dataset.endpoint||"/apps/library/review-dashboard").replace("review-dashboard","review-update"),token=new URLSearchParams(location.search).get("token");return base+(token?"?token="+encodeURIComponent(token):"")}function historyCardHtml(review,index){const date=review.createdAt?escapeHtml(String(review.createdAt).slice(0,10)):"",pending=review.status==="pending"?'<span class="od-hist__pending" title="Visible once approved">Awaiting approval</span>':"",sound=review.soundRating?'<span class="od-hist__sound">Sound quality '+historyStars(review.soundRating,"od-hist__stars od-hist__stars--sound")+"</span>":"";return'<article class="od-hist" data-od-hist-card data-index="'+index+'"><p class="od-hist__product">'+titleHtml(review.productTitle)+'</p><p class="od-hist__meta">'+historyStars(review.rating,"od-hist__stars")+sound+(date?'<span class="od-hist__date">'+date+"</span>":"")+pending+"</p>"+(review.title?'<h3 class="od-hist__title">'+escapeHtml(review.title)+"</h3>":"")+(review.body?'<p class="od-hist__body">'+escapeHtml(review.body)+"</p>":"")+(review.id?'<p class="od-hist__actions"><button type="button" class="od-hist__edit" data-od-hist-edit>Edit</button></p>':"")+"</article>"}function historyEditHtml(review,index){const idBase="od-hist-"+index,starInputs=(name,legend,extraClass,selected)=>{let inputs="";for(let i=1;i<=5;i++)inputs+='<input type="radio" id="'+idBase+"-"+name+"-"+i+'" name="'+name+'" value="'+i+'"'+(selected===i?" checked":"")+'><label for="'+idBase+"-"+name+"-"+i+'" aria-label="'+i+" star"+(i>1?"s":"")+'"'+(selected!==null&&i<=selected?' class="is-filled"':"")+">\u2605</label>";return'<fieldset class="od-review-form__stars'+(extraClass?" "+extraClass:"")+'" data-od-star-input><legend>'+legend+"</legend>"+inputs+"</fieldset>"};return'<article class="od-hist od-hist--editing" data-od-hist-card data-index="'+index+'"><p class="od-hist__product">'+titleHtml(review.productTitle)+'</p><div class="od-review-form od-hist__form">'+starInputs("rating","Overall rating","od-dash-stars--overall",review.rating)+starInputs("soundRating","Sound quality <em>(optional)</em>","od-review-form__stars--sound",review.soundRating||null)+'<label class="od-review-form__field"><span>Review title <em>(optional)</em></span><input type="text" name="title" maxlength="200" value="'+escapeHtml(review.title||"")+'"></label><label class="od-review-form__field"><span>Your review <em>(optional)</em></span><textarea name="body" rows="5" maxlength="6000">'+escapeHtml(review.body||"")+'</textarea></label><p class="od-review-form__message" data-od-hist-message hidden></p><div class="od-hist__edit-actions"><button type="button" class="od-review-form__submit" data-od-hist-save>Save</button><button type="button" class="od-hist__cancel" data-od-hist-cancel>Cancel</button><button type="button" class="od-hist__delete" data-od-hist-delete><svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
91<line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>Delete</button></div></div></article>'}function renderPreviousReviews(){const root=state.root;if(!root)return;const box=root.querySelector("[data-od-dash-previous]");if(!box)return;if(!state.myReviews.length){box.hidden=!0;return}const cards=state.myReviews.slice(0,state.historyShown).map((review,i)=>state.editingIndex===i?historyEditHtml(review,i):historyCardHtml(review,i)).join(""),more=state.myReviews.length>state.historyShown?'<div class="od-reviews__more-wrapper"><button type="button" class="button button--outline-secondary od-reviews__more" data-od-hist-more>Load more reviews</button></div>':"";box.hidden=!1,box.innerHTML='<h2 class="od-dash-previous__heading">Previous Reviews</h2><p class="od-dash-previous__sub">Everything you\u2019ve shared, newest first.</p>'+cards+more}async function saveHistoryEdit(card){const index=Number(card.dataset.index),review=state.myReviews[index];if(!review)return;const message=card.querySelector("[data-od-hist-message]"),showMessage=(text,kind)=>{message.textContent=text,message.hidden=!1,message.className="od-review-form__message od-review-form__message--"+kind},rating=card.querySelector('input[name="rating"]:checked');if(!rating){showMessage("Please choose an overall rating.","error");return}const sound=card.querySelector('input[name="soundRating"]:checked'),title=card.querySelector('input[name="title"]').value.trim(),body=card.querySelector('textarea[name="body"]').value.trim(),saveBtn=card.querySelector("[data-od-hist-save]");saveBtn.disabled=!0,saveBtn.textContent="Saving\u2026";try{const result=await(await fetch(updateEndpoint(),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({reviewId:review.id,rating:Number(rating.value),soundRating:sound?Number(sound.value):null,title,body})})).json().catch(()=>({}));result.ok?(state.myReviews[index]={...review,rating:Number(rating.value),soundRating:sound?Number(sound.value):null,title,body,status:result.status},state.editingIndex=null,renderPreviousReviews()):(showMessage(result.message||"Something went wrong \u2014 please try again.","error"),saveBtn.disabled=!1,saveBtn.textContent="Save")}catch{showMessage("Could not reach the server \u2014 please try again.","error"),saveBtn.disabled=!1,saveBtn.textContent="Save"}}async function deleteHistoryReview(card){const index=Number(card.dataset.index),review=state.myReviews[index];if(!review||!review.id||!window.confirm("Delete this review permanently? This cannot be undone."))return;const message=card.querySelector("[data-od-hist-message]"),deleteBtn=card.querySelector("[data-od-hist-delete]");deleteBtn.disabled=!0,deleteBtn.textContent="Deleting\u2026";try{const result=await(await fetch(updateEndpoint(),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({reviewId:review.id,delete:!0})})).json().catch(()=>({}));result.ok?(state.myReviews.splice(index,1),state.editingIndex=null,state.reviewCount=Math.max(0,state.reviewCount-1),renderContribution(),renderPreviousReviews()):(message.textContent=result.message||"Something went wrong \u2014 please try again.",message.hidden=!1,message.className="od-review-form__message od-review-form__message--error",deleteBtn.disabled=!1,deleteBtn.textContent="Delete")}catch{message.textContent="Could not reach the server \u2014 please try again.",message.hidden=!1,message.className="od-review-form__message od-review-form__message--error",deleteBtn.disabled=!1,deleteBtn.textContent="Delete"}}async function loadDashboard(root){const status=root.querySelector("[data-od-dashboard-status]"),list=root.querySelector("[data-od-dashboard-list]"),token=new URLSearchParams(location.search).get("token"),endpoint=root.dataset.endpoint+(token?"?token="+encodeURIComponent(token):"");let data;try{const res=await fetch(endpoint,{headers:{Accept:"application/json"},credentials:"same-origin"});if(data=await res.json(),res.status===401||data.ok===!1){status.innerHTML='Please <a href="/account/login?return_url=/pages/review-dashboard">sign in</a> to see the recordings awaiting your review \u2014 or use the link from your review email.';return}}catch{status.textContent="We could not load your recordings \u2014 please try again shortly.";return}if(state.root=root,state.items=data.toReview||[],state.customer=data.customer,state.index=0,state.reviewCount=Number(data.reviewCount)||0,state.myReviews=Array.isArray(data.myReviews)?data.myReviews:[],state.historyShown=10,state.editingIndex=null,state.drafts={},status.hidden=!0,renderContribution(),root.querySelector("[data-od-dash-previous]")||list.insertAdjacentHTML("afterend",'<section class="od-dash-previous" data-od-dash-previous hidden aria-label="Previous reviews"></section>'),renderPreviousReviews(),!state.items.length){list.innerHTML=emptyHtml(),list.hidden=!1;return}list.innerHTML=shellHtml(data.customer,root.dataset.submitEndpoint),list.hidden=!1,renderCurrent(),lockInfoHeight(),bindSwipe(root.querySelector("[data-od-dash-frame]")),overlayEl()||document.body.insertAdjacentHTML("beforeend",dialogHtml());const overlay=overlayEl();overlay.dataset.odBound!=="1"&&(overlay.dataset.odBound="1",overlay.addEventListener("keydown",evt=>{if(evt.key==="Escape"){evt.preventDefault(),closeDialog(state.root&&state.root.querySelector(".od-dashboard__heading"));return}if(evt.key!=="Tab")return;const focusables=Array.from(overlay.querySelectorAll("button:not([hidden])"));if(!focusables.length)return;const first=focusables[0],last=focusables[focusables.length-1];evt.shiftKey&&document.activeElement===first?(evt.preventDefault(),last.focus()):!evt.shiftKey&&document.activeElement===last&&(evt.preventDefault(),first.focus())}))}document.addEventListener("od:review-submitted",evt=>{const root=state.root;if(!root||!document.contains(root)||!root.contains(evt.target))return;const item=state.items[state.index];if(!item||evt.detail.productHandle!==item.handle)return;const wasTopReviewer=state.reviewCount>25;state.reviewCount+=1,state.myReviews.unshift({id:evt.detail.reviewId||"",productTitle:item.title,productHandle:item.handle,rating:evt.detail.rating||0,soundRating:evt.detail.soundRating||null,title:evt.detail.title||"",body:evt.detail.body||"",createdAt:new Date().toISOString().slice(0,10),status:evt.detail.status}),state.editingIndex=state.editingIndex===null?null:state.editingIndex+1,renderPreviousReviews();const becameTopReviewer=state.reviewCount>25&&!wasTopReviewer;renderContribution(),delete state.drafts[item.handle],state.items.splice(state.index,1),state.items.length?(state.index>=state.items.length&&(state.index=state.items.length-1),renderCurrent(),lockInfoHeight(),restoreForm(state.items[state.index].handle)):renderEmpty(),becameTopReviewer?openDialog("That review earned you the Top Reviewer diamond \u2014 it now appears beside your name across Opera Depot. Thank y
91ou for sharing your expertise with fellow opera lovers. Care to keep going?",{celebrate:!0}):openDialog(evt.detail.status==="published"?"Your review has been posted. Would you like to review another recording?":"Your review has been received and will appear after a quick approval. Would you like to review another recording?")}),document.addEventListener("click",evt=>{const root=state.root;if(evt.target.closest("[data-od-dash-another]")){closeDialog(root&&root.querySelector("[data-od-form-heading]"));const band=root&&root.querySelector("[data-od-dash-frame]");band&&band.scrollIntoView({behavior:reducedMotion()?"auto":"smooth",block:"start"});return}if(evt.target.closest("[data-od-dash-finish]")){closeDialog(root&&root.querySelector(".od-dashboard__heading"));return}!root||!root.contains(evt.target)||(evt.target.closest("[data-od-dash-prev]")?goTo(state.index-1,-1):evt.target.closest("[data-od-dash-next]")?goTo(state.index+1,1):evt.target.closest("[data-od-hist-edit]")?(state.editingIndex=Number(evt.target.closest("[data-od-hist-card]").dataset.index),renderPreviousReviews()):evt.target.closest("[data-od-hist-cancel]")?(state.editingIndex=null,renderPreviousReviews()):evt.target.closest("[data-od-hist-save]")?saveHistoryEdit(evt.target.closest("[data-od-hist-card]")):evt.target.closest("[data-od-hist-delete]")?deleteHistoryReview(evt.target.closest("[data-od-hist-card]")):evt.target.closest("[data-od-hist-more]")&&(state.historyShown+=10,renderPreviousReviews()))});const loadingRoots=new WeakSet;function initDashboard(){const root=document.querySelector("[data-od-review-dashboard]");if(!root)return!1;if(loadingRoots.has(root))return!0;const list=root.querySelector("[data-od-dashboard-list]"),looksLoaded=list&&!list.hidden&&list.childElementCount>0;return boundRoots.has(root)&&looksLoaded||(boundRoots.add(root),loadingRoots.add(root),loadDashboard(root).finally(()=>loadingRoots.delete(root))),!0}function initWithRetries(){let tries=0;const tick=()=>{tries+=1,!initDashboard()&&tries<RETRY_MAX_TRIES&&setTimeout(tick,RETRY_EVERY_MS)};tick()}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",initWithRetries,{once:!0}):initWithRetries(),["shopify:page:load","shopify:section:load","od:after-swap","od:main-content-replaced"].forEach(eventName=>{document.addEventListener(eventName,()=>setTimeout(initWithRetries,0))}),window.addEventListener("pushstate",()=>setTimeout(initWithRetries,0)),window.addEventListener("popstate",()=>setTimeout(initWithRetries,0))})();
92//# sourceMappingURL=/cdn/shop/t/188/assets/app.js.map?v=29719832494942380221790943631

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.