PageSourceSearch

https://diptyqueparis.com/cdn/shop/t/91/compiled_assets/snippet-scripts.js?v=18972120271862874511790771807

js diptyqueparis.com collected 2026-10-01 10:28:26 UTC 195,325 bytes, 29 lines download raw bytes

1(function(){var __snippets__={};(function(){for(var element=document.getElementById("snippets-script"),attribute=element?element.getAttribute("data-snippets"):"",snippets=attribute.split(",").filter(Boolean),i=0;i<snippets.length;i++)__snippets__[snippets[i]]=!0})(),(function(){if(!(!__snippets__["audio-player"]&&!Shopify.designMode))try{(()=>{var AudioPlayer=class extends HTMLElement{constructor(){super(),this.audio=null,this.syncVideo=!1,this.isAudioPlaying=!1,this.videos=[],this.section=null,this.playBtn=null,this.iconPlay=null,this.iconPause=null,this.waveform=null,this.timeEl=null,this.durationEl=null,this.boundTimeUpdate=this.onTimeUpdate.bind(this),this.boundEnded=this.onEnded.bind(this),this.boundLoaded=this.onLoaded.bind(this),this.boundTogglePlay=()=>{this.togglePlay()}}connectedCallback(){if(this.syncVideo=this.getAttribute("data-sync-video")==="true",this.syncVideo){this.section=this.closest("[data-section-id]")??this.closest("section");const allVideos=this.getSyncVideos();if(allVideos.length===0){console.warn("[c-audio-player] sync_video enabled but no c-container-video foun
1d in section.");return}this.audio=this.getActiveSyncVideo()??allVideos[0],this.videos=allVideos.filter(video=>video!==this.audio),allVideos.forEach(video=>{video.muted=!0,video.playsInline=!0,video.setAttribute("playsinline","")}),this.section&&this.section.querySelectorAll("c-container-video [data-mute-btn]").forEach(btn=>btn.setAttribute("hidden",""))}else{const src=this.getAttribute("data-src");if(!src){console.warn("[c-audio-player] No data-src attribute found.");return}this.audio=new Audio(src),this.audio.loop=this.getAttribute("data-loop")==="true",this.audio.preload="metadata"}this.playBtn=this.querySelector("[data-play-btn]"),this.iconPlay=this.querySelector("[data-icon-play]"),this.iconPause=this.querySelector("[data-icon-pause]"),this.waveform=this.querySelector("[data-waveform]"),this.timeEl=this.querySelector("[data-time]"),this.durationEl=this.querySelector("[data-duration]"),this.playBtn?.addEventListener("click",this.boundTogglePlay),this.waveform?.addEventListener("click",e=>this.seek(e)),this.bindMediaEvents(this.audio)}disconnectedCallback(){this.syncVideo&&this.audio?this.audio.muted=!0:this.audio?.pause(),this.unbindMediaEvents(this.audio),this.playBtn?.removeEventListener("click",this.boundTogglePlay),this.audio=null,this.isAudioPlaying=!1,this.videos=[],this.section=null}async togglePlay(){if(this.audio)if(this.syncVideo){const video=this.getActiveSyncVideo();if(!video)return;if(this.setActiveMedia(video),this.isAudioPlaying)video.muted=!0,this.isAudioPlaying=!1,this.setPlaying(!1),this.waveform&&(this.waveform.style.setProperty("--progress","0%"),this.waveform.setAttribute("aria-valuenow","0")),this.timeEl&&(this.timeEl.textContent="00:00");else{if(video.currentTime=0,video.muted=!1,video.playsInline=!0,this.videosSync(0),!await this.playMedia(video)){video.muted=!0,this.isAudioPlaying=!1,this.setPlaying(!1);return}this.isAudioPlaying=!0,this.setPlaying(!0)}}else this.audio.paused?await this.playMedia(this.audio)&&this.setPlaying(!0):(this.audio.pause(),this.setPlaying(!1))}setPlaying(playing){playing?(this.iconPlay?.setAttribute("hidden",""),this.iconPause?.removeAttribute("hidden"),this.setAttribute("playing",""),this.playBtn&&this.playBtn.setAttribute("aria-label","Pause")):(this.iconPause?.setAttribute("hidden",""),this.iconPlay?.removeAttribute("hidden"),this.removeAttribute("playing"),this.playBtn&&this.playBtn.setAttribute("aria-label","Play"))}onLoaded(){this.durationEl&&this.audio&&(this.durationEl.textContent=this.formatTime(this.audio.duration))}onTimeUpdate(){if(this.syncVideo&&!this.isAudioPlaying||!this.audio?.duration)return;const progress=this.audio.currentTime/this.audio.duration;this.waveform&&(this.waveform.style.setProperty("--progress",`${progress*100}%`),this.waveform.setAttribute("aria-valuenow",String(Math.round(progress*100)))),this.timeEl&&(this.timeEl.textContent=this.formatTime(this.audio.currentTime))}onEnded(){this.setPlaying(!1),this.videos.forEach(v=>v.pause()),this.videosSync(0),this.waveform&&(this.waveform.style.setProperty("--progress","0%"),this.waveform.setAttribute("aria-valuenow","0")),this.timeEl&&(this.timeEl.textContent="00:00")}bindMediaEvents(media){media?.addEventListener("timeupdate",this.boundTimeUpdate),media?.addEventListener("ended",this.boundEnded),media?.addEventListener("loadedmetadata",this.boundLoaded)}unbindMediaEvents(media){media?.removeEventListener("timeupdate",this.boundTimeUpdate),media?.removeEventListener("ended",this.boundEnded),media?.removeEventListener("loadedmetadata",this.boundLoaded)}setActiveMedia(video){this.audio!==video&&(this.unbindMediaEvents(this.audio),this.audio=video,this.bindMediaEvents(this.audio),this.videos=this.getSyncVideos().filter(item=>item!==video))}getSyncVideos(){return this.section?Array.from(this.section.querySelectorAll("c-container-video video")):[]}getActiveSyncVideo(){const videos=this.getSyncVideos();return videos.length===0?null:videos.find(video=>{const wrapper=video.parentElement;return wrapper?window.getComputedStyle(wrapper).display!=="none":!1})??videos[0]}async playMedia(media){try{return media instanceof HTMLVideoElement&&(media.playsInl
1ine=!0,media.setAttribute("playsinline","")),media.networkState===media.NETWORK_EMPTY&&media.load(),await media.play(),!0}catch(error){return console.warn("[c-audio-player] Media play prevented.",error),!1}}seek(e){if(!this.audio?.duration||!this.waveform||this.syncVideo&&!this.isAudioPlaying)return;const rect=this.waveform.getBoundingClientRect(),ratio=Math.max(0,Math.min(1,(e.clientX-rect.left)/rect.width));this.audio.currentTime=ratio*this.audio.duration,this.waveform.style.setProperty("--progress",`${ratio*100}%`),this.videosSync(ratio*this.audio.duration)}formatTime(secs){const m=Math.floor(secs/60).toString().padStart(2,"0"),s=Math.floor(secs%60).toString().padStart(2,"0");return`${m}:${s}`}videosSync(time){this.videos.forEach(v=>{v.currentTime=time})}};window.customElements.get("c-audio-player")||window.customElements.define("c-audio-player",AudioPlayer)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["booxi-countdown"]&&!Shopify.designMode))try{(()=>{var RELOAD_DELAY=500,SETTINGS_POLL_MS=250,SETTINGS_MAX_ATTEMPTS=24,reloadTimer=null;function scheduleReload(){reloadTimer===null&&(reloadTimer=window.setTimeout(()=>window.location.reload(),RELOAD_DELAY))}function holdMinutes(){const value=window.booxiApp?.settings?.timer_remove_product;return typeof value=="number"&&value>0?value:null}function formatRemaining(ms){const total=Math.ceil(ms/1e3),minutes=Math.floor(total/60),seconds=total%60;return`${minutes}:${String(seconds).padStart(2,"0")}`}var BooxiCountdown=class extends HTMLElement{constructor(){super(...arguments),this.ticker=null,this.waiter=null,this.expiring=!1,this.lastText=null}connectedCallback(){this.waitForSettings()}disconnectedCallback(){this.stop()}waitForSettings(attempt=0){if(holdMinutes()!==null){this.start();return}attempt>=SETTINGS_MAX_ATTEMPTS||(this.waiter=window.setTimeout(()=>this.waitForSettings(attempt+1),SETTINGS_POLL_MS))}start(){this.tick(),this.ticker=window.setInterval(()=>this.tick(),1e3)}stop(){this.ticker!==null&&window.clearInterval(this.ticker),this.waiter!==null&&window.clearTimeout(this.waiter),this.ticker=null,this.waiter=null}deadline(){const minutes=holdMinutes(),stamp=Number(this.dataset.timestamp);return minutes===null||!Number.isFinite(stamp)||stamp<=0?null:stamp+minutes*6e4}tick(){const deadline=this.deadline();if(deadline===null)return;const remaining=deadline-Date.now();if(remaining>0){const template=this.dataset.template||"__TIME__";this.render(template.replace("__TIME__",formatRemaining(remaining)));return}this.render(this.dataset.expired||""),this.stop(),this.expire()}render(text){if(text!==this.lastText){const slot=this.querySelector("[data-booxi-countdown-text]")??this;slot.textContent=text,this.lastText=text}this.hidden&&(this.hidden=!1)}async expire(){if(this.expiring)return;this.expiring=!0;const key=this.dataset.lineKey;if(key){const root=window.Shopify?.routes?.root||"/";try{await fetch(`${root}cart/change.js`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:key,quantity:0})})}catch{}}scheduleReload()}};window.customElements.get("c-booxi-countdown")||window.customElements.define("c-booxi-countdown",BooxiCountdown)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["calendar-button"]&&!Shopify.designMode))try{(()=>{var PRODID="-//Diptyque//Calendar Event//FR",UID_DOMAIN="diptyqueparis.com",FOLD_LIMIT=75,encoder=new TextEncoder;function escapeText(value){return value.replace(/\\/g,"\\\\").replace(/[;,]/g,"\\$&").replace(/\r\n|\r|\n/g,"\\n")}function foldLine(line){if(encoder.encode(line).length<=FOLD_LIMIT)return line;const parts=[];let chunk="",bytes=0,limit=FOLD_LIMIT;for(const char of line){const size=encoder.encode(char).length;bytes+size>limit&&(parts.push(chunk),chunk="",bytes=0,limit=FOLD_LIMIT-1),chunk+=char,bytes+=size}return parts.push(chunk),parts.join(`\r
2 `)}function toUtcStamp(epochSeconds){return new Date(epochSeconds*1e3).toISOString().replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z")}function slugify(value){return value.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-+|-+$/g,"").toLowerCase()}var CalendarButton=class extends HTMLElement{constructor(){super(...arguments),this.handleClick=event=>{event.target?.closest("button")&&this.download()}}connectedCallback(){this.addEventListener("click",this.handleClick)}timestamp(raw){if(!raw)return null;const value=Number(raw);return Number.isFinite(value)?value:null}download(){const start=this.timestamp(this.dataset.startTs),end=this.timestamp(this.dataset.endTs);if(start===null||end===null){console.error("c-calendar-button: data-start-ts / data-end-ts must be epoch seconds");return}const title=this.dataset.title||"",slug=slugify(title)||"evenement",startStamp=toUtcStamp(start),lines=["BEGIN:VCALENDAR","VERSION:2.0",`PRODID:${PRODID}`,"CALSCALE:GREGORIAN","METHOD:PUBLISH","BEGIN:VEVENT",`UID:${startStamp}-${slug}@${UID_DOMAIN}`,`DTSTAMP:${toUtcStamp(Date.now()/1e3)}`,`DTSTART:${startStamp}`,`DTEND:${toUtcStamp(end)}
2`,`SUMMARY:${escapeText(title)}`,`DESCRIPTION:${escapeText(this.dataset.description||"")}`,`LOCATION:${escapeText(this.dataset.location||"")}`,"STATUS:CONFIRMED","SEQUENCE:0","BEGIN:VALARM","TRIGGER:-PT15M","ACTION:DISPLAY","DESCRIPTION:Reminder","END:VALARM","END:VEVENT","END:VCALENDAR"],blob=new Blob([lines.map(foldLine).join(`\r
3`)],{type:"text/calendar;charset=utf-8"}),url=window.URL.createObjectURL(blob),link=document.createElement("a");link.href=url,link.setAttribute("download",`${slug}.ics`),document.body.appendChild(link),link.click(),document.body.removeChild(link),window.URL.revokeObjectURL(url)}};function defineCalendarButton(){window.customElements.get("c-calendar-button")||window.customElements.define("c-calendar-button",CalendarButton)}defineCalendarButton()})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["cart-item-quantity"]&&!Shopify.designMode))try{(()=>{var ERROR_MESSAGE_SELECTOR="[data-cart-limit-error-message]",ERROR_TEXT_SELECTOR="[data-cart-limit-error-text]",OPEN_ENGRAVING_PANEL_SELECTOR="c-engraving-panel.is-open",SEARCH_DIALOG_SELECTOR="dialog[data-search-dialog]",QUANTITY_LIMIT_PATTERNS=[/can'?t add more/i,/maximum allowed quantity/i,/maximum quantity/i,/quantity.*exceeded/i,/only add \d+/i];function getErrorMessageEl(){return document.querySelector(ERROR_MESSAGE_SELECTOR)}function getDefaultMessage(){return window.cartStrings?.addToCartLimitError??"The maximum allowed quantity for this product has been exceeded."}function isCartQuantityLimitError(status,description){if(status!==422)return!1;const normalized=description.trim();return normalized.length===0?!0:QUANTITY_LIMIT_PATTERNS.some(pattern=>pattern.test(normalized))}function closeOpenEngravingPanels(){document.querySelectorAll(OPEN_ENGRAVING_PANEL_SELECTOR).forEach(panel=>{panel.close()})}function closeHeaderSearchIfOpen(){const openDialogs=document.querySelectorAll(`${SEARCH_DIALOG_SELECTOR}[open]`);openDialogs.length!==0&&(document.documentElement.classList.remove("is-overflow-hidden"),openDialogs.forEac
3h(dialog=>{dialog.close()}))}function showCartLimitError(message){closeHeaderSearchIfOpen();const errorMessage=getErrorMessageEl();if(!errorMessage)return;const textEl=errorMessage.querySelector(ERROR_TEXT_SELECTOR);textEl&&(textEl.textContent=message??getDefaultMessage()),errorMessage.classList.remove("hidden"),errorMessage.removeAttribute("hidden"),errorMessage.setAttribute("aria-hidden","false"),closeOpenEngravingPanels(),window.scrollTo(0,0)}function hideCartLimitError(){const errorMessage=getErrorMessageEl();if(!errorMessage)return;const textEl=errorMessage.querySelector(ERROR_TEXT_SELECTOR);textEl&&(textEl.textContent=""),errorMessage.classList.add("hidden"),errorMessage.setAttribute("hidden",""),errorMessage.setAttribute("aria-hidden","true")}var CART_A11Y_PENDING_KEY="cart-a11y-announce";function queueCartStatusForReload(message){const trimmed=message.trim();if(trimmed)try{sessionStorage.setItem(CART_A11Y_PENDING_KEY,trimmed)}catch{}}function fillCartStatusTemplate(template,values){let result=template;return values.title!==void 0&&(result=result.replace(/__TITLE__/g,values.title)),values.quantity!==void 0&&(result=result.replace(/__QUANTITY__/g,String(values.quantity))),result}var CartItemQuantity=class extends HTMLElement{constructor(){super(),this.input=this.querySelector('input[type="number"]'),this.minusButton=this.querySelector('[data-action="minus"]'),this.plusButton=this.querySelector('[data-action="plus"]'),this.allSample=[...document.querySelectorAll("[data-parent-id]")],this.varaintId=this.dataset.variantId,this.urlChange=this.dataset.url,this.lineIndex=this.getAttribute("data-line"),this.originalQuantity=parseInt(this.getAttribute("data-original-quantity")||this.input.value,10),this.maxQuantity=parseInt(this.input.getAttribute("max")||"0",10),this.init()}init(){this.bindEvents(),this.setOriginalQuantity(),this.updateButtonStates()}bindEvents(){this.minusButton&&this.minusButton.addEventListener("click",this.handleMinus.bind(this)),this.plusButton&&this.plusButton.addEventListener("click",this.handlePlus.bind(this)),this.input.addEventListener("blur",this.handleBlur.bind(this)),this.input.addEventListener("keypress",this.handleKeypress.bind(this)),this.input.addEventListener("keydown",this.handleKeydown.bind(this)),this.input.addEventListener("input",this.handleInput.bind(this))}syncErrorVisibility(quantity){if(this.maxQuantity>0&&quantity>this.maxQuantity){showCartLimitError();return}hideCartLimitError()}handleMinus(){const currentValue=parseInt(this.input.value,10);currentValue>1&&(this.input.value=(currentValue-1).toString(),this.updateQuantity(currentValue-1),this.updateButtonStates(),this.syncErrorVisibility(currentValue-1))}handlePlus(){const currentValue=parseInt(this.input.value,10);if(this.maxQuantity>0&&currentValue>=this.maxQuantity){showCartLimitError();return}(currentValue<this.maxQuantity||this.maxQuantity<=0)&&(this.input.value=(currentValue+1).toString(),this.updateQuantity(currentValue+1),this.updateButtonStates(),this.syncErrorVisibility(currentValue+1))}handleBlur(){const cleanStr=this.input.value.replace(/[^0-9]/g,"");let newQuantity=parseInt(cleanStr,10);Number.isNaN(newQuantity)||newQuantity<1?(this.input.value="1",newQuantity=1):this.maxQuantity>0&&newQuantity>this.maxQuantity?(this.input.value=this.maxQuantity.toString(),newQuantity=this.maxQuantity,showCartLimitError()):hideCartLimitError(),newQuantity!==this.originalQuantity&&this.updateQuantity(newQuantity),this.updateButtonStates()}handleKeypress(e){e.preventDefault(),e.key==="Enter"&&this.input.blur()}handleKeydown(e){[8,9,27,13,37,38,39,40].indexOf(e.keyCode)===-1&&(e.keyCode>=48&&e.keyCode<=57||e.keyCode>=96&&e.keyCode<=105||e.preventDefault())}handleInput(){const cleanValue=this.input.value.replace(/[^0-9]/g,"");cleanValue!==this.input.value&&(this.input.value=cleanValue);const currentValue=parseInt(cleanValue,10);this.input.classList.remove("error"),this.maxQuantity>0&&currentValue>this.maxQuantity?(this.input.value=this.maxQuantity.toString(),this.input.classList.add("error"),showCartLimitError()):currentValue<1?this.input.classList.add("error"):hideCartLimitError(),this.updateButtonStates()}updateButtonStates(){const currentValue=parseInt(this.input.value,10);this.minusButton&&this.minusButton.classList.toggle("cart__item-quantity-button--disabled",currentValue<=1),this.plusButton&&this.plusButton.classList.toggle("cart__item-quantity-button--disabled",this.maxQuantity>0&&currentValue>=this.maxQuantity)}updateQuantity(quantity){const formData=new FormData,sampleProduct=this.allSample.find(sample=>sample.dataset.parentId==this.varaintId);sampleProduct!=null&&formData.append(`updates[${sampleProduct.dataset.childId}]`,quantity.toString()),formData.append(`updates[${this.varaintId}]`,quantity.toString()),fetch((window.Shopify?.routes?.root||"/")+"cart/update.js",{method:"POST",body:formData}).then(async response=>{if(!response.ok){const errorData=await response.json().catch(()=>({})),rawMessage=errorData.description||errorData.message||`Erreur ${response.status}`;isCartQuantityLimitError(response.status,rawMessage)?showCartLimitError():showCartLimitError(rawMessage),this.reset();return}hideCartLimitError(),this.queueQuantityUpdatedAnnouncement(quantity),window.location.reload()}).catch(()=>{this.reset()})}queueQuantityUpdatedAnnouncement(quantity){const title=this.dataset.productTitle?.trim()||"Item",template=this.dataset.quantityUpdatedTemplate||"__TITLE__ quantity updated to __QUANTITY__";queueCartStatusForReload(fillCartStatusTemplate(template,{title,quantity}))}setOriginalQuantity(){this.originalQuantity=parseInt(this.input.value,10),this.setAttribute("data-original-quantity",this.input.value)}updateOriginalQuantity(){this.originalQuantity=parseInt(this.input.value,10),this.setOriginalQuantity()}reset(){this.input.value=this.originalQuantity.toString(),this.input.classList.remove("error"),this.updateButtonStates()}get quantity(){return parseInt(this.input.value,10)}set quantity(value){this.input.value=value.toString(),this.updateButtonStates()}};customElements.define("cart-item-quantity",CartItemQuantity)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["cart-limit-error"]&&!Shopify.designMode))try{(()=>{var ERROR_MESSAGE_SELECTOR="[data-cart-limit-error-message]",ERROR_TEXT_SELECTOR="[data-cart-limit-error-text]";function getErrorMessageEl(){return document.querySelector(ERROR_MESSAGE_SELECTOR)}function hideCartLimitError(){const errorMessage=getErrorMessageEl();if(!errorMessage)return;const textEl=errorMessage.querySelector(ERROR_TEXT_SELECTOR);textEl&&(textEl.textContent=""),errorMessage.classList.add("hidden"),errorMessage.setAttribute("hidden",""),errorMessage.setAttribute("aria-hidden","true")}var CartLimitError=class extends HTMLElement{constructor(){super(...arguments),this.errorMessage=null,this.errorMessageButton=null,this.handleErrorMessageClose=()=>{hideCartLimitError()}}connectedCallback(){this.errorMessage=this.querySelector("[data-cart-limit-error-message]"),this.errorMessageButton=this.errorMessage?.querySelector(".cart-limit-error_message_button")??null,this.errorMessageButton?.addEventListener("click",this.handleErrorMessageClose)}disconnectedCallback(){this.errorMessageButton?.removeEventListener("click",this.handleErrorMessageClose)}};window.customElements.get("c-cart-limit-error")||window.customElements.define("c-cart-limit-error",CartLimitError)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["cart-packaging-jp-hk"]&&!Shopify.designMode))try{(()=>{var SECTION_PREFIX="shopify-section-";function getSectionId(el){return el?.id?.startsWith(SECTION_PREFIX)?el.id.slice(SECTION_PREFIX.length):null}function closestSectionId(el){const wrapper=el?.closest(`[id^="${SECTION_PREFIX}"]`);return getSectionId(wrapper)}function buildUrl(base,params){const url=new URL(base??window.location.pathname,window.location.origin);for(const[key,value]of Object.entries(params))url.searchParams.set(key,value);return url.toString()}function withQuery(params,query){return query?{...Object.fromEntries(Object.entries(query).map(([k,v])=>[k,String(v)])),...params}:params}async function fetchSections(ids,options={}){const url=buildUrl(options.url,withQuery({sections:ids.join(",")},options.query)),response=await fetch(url,{credentials:"same-origin"});if(!response.ok)throw new Error(`Sections fetch ${response.status}`);return response.json()}function swapInner(html,selector){const selectors=Array.isArray(selector)?selector:[selector],doc=new DOMParser().parseFromString(html,"text/html");
3selectors.forEach(sel=>{document.querySelectorAll(sel).forEach(element=>{const source=element.dataset.id?doc.querySelector(`${sel}[data-id="${element.dataset.id}"]`):doc.querySelector(sel);source&&(element.innerHTML=source.innerHTML)})})}function swapSection(id,html){const live=document.getElementById(`${SECTION_PREFIX}${id}`);if(!live)return;const doc=new DOMParser().parseFromString(html,"text/html"),next=doc.getElementById(`${SECTION_PREFIX}${id}`)||doc.body.firstElementChild;next instanceof HTMLElement?live.replaceWith(next):live.hidden=!0}async function renderSections(targets,options={}){if(targets.length===0)return;const map=options.sections??await fetchSections(targets.map(t=>t.id),options);for(const target of targets){const html=map[target.id];typeof html=="string"&&(target.selector?swapInner(html,target.selector):swapSection(target.id,html))}}var CART_LIVE_STATUS_ID="cart-live-status",FOCUS_ANNOUNCE_DELAY_MS=300;function getOrCreateCartLiveRegion(){let region=document.getElementById(CART_LIVE_STATUS_ID);return region instanceof HTMLElement||(region=document.createElement("div"),region.id=CART_LIVE_STATUS_ID,region.className="sr-only form-status",region.setAttribute("role","status"),region.setAttribute("aria-live","polite"),region.setAttribute("aria-atomic","true"),document.body.appendChild(region)),region}function announceCartStatus(message,options={}){const trimmed=message.trim();if(!trimmed)return;const shouldFocus=options.focus!==!1,region=getOrCreateCartLiveRegion();if(shouldFocus){region.setAttribute("aria-live","off"),region.setAttribute("tabindex","-1"),region.textContent=trimmed,region.focus({preventScroll:!0}),window.setTimeout(()=>{region.setAttribute("aria-live","polite")},FOCUS_ANNOUNCE_DELAY_MS);return}region.textContent="",requestAnimationFrame(()=>{region.textContent=trimmed})}function delayFocusAfterAnnounce(callback){window.setTimeout(callback,FOCUS_ANNOUNCE_DELAY_MS)}function fillCartStatusTemplate(template,values){let result=template;return values.title!==void 0&&(result=result.replace(/__TITLE__/g,values.title)),values.quantity!==void 0&&(result=result.replace(/__QUANTITY__/g,String(values.quantity))),result}var CartPackagingBase=class extends HTMLElement{constructor(){super(),this.updateCart=!1,this.updateCart=!1,this.boxContainer=this.querySelector("[data-box-container]"),this.boxCheckbox=this.querySelector("[data-box-toggle]"),this.packagingMessageContainer=this.querySelector("[data-box-message-container]"),this.messageFields=Array.from(this.querySelectorAll("[data-packaging-message-input], [data-packaging-message-textarea], #packaging-message")),this.quantityContainer=this.querySelector("[data-packaging-message-quantity-container]"),this.packagingId=this.querySelector("[data-packaging-id]"),this.minusButton=this.querySelector("[data-packaging-message-minus]"),this.plusButton=this.querySelector("[data-packaging-message-plus]"),this.quantityInput=this.querySelector("[data-packaging-message-quantity]"),this.messageContent=this.querySelector("[data-packaging-message-content]"),this.submitButton=this.querySelector("[data-packaging-message-submit]"),this.noteContainer=this.querySelector("[data-packaging-message-note-container]"),this.noteText=this.querySelector("[data-packaging-message-note-text]"),this.noteButton=this.querySelector("[data-packaging-message-update-note]"),this.maxQuantity=parseInt(this.quantityInput?.getAttribute("max")??"")||0,this.currentQuantity=parseInt(this.quantityInput?.value??"")||0,this.sectionsParam=this.querySelector('input[name="sections"]')?.value||"",this.cartSummarySectionId=this.getCartSummarySectionId(),this.sectionsRender=[{id:"header",selector:[".header__action-link--cart"]},{id:"popup-add-to-cart",selector:["[data-popup-atc-container]"]},{id:"main-cart",selector:["[data-cart-items]",".cart__items-list",".engraving-panel-container-cart"]},{id:this.cartSummarySectionId,selector:["[data-cart-summary]"]}]}getCartSummarySectionId(){const summaryChild=document.querySelector("[data-cart-summary]");return closestSectionId(summaryChild)||"cart-summary"}connectedCallback(){this.onCheckboxChange=this.handleCheckboxChange.bind(this),this.boxCheckbox?.addEventListener("change",this.onCheckboxChange),this.onMinus=this.handleMinusClick.bind(this),this.onPlus=this.handlePlusClick.bind(this),this.minusButton?.addEventListener("click",this.onMinus),this.plusButton?.addEventListener("click",this.onPlus),this.onSubmit=this.handleSubmitNote.bind(this),this.onInput=this.handleTextareaInput.bind(this),this.onPaste=this.handleTextareaPaste.bind(this),this.submitButton?.addEventListener("click",this.onSubmit),this.messageFields.forEach(field=>{field.addEventListener("input",this.onInput),field.addEventListener("paste",this.onPaste)}),this.onNoteButton=this.handleNoteButtonClick.bind(this),this.noteButton?.addEventListener("click",this.onNoteButton),this.updateQuantity(this.currentQuantity),this.updateRemainingCharacters(),this.reconcileGiftMessage()}async reconcileGiftMessage(){this.boxCheckbox?.checked||this.hasStoredGiftMessage()&&await this.updateCartNote(this.getEmptyMessageAttributes())}hasStoredGiftMessage(){return this.messageFields.some(field=>field.value.trim())?!0:!!this.noteContainer&&!this.noteContainer.classList.contains("hide")}removeEvents(){this.boxCheckbox?.removeEventListener("change",this.onCheckboxChange),this.minusButton?.removeEventListener("click",this.onMinus),this.plusButton?.removeEventListener("click",this.onPlus),this.submitButton?.removeEventListener("click",this.onSubmit),this.messageFields.forEach(field=>{field.removeEventListener("input",this.onInput),field.removeEventListener("paste",this.onPaste)}),this.noteButton?.removeEventListener("click",this.onNoteButton)}async handleCheckboxChange(){this.updateCart||(this.disableBoxElements(),this.boxCheckbox?.checked?(this.packagingMessageContainer.style.display="block",this.packagingMessageContainer.classList.add("show"),await this.addBoxToCart(),this.packagingMessageContainer.setAttribute("data-box-message-container","true"),this.enableBoxElements(),this.announceMessageReveal(),delayFocusAfterAnnounce(()=>this.focusMessageField())):(this.packagingMessageContainer.classList.remove("show"),this.packagingMessageContainer.style.display="none",await this.removeBoxFromCart(),this.packagingMessageContainer.setAttribute("data-box-message-container","false"),this.enableBoxElements()))}
3announceMessageReveal(){const message=this.dataset.giftMessageAnnounce||"Gift message field is now available";announceCartStatus(message,{focus:!1})}focusMessageField(){const field=this.messageFields[0];field&&field.focus()}async addBoxToCart(){const boxProductId=this.boxCheckbox?.getAttribute("data-box-id");if(!boxProductId){console.error("Box product ID not found");return}const numericProductId=parseInt(boxProductId),boxInCart=this.packagingMessageContainer?.getAttribute("data-box-message-container");(boxInCart=="false"||!boxInCart)&&await this.addToCart(numericProductId,1,null,{_product_gift_cart:"true"})}async removeBoxFromCart(){const boxProductId=this.boxCheckbox?.getAttribute("data-box-id");if(!boxProductId){console.error("Box product ID not found");return}const packagingProductId=this.packagingId?.getAttribute("data-packaging-id");if(!packagingProductId){console.error("Packaging product ID not found");return}const numericProductId=parseInt(boxProductId),numericPackagingProductId=parseInt(packagingProductId),cart=await this.fetchCart(),boxItem=cart.items.find(item=>item.id===numericProductId),packagingItem=cart.items.find(item=>item.id===numericPackagingProductId);if(boxItem){const itemsKeys=[boxItem.key];packagingItem&&itemsKeys.push(packagingItem.key),await this.updateFromCartByKey(itemsKeys,0,this.getEmptyMessageAttributes()),this.resetGiftMessage()}else{console.error("Item not found in cart");return}}getEmptyMessageAttributes(){return this.messageFields.reduce((attributes,field)=>{const attributeName=this.getCartAttributeName(field);return attributeName&&(attributes[attributeName]=""),attributes},{})}
3resetGiftMessage(){this.messageFields.forEach(field=>{field.value="",this.hideError(field),this.updateRemainingCharacters(field)}),this.applyMessageState(this.getEmptyMessageAttributes())}async handleMinusClick(){if(this.currentQuantity>0&&!this.updateCart){this.disableBoxElements();const quantity=this.currentQuantity-1;this.updateQuantity(quantity);const packagingProductId=this.packagingId?.getAttribute("data-packaging-id");if(!packagingProductId){console.error("Packaging product ID not found");return}const numericProductId=parseInt(packagingProductId),item=(await this.fetchCart()).items.find(item2=>item2.id===numericProductId);if(item){const clearsMessage=quantity===0;await this.updateFromCartByKey([item.key],quantity,clearsMessage?this.getEmptyMessageAttributes():this.getMessageAttributes()),clearsMessage&&this.resetGiftMessage(),this.enableBoxElements(),this.announcePackagingQuantityUpdated(quantity)}else{console.error("Item not found in cart");return}}}async handlePlusClick(){if(this.currentQuantity<this.maxQuantity&&!this.updateCart){this.disableBoxElements();const quantity=this.currentQuantity+1;this.updateQuantity(quantity);const packagingProductId=this.packagingId?.getAttribute("data-packaging-id");if(!packagingProductId){console.error("Packaging product ID not found");return}const numericProductId=parseInt(packagingProductId),item=(await this.fetchCart()).items.find(item2=>item2.id===numericProductId);item?(await this.updateFromCartByKey([item.key],quantity,this.getMessageAttributes()),this.enableBoxElements(),this.announcePackagingQuantityUpdated(quantity)):(await this.addToCart(numericProductId,quantity,this.getMessageAttributes(),{_product_gift_cart:"true"}),this.enableBoxElements(),this.announcePackagingQuantityUpdated(quantity))}}updateQuantity(newQuantity){this.quantityInput&&(this.currentQuantity=Math.max(0,Math.min(newQuantity,this.maxQuantity)),this.quantityInput.value=String(this.currentQuantity),this.minusButton.style.opacity=this.currentQuantity<=0?"0.5":"1",this.minusButton.style.pointerEvents=this.currentQuantity<=0?"none":"auto",this.plusButton.style.opacity=this.currentQuantity>=this.maxQuantity?"0.5":"1",this.plusButton.style.pointerEvents=this.currentQuantity>=this.maxQuantity?"none":"auto")}announcePackagingQuantityUpdated(quantity){const title=this.dataset.productTitle?.trim()||"Item",template=this.dataset.quantityUpdatedTemplate||"__TITLE__ quantity updated to __QUANTITY__";announceCartStatus(fillCartStatusTemplate(template,{title,quantity}))}async handleSubmitNote(){this.messageFields.length!==0&&(this.updateCart||(this.disableBoxElements(),await this.updateCartNote(this.getMessageAttributes()),this.enableBoxElements()))}async updateCartNote(attributes){try{const response=await fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({attributes,sections:this.sectionsParam})});if(!response.ok){const errorData=await response.json();throw new Error(`HTTP ${response.status}: ${JSON.stringify(errorData)}`)}const data=await response.json();this.renderReturnedSections(data),this.applyMessageState(attributes)}catch(error){console.error("[CartPackaging] updateCartNote error:",error)}}applyMessageState(attributes){const lines=this.messageFields.map(field=>attributes[this.getCartAttributeName(field)??""]?.trim()).filter(value=>!!value),hasMessage=lines.length>0;this.messageContent?.classList.toggle("hide",hasMessage),this.quantityContainer?.classList.toggle("hide",hasMessage),this.noteText&&(this.noteText.innerHTML=lines.map(line=>line.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\r?\n/g,"<br>")).join("<br>")),this.noteContainer?.classList.toggle("hide",!hasMessage)}handleNoteButtonClick(){this.noteContainer?.classList.add("hide"),this.quantityContainer?.classList.remove("hide"),this.messageContent?.classList.remove("hide")}async addToCart(productId,quantity,attributes=null,properties=null){const formData={id:productId,quantity,sections:this.sectionsParam};properties&&(formData.properties=properties);try{const res=await fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(formData)});let data=await res.json();return res.ok?(attributes&&(data=await this.updateCartAttributes(attributes)),this.renderReturnedSections(data),data):this.handleRejectedMutation(data)}catch(error){throw console.error("Error adding to cart:",error),error}}async updateFromCartByKey(itemsKeys,qty,attributes=null){const updates=itemsKeys.reduce((acc,key)=>(acc[key]=qty,acc),{});try{const body={updates,sections:this.sectionsParam};attributes&&(body.attributes=attributes);const res=await fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}),data=await res.json();return res.ok?(this.renderReturnedSections(data),data):this.handleRejectedMutation(data)}catch(error){throw console.error("Error updating cart:",error),error}}async updateCartAttributes(attributes){const response=await fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({attributes,sections:this.sectionsParam})});if(!response.ok){const errorData=await response.json();throw new Error(`HTTP ${response.status}: ${JSON.stringify(errorData)}`)}return response.json()}renderReturnedSections(data){data?.sections&&renderSections(this.sectionsRender,{sections:data.sections})}async handleRejectedMutation(data){return console.error("[CartPackaging] cart mutation rejected:",data),await this.syncQuantityFromCart(),null}async syncQuantityFromCart(){const packagingProductId=this.packagingId?.getAttribute("data-packaging-id");if(!packagingProductId)return;const numericProductId=parseInt(packagingProductId);try{const quantity=(await this.fetchCart()).items.filter(item=>item.id===numericProductId).reduce((total,item)=>total+item.quantity,0);this.updateQuantity(quantity)}catch(error){console.error("[CartPackaging] cart resync failed:",error)}}async fetchCart(){const response=await fetch("/cart.js");if(!response.ok)throw new Error(`Cart fetch failed: ${response.status}`);return response.json()}disableBoxElements(){this.updateCart=!0,this.submitButton&&(this.submitButton.disabled=!0),this.boxContainer?.classList.add("disabled")}enableBoxElements(){this.updateCart=!1,this.submitButton&&(this.submitButton.disabled=!1),this.boxContainer?.classList.remove("disabled")}getMessageAttributes(){return this.messageFields.reduce((attributes,field)=>{const attributeName=this.getCartAttributeName(field);return attributeName&&(attributes[attributeName]=field.value.trim()),attributes},{})}getCartAttributeName(field){return field.name.match(/^attributes\[(.+)]$/)?.[1]??null}handleTextareaInput(event){if(!this.isMessageField(event.target))return;const field=event.target,max=Number(field.getAttribute("maxlength"))||250,before=this.normalizeFieldValue((field.value||"").normalize("NFC")),hadIllegal=this.illegalRx(!1).test(before);field.value=before.replace(this.illegalRx(!0),"").slice(0,max),hadIllegal?this.showError(field):this.hideError(field),this.updateRemainingCharacters(field)}handleTextareaPaste(event){if(!this.isMessageField(event.target))return;const field=event.target,raw=(event.clipboardData||window.clipboardData)?.getData("text")||"";if(this.illegalRx(!1).test(raw)){event.preventDefault(),this.showError(field);return}this.hideError(field)}normalizeFieldValue(value){return value}illegalRx(global=!1){const{modern,fallback}=this.allowedChars();try{return new RegExp(modern,global?"gu":"u")}catch(error){return console.error("[CartPackaging] illegalRx error:",error),new RegExp(fallback,global?"g":"")}}updateRemainingCharacters(field){(field?[field]:this.messageFields).forEac
3h(messageField=>{const remainingCharsElement=this.getMessageFieldContainer(messageField)?.querySelector("[data-packaging-remaining-characters]");if(!remainingCharsElement)return;const maxLength=Number(messageField.getAttribute("maxlength"))||250,currentLength=messageField.value.length,remaining=maxLength-currentLength;remainingCharsElement.textContent=String(remaining)})}showError(field){this.getMessageFieldContainer(field)?.querySelector("[data-packaging-error]")?.classList.add("error")}hideError(field){this.getMessageFieldContainer(field)?.querySelector("[data-packaging-error]")?.classList.remove("error")}getMessageFieldContainer(field){return field.closest(".cart__packaging-message-input")}isMessageField(target){return target instanceof HTMLInputElement||target instanceof HTMLTextAreaElement}},CartPackagingJpHk=class extends CartPackagingBase{allowedChars(){return{modern:"[^\\p{Script=Latin}\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Nd} \u3000\\r\\n.,!?'\\-\u3001\u3002\u30FC\u30FB\u300C\u300D\uFF08\uFF09\uFF01\uFF1F\uFF0E\uFF0C\u301C\uFF1A]",fallback:"[^A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\xFF0-9 \\r\\n.,!?'\\-\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF\uFF00-\uFFEF]"}}};customElements.define("cart-packaging",CartPackagingJpHk)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["cart-packaging"]&&!Shopify.designMode))try{(()=>{var SECTION_PREFIX="shopify-section-";function getSectionId(el){return el?.id?.startsWith(SECTION_PREFIX)?el.id.slice(SECTION_PREFIX.length):null}function closestSectionId(el){const wrapper=el?.closest(`[id^="${SECTION_PREFIX}"]`);return getSectionId(wrapper)}function buildUrl(base,params){const url=new URL(base??window.location.pathname,window.location.origin);for(const[key,value]of Object.entries(params))url.searchParams.set(key,value);return url.toString()}function withQuery(params,query){return query?{...Object.fromEntries(Object.entries(query).map(([k,v])=>[k,String(v)])),...params}:params}async function fetchSections(ids,options={}){const url=buildUrl(options.url,withQuery({sections:ids.join(",")},options.query)),response=await fetch(url,{credentials:"same-origin"});if(!response.ok)throw new Error(`Sections fetch ${response.status}`);return response.json()}function swapInner(html,selector){const selectors=Array.isArray(selector)?selector:[selector],doc=new DOMParser().parseFromString(html,"text/html");selectors.forEach(sel=>{document.querySelectorAll(sel).forEach(element=>{const source=element.dataset.id?doc.querySelector(`${sel}[data-id="${element.dataset.id}"]`):doc.querySelector(sel);source&&(element.innerHTML=source.innerHTML)})})}function swapSection(id,html){const live=document.getElementById(`${SECTION_PREFIX}${id}`);if(!live)return;const doc=new DOMParser().parseFromString(html,"text/html"),next=doc.getElementById(`${SECTION_PREFIX}${id}`)||doc.body.firstElementChild;next instanceof HTMLElement?live.replaceWith(next):live.hidden=!0}
3async function renderSections(targets,options={}){if(targets.length===0)return;const map=options.sections??await fetchSections(targets.map(t=>t.id),options);for(const target of targets){const html=map[target.id];typeof html=="string"&&(target.selector?swapInner(html,target.selector):swapSection(target.id,html))}}var CART_LIVE_STATUS_ID="cart-live-status",FOCUS_ANNOUNCE_DELAY_MS=300;function getOrCreateCartLiveRegion(){let region=document.getElementById(CART_LIVE_STATUS_ID);return region instanceof HTMLElement||(region=document.createElement("div"),region.id=CART_LIVE_STATUS_ID,region.className="sr-only form-status",region.setAttribute("role","status"),region.setAttribute("aria-live","polite"),region.setAttribute("aria-atomic","true"),document.body.appendChild(region)),region}function announceCartStatus(message,options={}){const trimmed=message.trim();if(!trimmed)return;const shouldFocus=options.focus!==!1,region=getOrCreateCartLiveRegion();if(shouldFocus){region.setAttribute("aria-live","off"),region.setAttribute("tabindex","-1"),region.textContent=trimmed,region.focus({preventScroll:!0}),window.setTimeout(()=>{region.setAttribute("aria-live","polite")},FOCUS_ANNOUNCE_DELAY_MS);return}region.textContent="",requestAnimationFrame(()=>{region.textContent=trimmed})}function delayFocusAfterAnnounce(callback){window.setTimeout(callback,FOCUS_ANNOUNCE_DELAY_MS)}function fillCartStatusTemplate(template,values){let result=template;return values.title!==void 0&&(result=result.replace(/__TITLE__/g,values.title)),values.quantity!==void 0&&(result=result.replace(/__QUANTITY__/g,String(values.quantity))),result}var CartPackagingBase=class extends HTMLElement{constructor(){super(),this.updateCart=!1,this.updateCart=!1,this.boxContainer=this.querySelector("[data-box-container]"),this.boxCheckbox=this.querySelector("[data-box-toggle]"),this.packagingMessageContainer=this.querySelector("[data-box-message-container]"),this.messageFields=Array.from(this.querySelectorAll("[data-packaging-message-input], [data-packaging-message-textarea], #packaging-message")),this.quantityContainer=this.querySelector("[data-packaging-message-quantity-container]"),this.packagingId=this.querySelector("[data-packaging-id]"),this.minusButton=this.querySelector("[data-packaging-message-minus]"),this.plusButton=this.querySelector("[data-packaging-message-plus]"),this.quantityInput=this.querySelector("[data-packaging-message-quantity]"),this.messageContent=this.querySelector("[data-packaging-message-content]"),this.submitButton=this.querySelector("[data-packaging-message-submit]"),this.noteContainer=this.querySelector("[data-packaging-message-note-container]"),this.noteText=this.querySelector("[data-packaging-message-note-text]"),this.noteButton=this.querySelector("[data-packaging-message-update-note]"),this.maxQuantity=parseInt(this.quantityInput?.getAttribute("max")??"")||0,this.currentQuantity=parseInt(this.quantityInput?.value??"")||0,this.sectionsParam=this.querySelector('input[name="sections"]')?.value||"",this.cartSummarySectionId=this.getCartSummarySectionId(),this.sectionsRender=[{id:"header",selector:[".header__action-link--cart"]},{id:"popup-add-to-cart",selector:["[data-popup-atc-container]"]},{id:"main-cart",selector:["[data-cart-items]",".cart__items-list",".engraving-panel-container-cart"]},{id:this.cartSummarySectionId,selector:["[data-cart-summary]"]}]}getCartSummarySectionId(){const summaryChild=document.querySelector("[data-cart-summary]");return closestSectionId(summaryChild)||"cart-summary"}connectedCallback(){this.onCheckboxChange=this.handleCheckboxChange.bind(this),this.boxCheckbox?.addEventListener("change",this.onCheckboxChange),this.onMinus=this.handleMinusClick.bind(this),this.onPlus=this.handlePlusClick.bind(this),this.minusButton?.addEventListener("click",this.onMinus),this.plusButton?.addEventListener("click",this.onPlus),this.onSubmit=this.handleSubmitNote.bind(this),this.onInput=this.handleTextareaInput.bind(this),this.onPaste=this.handleTextareaPaste.bind(this),this.submitButton?.addEventListener("click",this.onSubmit),this.messageFields.forEach(field=>{field.addEventListener("input",this.onInput),field.addEventListener("paste",this.onPaste)}),this.onNoteButton=this.handleNoteButtonClick.bind(this),this.noteButton?.addEventListener("click",this.onNoteButton),this.updateQuantity(this.currentQuantity),this.updateRemainingCharacters(),this.reconcileGiftMessage()}async reconcileGiftMessage(){this.boxCheckbox?.checked||this.hasStoredGiftMessage()&&await this.updateCartNote(this.getEmptyMessageAttributes())}hasStoredGiftMessage(){return this.messageFields.some(field=>field.value.trim())?!0:!!this.noteContainer&&!this.noteContainer.classList.contains("hide")}removeEvents(){this.boxCheckbox?.removeEventListener("change",this.onCheckboxChange),this.minusButton?.removeEventListener("click",this.onMinus),this.plusButton?.removeEventListener("click",this.onPlus),this.submitButton?.removeEventListener("click",this.onSubmit),this.messageFields.forEach(field=>{field.removeEventListener("input",this.onInput),field.removeEventListener("paste",this.onPaste)}),this.noteButton?.removeEventListener("click",this.onNoteButton)}async handleCheckboxChange(){this.updateCart||(this.disableBoxElements(),this.boxCheckbox?.checked?(this.packagingMessageContainer.style.display="block",this.packagingMessageContainer.classList.add("show"),await this.addBoxToCart(),this.packagingMessageContainer.setAttribute("data-box-message-container","true"),this.enableBoxElements(),this.announceMessageReveal(),delayFocusAfterAnnounce(()=>this.focusMessageField())):(this.packagingMessageContainer.classList.remove("show"),this.packagingMessageContainer.style.display="none",await this.removeBoxFromCart(),this.packagingMessageContainer.setAttribute("data-box-message-container","false"),this.enableBoxElements()))}
3announceMessageReveal(){const message=this.dataset.giftMessageAnnounce||"Gift message field is now available";announceCartStatus(message,{focus:!1})}focusMessageField(){const field=this.messageFields[0];field&&field.focus()}async addBoxToCart(){const boxProductId=this.boxCheckbox?.getAttribute("data-box-id");if(!boxProductId){console.error("Box product ID not found");return}const numericProductId=parseInt(boxProductId),boxInCart=this.packagingMessageContainer?.getAttribute("data-box-message-container");(boxInCart=="false"||!boxInCart)&&await this.addToCart(numericProductId,1,null,{_product_gift_cart:"true"})}async removeBoxFromCart(){const boxProductId=this.boxCheckbox?.getAttribute("data-box-id");if(!boxProductId){console.error("Box product ID not found");return}const packagingProductId=this.packagingId?.getAttribute("data-packaging-id");if(!packagingProductId){console.error("Packaging product ID not found");return}const numericProductId=parseInt(boxProductId),numericPackagingProductId=parseInt(packagingProductId),cart=await this.fetchCart(),boxItem=cart.items.find(item=>item.id===numericProductId),packagingItem=cart.items.find(item=>item.id===numericPackagingProductId);if(boxItem){const itemsKeys=[boxItem.key];packagingItem&&itemsKeys.push(packagingItem.key),await this.updateFromCartByKey(itemsKeys,0,this.getEmptyMessageAttributes()),this.resetGiftMessage()}else{console.error("Item not found in cart");return}}getEmptyMessageAttributes(){return this.messageFields.reduce((attributes,field)=>{const attributeName=this.getCartAttributeName(field);return attributeName&&(attributes[attributeName]=""),attributes},{})}
3resetGiftMessage(){this.messageFields.forEach(field=>{field.value="",this.hideError(field),this.updateRemainingCharacters(field)}),this.applyMessageState(this.getEmptyMessageAttributes())}async handleMinusClick(){if(this.currentQuantity>0&&!this.updateCart){this.disableBoxElements();const quantity=this.currentQuantity-1;this.updateQuantity(quantity);const packagingProductId=this.packagingId?.getAttribute("data-packaging-id");if(!packagingProductId){console.error("Packaging product ID not found");return}const numericProductId=parseInt(packagingProductId),item=(await this.fetchCart()).items.find(item2=>item2.id===numericProductId);if(item){const clearsMessage=quantity===0;await this.updateFromCartByKey([item.key],quantity,clearsMessage?this.getEmptyMessageAttributes():this.getMessageAttributes()),clearsMessage&&this.resetGiftMessage(),this.enableBoxElements(),this.announcePackagingQuantityUpdated(quantity)}else{console.error("Item not found in cart");return}}}async handlePlusClick(){if(this.currentQuantity<this.maxQuantity&&!this.updateCart){this.disableBoxElements();const quantity=this.currentQuantity+1;this.updateQuantity(quantity);const packagingProductId=this.packagingId?.getAttribute("data-packaging-id");if(!packagingProductId){console.error("Packaging product ID not found");return}const numericProductId=parseInt(packagingProductId),item=(await this.fetchCart()).items.find(item2=>item2.id===numericProductId);item?(await this.updateFromCartByKey([item.key],quantity,this.getMessageAttributes()),this.enableBoxElements(),this.announcePackagingQuantityUpdated(quantity)):(await this.addToCart(numericProductId,quantity,this.getMessageAttributes(),{_product_gift_cart:"true"}),this.enableBoxElements(),this.announcePackagingQuantityUpdated(quantity))}}updateQuantity(newQuantity){this.quantityInput&&(this.currentQuantity=Math.max(0,Math.min(newQuantity,this.maxQuantity)),this.quantityInput.value=String(this.currentQuantity),this.minusButton.style.opacity=this.currentQuantity<=0?"0.5":"1",this.minusButton.style.pointerEvents=this.currentQuantity<=0?"none":"auto",this.plusButton.style.opacity=this.currentQuantity>=this.maxQuantity?"0.5":"1",this.plusButton.style.pointerEvents=this.currentQuantity>=this.maxQuantity?"none":"auto")}announcePackagingQuantityUpdated(quantity){const title=this.dataset.productTitle?.trim()||"Item",template=this.dataset.quantityUpdatedTemplate||"__TITLE__ quantity updated to __QUANTITY__";announceCartStatus(fillCartStatusTemplate(template,{title,quantity}))}async handleSubmitNote(){this.messageFields.length!==0&&(this.updateCart||(this.disableBoxElements(),await this.updateCartNote(this.getMessageAttributes()),this.enableBoxElements()))}async updateCartNote(attributes){try{const response=await fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({attributes,sections:this.sectionsParam})});if(!response.ok){const errorData=await response.json();throw new Error(`HTTP ${response.status}: ${JSON.stringify(errorData)}`)}const data=await response.json();this.renderReturnedSections(data),this.applyMessageState(attributes)}catch(error){console.error("[CartPackaging] updateCartNote error:",error)}}applyMessageState(attributes){const lines=this.messageFields.map(field=>attributes[this.getCartAttributeName(field)??""]?.trim()).filter(value=>!!value),hasMessage=lines.length>0;this.messageContent?.classList.toggle("hide",hasMessage),this.quantityContainer?.classList.toggle("hide",hasMessage),this.noteText&&(this.noteText.innerHTML=lines.map(line=>line.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\r?\n/g,"<br>")).join("<br>")),this.noteContainer?.classList.toggle("hide",!hasMessage)}handleNoteButtonClick(){this.noteContainer?.classList.add("hide"),this.quantityContainer?.classList.remove("hide"),this.messageContent?.classList.remove("hide")}async addToCart(productId,quantity,attributes=null,properties=null){const formData={id:productId,quantity,sections:this.sectionsParam};properties&&(formData.properties=properties);try{const res=await fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(formData)});let data=await res.json();return res.ok?(attributes&&(data=await this.updateCartAttributes(attributes)),this.renderReturnedSections(data),data):this.handleRejectedMutation(data)}catch(error){throw console.error("Error adding to cart:",error),error}}async updateFromCartByKey(itemsKeys,qty,attributes=null){const updates=itemsKeys.reduce((acc,key)=>(acc[key]=qty,acc),{});try{const body={updates,sections:this.sectionsParam};attributes&&(body.attributes=attributes);const res=await fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}),data=await res.json();return res.ok?(this.renderReturnedSections(data),data):this.handleRejectedMutation(data)}catch(error){throw console.error("Error updating cart:",error),error}}async updateCartAttributes(attributes){const response=await fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({attributes,sections:this.sectionsParam})});if(!response.ok){const errorData=await response.json();throw new Error(`HTTP ${response.status}: ${JSON.stringify(errorData)}`)}return response.json()}renderReturnedSections(data){data?.sections&&renderSections(this.sectionsRender,{sections:data.sections})}async handleRejectedMutation(data){return console.error("[CartPackaging] cart mutation rejected:",data),await this.syncQuantityFromCart(),null}async syncQuantityFromCart(){const packagingProductId=this.packagingId?.getAttribute("data-packaging-id");if(!packagingProductId)return;const numericProductId=parseInt(packagingProductId);try{const quantity=(await this.fetchCart()).items.filter(item=>item.id===numericProductId).reduce((total,item)=>total+item.quantity,0);this.updateQuantity(quantity)}catch(error){console.error("[CartPackaging] cart resync failed:",error)}}async fetchCart(){const response=await fetch("/cart.js");if(!response.ok)throw new Error(`Cart fetch failed: ${response.status}`);return response.json()}disableBoxElements(){this.updateCart=!0,this.submitButton&&(this.submitButton.disabled=!0),this.boxContainer?.classList.add("disabled")}enableBoxElements(){this.updateCart=!1,this.submitButton&&(this.submitButton.disabled=!1),this.boxContainer?.classList.remove("disabled")}getMessageAttributes(){return this.messageFields.reduce((attributes,field)=>{const attributeName=this.getCartAttributeName(field);return attributeName&&(attributes[attributeName]=field.value.trim()),attributes},{})}getCartAttributeName(field){return field.name.match(/^attributes\[(.+)]$/)?.[1]??null}handleTextareaInput(event){if(!this.isMessageField(event.target))return;const field=event.target,max=Number(field.getAttribute("maxlength"))||250,before=this.normalizeFieldValue((field.value||"").normalize("NFC")),hadIllegal=this.illegalRx(!1).test(before);field.value=before.replace(this.illegalRx(!0),"").slice(0,max),hadIllegal?this.showError(field):this.hideError(field),this.updateRemainingCharacters(field)}handleTextareaPaste(event){if(!this.isMessageField(event.target))return;const field=event.target,raw=(event.clipboardData||window.clipboardData)?.getData("text")||"";if(this.illegalRx(!1).test(raw)){event.preventDefault(),this.showError(field);return}this.hideError(field)}normalizeFieldValue(value){return value}illegalRx(global=!1){const{modern,fallback}=this.allowedChars();try{return new RegExp(modern,global?"gu":"u")}catch(error){return console.error("[CartPackaging] illegalRx error:",error),new RegExp(fallback,global?"g":"")}}updateRemainingCharacters(field){(field?[field]:this.messageFields).forEac
3h(messageField=>{const remainingCharsElement=this.getMessageFieldContainer(messageField)?.querySelector("[data-packaging-remaining-characters]");if(!remainingCharsElement)return;const maxLength=Number(messageField.getAttribute("maxlength"))||250,currentLength=messageField.value.length,remaining=maxLength-currentLength;remainingCharsElement.textContent=String(remaining)})}showError(field){this.getMessageFieldContainer(field)?.querySelector("[data-packaging-error]")?.classList.add("error")}hideError(field){this.getMessageFieldContainer(field)?.querySelector("[data-packaging-error]")?.classList.remove("error")}getMessageFieldContainer(field){return field.closest(".cart__packaging-message-input")}isMessageField(target){return target instanceof HTMLInputElement||target instanceof HTMLTextAreaElement}},CartPackaging=class extends CartPackagingBase{allowedChars(){return{modern:"[^\\p{Script=Latin}\\p{Nd} \\r\\n.,!?'\\-]",fallback:"[^A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\xFF0-9 \\r\\n.,!?'\\-]"}}normalizeFieldValue(value){return value.replace(/[\r\n]+/g,"")}};customElements.define("cart-packaging",CartPackaging)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["cart-samples"]&&!Shopify.designMode))try{(()=>{var ERROR_MESSAGE_SELECTOR="[data-cart-limit-error-message]",ERROR_TEXT_SELECTOR="[data-cart-limit-error-text]",OPEN_ENGRAVING_PANEL_SELECTOR="c-engraving-panel.is-open",SEARCH_DIALOG_SELECTOR="dialog[data-search-dialog]";function getErrorMessageEl(){return document.querySelector(ERROR_MESSAGE_SELECTOR)}function getDefaultMessage(){return window.cartStrings?.addToCartLimitError??"The maximum allowed quantity for this product has been exceeded."}function closeOpenEngravingPanels(){document.querySelectorAll(OPEN_ENGRAVING_PANEL_SELECTOR).forEach(panel=>{panel.close()})}function closeHeaderSearchIfOpen(){const openDialogs=document.querySelectorAll(`${SEARCH_DIALOG_SELECTOR}[open]`);openDialogs.length!==0&&(document.documentElement.classList.remove("is-overflow-hidden"),openDialogs.forEac
3h(dialog=>{dialog.close()}))}function showCartLimitError(message){closeHeaderSearchIfOpen();const errorMessage=getErrorMessageEl();if(!errorMessage)return;const textEl=errorMessage.querySelector(ERROR_TEXT_SELECTOR);textEl&&(textEl.textContent=message??getDefaultMessage()),errorMessage.classList.remove("hidden"),errorMessage.removeAttribute("hidden"),errorMessage.setAttribute("aria-hidden","false"),closeOpenEngravingPanels(),window.scrollTo(0,0)}function hideCartLimitError(){const errorMessage=getErrorMessageEl();if(!errorMessage)return;const textEl=errorMessage.querySelector(ERROR_TEXT_SELECTOR);textEl&&(textEl.textContent=""),errorMessage.classList.add("hidden"),errorMessage.setAttribute("hidden",""),errorMessage.setAttribute("aria-hidden","true")}var SECTION_PREFIX="shopify-section-";function getSectionId(el){return el?.id?.startsWith(SECTION_PREFIX)?el.id.slice(SECTION_PREFIX.length):null}function closestSectionId(el){const wrapper=el?.closest(`[id^="${SECTION_PREFIX}"]`);return getSectionId(wrapper)}function buildUrl(base,params){const url=new URL(base??window.location.pathname,window.location.origin);for(const[key,value]of Object.entries(params))url.searchParams.set(key,value);return url.toString()}function withQuery(params,query){return query?{...Object.fromEntries(Object.entries(query).map(([k,v])=>[k,String(v)])),...params}:params}async function fetchSectionHTML(id,options={}){const url=buildUrl(options.url,withQuery({section_id:id},options.query)),response=await fetch(url,{credentials:"same-origin"});if(!response.ok)throw new Error(`Section fetch ${response.status}`);return response.text()}function swapInner(html,selector){const selectors=Array.isArray(selector)?selector:[selector],doc=new DOMParser().parseFromString(html,"text/html");selectors.forEach(sel=>{document.querySelectorAll(sel).forEach(element=>{const source=element.dataset.id?doc.querySelector(`${sel}[data-id="${element.dataset.id}"]`):doc.querySelector(sel);source&&(element.innerHTML=source.innerHTML)})})}function swapSection(id,html){const live=document.getElementById(`${SECTION_PREFIX}${id}`);if(!live)return;const doc=new DOMParser().parseFromString(html,"text/html"),next=doc.getElementById(`${SECTION_PREFIX}${id}`)||doc.body.firstElementChild;next instanceof HTMLElement?live.replaceWith(next):live.hidden=!0}
3async function renderSection(target,options={}){const html=await fetchSectionHTML(target.id,options);target.selector?swapInner(html,target.selector):swapSection(target.id,html)}var CART_LIVE_STATUS_ID="cart-live-status",FOCUS_ANNOUNCE_DELAY_MS=300;function getOrCreateCartLiveRegion(){let region=document.getElementById(CART_LIVE_STATUS_ID);return region instanceof HTMLElement||(region=document.createElement("div"),region.id=CART_LIVE_STATUS_ID,region.className="sr-only form-status",region.setAttribute("role","status"),region.setAttribute("aria-live","polite"),region.setAttribute("aria-atomic","true"),document.body.appendChild(region)),region}function announceCartStatus(message,options={}){const trimmed=message.trim();if(!trimmed)return;const shouldFocus=options.focus!==!1,region=getOrCreateCartLiveRegion();if(shouldFocus){region.setAttribute("aria-live","off"),region.setAttribute("tabindex","-1"),region.textContent=trimmed,region.focus({preventScroll:!0}),window.setTimeout(()=>{region.setAttribute("aria-live","polite")},FOCUS_ANNOUNCE_DELAY_MS);return}region.textContent="",requestAnimationFrame(()=>{region.textContent=trimmed})}var CartSamples=class extends HTMLElement{constructor(){super(),this.SELECTORS={samplesQty:"[data-samples-qty]",popup:"[data-samples-popup]",close:"[data-samples-close]",sampleItem:"[data-samples-product-item]",popupSampleItem:"[data-popup-sample-product-item]",addButton:"[data-samples-add]",count:"[data-samples-count]",cartItemsList:".cart__items-list",cartError:"[data-cart-error]",activePopupProduct:".cart__samples-popup-product.active",sectionRoot:"[data-cart-samples]"},this.CLASSES={error:"cart__items-error label-s-regular",active:"active",disabled:"disabled"},this.lastFocusedElement=null,this.onOpenPopup=event=>{this.openPopup(event)},this.onClosePopup=()=>{this.closePopup()},this.onDocumentKeydown=event=>{event.key==="Escape"&&this.popup?.classList.contains(this.CLASSES.active)&&this.closePopup()},this.onSampleItemKeydown=event=>{(event.key==="Enter"||event.key===" ")&&(event.preventDefault(),this.openPopup(event))},this.samplesQty=this.querySelector(this.SELECTORS.samplesQty)?.dataset.samplesQty,this.popup=this.querySelector(this.SELECTORS.popup),this.overlay=this.querySelector(this.SELECTORS.close),this.sampleItems=[...this.querySelectorAll(this.SELECTORS.sampleItem)],this.popupSampleItems=[...this.querySelectorAll(this.SELECTORS.popupSampleItem)],this.sampleAddButton=this.querySelector(this.SELECTORS.addButton),this.closeElements=[...this.querySelectorAll(this.SELECTORS.close)],this.samplesCount=this.querySelector(this.SELECTORS.count),this.sectionId=this.getSectionId(),this.sectionsRender=[{id:this.sectionId,selector:[this.SELECTORS.sectionRoot]}]}getSectionId(){return closestSectionId(this)||"cart-samples"}connectedCallback(){this.bindEvents(),this.updateButtonState(),this.setPopupHidden(!0)}disconnectedCallback(){this.removeEvents()}bindEvents(){this.sampleItems.forEach(item=>{item.addEventListener("click",this.onOpenPopup),item.addEventListener("keydown",this.onSampleItemKeydown)}),this.overlay?.addEventListener("click",this.onClosePopup),this.closeElements.forEach(element=>{element.addEventListener("click",this.onClosePopup)}),this.popupSampleItems.forEach(item=>{item.addEventListener("click",this.toggleActiveSample.bind(this))}),this.sampleAddButton?.addEventListener("click",this.addSamples.bind(this))}removeEvents(){this.sampleItems.forEach(item=>{item.removeEventListener("click",this.onOpenPopup),item.removeEventListener("keydown",this.onSampleItemKeydown)}),this.overlay?.removeEventListener("click",this.onClosePopup),this.closeElements.forEach(element=>{element.removeEventListener("click",this.onClosePopup)}),document.removeEventListener("keydown",this.onDocumentKeydown)}syncOpenersExpanded(isOpen){this.sampleItems.forEach(item=>{item.setAttribute("aria-expanded",isOpen?"true":"false")})}setPopupHidden(hidden){this.popup instanceof HTMLElement&&(this.popup.setAttribute("aria-hidden",hidden?"true":"false"),hidden?this.popup.setAttribute("inert",""):this.popup.removeAttribute("inert"))}openPopup(event){if(!this.popup&&!this.overlay)return;const trigger=event?.currentTarget;this.lastFocusedElement=trigger instanceof HTMLElement?trigger:null,this.setPopupHidden(!1),this.popup?.classList.add(this.CLASSES.active),this.overlay?.classList.add(this.CLASSES.active),this.syncOpenersExpanded(!0),document.body.classList.add("is-overflow-hidden"),document.addEventListener("keydown",this.onDocumentKeydown);const closeButton=this.popup?.querySelector("button[data-samples-close]");closeButton&&closeButton.focus()}
3closePopup(){if(!this.popup&&!this.overlay)return;this.popup?.classList.remove(this.CLASSES.active),this.setPopupHidden(!0),this.syncOpenersExpanded(!1),document.body.classList.remove("is-overflow-hidden"),document.removeEventListener("keydown",this.onDocumentKeydown);const overlay=this.overlay;setTimeout(()=>{overlay?.classList.remove(this.CLASSES.active)},300),this.lastFocusedElement&&this.lastFocusedElement.isConnected&&this.lastFocusedElement.focus(),this.lastFocusedElement=null}addSamples(event){event.preventDefault(),this.sampleAddButton&&(this.sampleAddButton.disabled=!0,this.replaceSamples())}async replaceSamples(){const max=Number(this.samplesQty??2),variantIds=this.getSelectedSampleVariantIds();if(!(variantIds.length>max)){this.clearCartError();try{await this.clearExistingSamples(),variantIds.length>0&&await this.addItemsToCart(this.buildSamplesPayload(variantIds)),this.onSamplesAdded(),this.announceSamplesUpdated()}catch(err){console.error("[CartSamples] samples flow error:",err),showCartLimitError(err instanceof Error&&err.message?err.message:"Une erreur est survenue.")}finally{this.sampleAddButton&&(this.sampleAddButton.disabled=!1),this.updateButtonState()}}}clearCartError(){hideCartLimitError()}getSelectedSampleVariantIds(){return this.popupSampleItems.filter(item=>item.classList.contains(this.CLASSES.active)).map(item=>item.dataset.popupSampleProductItem).filter(id=>id!==void 0)}async clearExistingSamples(){const sampleItems=(await this.fetchCart()).items.filter(it=>this.isSampleLineItem(it));if(!sampleItems.length)return;const updates={};sampleItems.forEach(item=>{updates[item.key]=0});const response=await fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},credentials:"same-origin",body:JSON.stringify({updates})});if(!response.ok){const errorData=await response.json().catch(()=>({}));throw new Error(`Remove samples failed: ${response.status} - ${errorData.message||"Unknown error"}`)}}isSampleLineItem(it){const p=it?.properties||{};return p._sample==="1"||p._sample==="true"||p.sample==="1"||p.sample==="true"}async fetchCart(){const res=await fetch("/cart.js",{method:"GET",headers:{Accept:"application/json"},credentials:"same-origin"});if(!res.ok)throw new Error(`Cart GET ${res.status}`);return res.json()}async addItemsToCart(payload){const res=await fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},credentials:"same-origin",body:JSON.stringify(payload)});if(!res.ok){let msg=`Add error ${res.status}`;try{const data=await res.json();(data?.description||data?.message)&&(msg=data.description||data.message)}catch{}throw new Error(msg)}return res.json()}buildSamplesPayload(variantIds){return{items:variantIds.map(id=>({id,quantity:1,properties:{_sample:"1",_product_gift_cart:"true"}}))}}onSamplesAdded(){this.closePopup(),setTimeout(()=>{this.renderSampleSection()},100)}announceSamplesUpdated(){const message=this.dataset.samplesUpdatedAnnounce||"Free samples updated";announceCartStatus(message)}async renderSampleSection(){try{for(const section of this.sectionsRender)await renderSection(section)}catch(error){console.error("[CartSamples] section render error:",error),window.location.reload()}}toggleActiveSample(event){if(this.checkAvailableSamples(event))return;event.currentTarget.classList.toggle(this.CLASSES.active),this.updateButtonState()}updateButtonState(){const max=Number(this.samplesQty??2),activeSamplesCount=this.querySelectorAll(this.SELECTORS.activePopupProduct).length;this.samplesCount&&(this.samplesCount.innerHTML=`(${activeSamplesCount}/${max})`),this.sampleAddButton&&(this.sampleAddButton.disabled=activeSamplesCount>max),activeSamplesCount>=max?this.disablePopupSimples():this.enablePopupSimples()}enablePopupSimples(){this.popupSampleItems.forEach(item=>{item.classList.contains(this.CLASSES.disabled)&&item.classList.remove(this.CLASSES.disabled)})}disablePopupSimples(){this.popupSampleItems.forEach(item=>{item.classList.contains(this.CLASSES.active)||item.classList.add(this.CLASSES.disabled)})}checkAvailableSamples(event){if(event.currentTarget.classList.contains(this.CLASSES.active))return!1;const activeSamplesCount=this.querySelectorAll(this.SELECTORS.activePopupProduct).length,max=Number(this.samplesQty??2);return activeSamplesCount>=max}};customElements.define("cart-samples",CartSamples)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["category-card"]&&!Shopify.designMode))try{(()=>{var CategoryCard=class extends HTMLElement{connectedCallback(){}disconnectedCallback(){}};window.customElements.get("c-category-card")||window.customElements.define("c-category-card",CategoryCard)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["collections-list"]&&!Shopify.designMode))try{(()=>{var CCollectionsList=class extends HTMLElement{constructor(){super(),this.titles=[],this.containers=[],this.emblaMap=new Map}connectedCallback(){this.titles=[...this.querySelectorAll(".collections-list__collection-title")],this.containers=[...this.querySelectorAll(".collections-list__collection-container")];const firstActive=this.querySelector(".collections-list__collection-container.active");
3firstActive&&this.initEmbla(firstActive),this.titles.forEach((title,index)=>{title.addEventListener("click",()=>this.switchTab(index))})}initEmbla(container){if(this.emblaMap.has(container)||typeof window.EmblaCarousel!="function")return;const viewport=container.querySelector(".embla__viewport");if(!viewport)return;const embla=window.EmblaCarousel(viewport,{dragFree:!1,active:!0,align:"start",slidesToScroll:"auto","(min-width: 1024px)":{active:!1,dragFree:!0,slidesToScroll:"auto"}},[EmblaCarouselAutoHeight()]);this.emblaMap.set(container,embla);const prev=container.querySelector(".embla__prev"),next=container.querySelector(".embla__next"),prevContainer=container.querySelector(".container_embla__prev"),nextContainer=container.querySelector(".container_embla__next"),bar=container.querySelector(".embla__progress__bar");if(prev&&prev.addEventListener("click",()=>embla.scrollPrev()),next&&next.addEventListener("click",()=>embla.scrollNext()),this.bindMouseFollow(prevContainer,prev),this.bindMouseFollow(nextContainer,next),bar){const updateProgress=()=>{const snapCount=embla.scrollSnapList().length,selected=embla.selectedScrollSnap();bar.style.width=`${100/snapCount}%`,bar.style.transform=`translate3d(${selected*100}%,0px,0px)`,prev?.parentElement&&prev.parentElement.toggleAttribute("data-disabled",!embla.canScrollPrev()),next?.parentElement&&next.parentElement.toggleAttribute("data-disabled",!embla.canScrollNext())};updateProgress(),embla.on("scroll",updateProgress),embla.on("resize",updateProgress),embla.on("reinit",updateProgress)}}bindMouseFollow(container,button){!container||!button||(container.addEventListener("mousemove",e=>this.followMouse(e,button)),container.addEventListener("mouseleave",()=>this.resetButton(button)))}followMouse(e,button){if(!button)return;const rect=e.currentTarget.getBoundingClientRect(),offsetX=e.clientX-rect.left-rect.width/2,offsetY=e.clientY-rect.top-rect.height/2;button.style.transform=`translate(${offsetX}px, ${offsetY}px)`}resetButton(button){button&&(button.style.transform="")}
3switchTab(index){this.titles.forEach(t=>{t.classList.remove("active"),t.classList.add("color-black-300")}),this.titles[index]?.classList.add("active"),this.titles[index]?.classList.remove("color-black-300"),this.containers.forEach(c=>c.classList.remove("active"));const target=this.containers[index];if(!target)return;target.classList.add("active"),this.initEmbla(target);const api=this.emblaMap.get(target);api&&api.reInit()}};customElements.get("c-collections-list")||customElements.define("c-collections-list",CCollectionsList)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__.countdown&&!Shopify.designMode))try{(()=>{var Countdown=class extends HTMLElement{constructor(){super(...arguments),this.timer=null,this.showSeconds=!0}connectedCallback(){const rawDate=this.getAttribute("end-date");if(this.endDate=new Date(rawDate??""),this.showSeconds=this.getAttribute("show-seconds")!=="false",isNaN(this.endDate.getTime())){console.error("Invalid end-date provided to c-countdown");return}this.update(),this.timer=setInterval(()=>this.update(),1e3)}disconnectedCallback(){this.timer&&clearInterval(this.timer)}update(){const now=new Date().getTime(),distance=this.endDate.getTime()-now;if(distance<0){this.handleExpiry();return}const days=Math.floor(distance/(1e3*60*60*24)),hours=Math.floor(distance%(1e3*60*60*24)/(1e3*60*60)),minutes=Math.floor(distance%(1e3*60*60)/(1e3*60)),seconds=Math.floor(distance%(1e3*60)/1e3);this.render(days,hours,minutes,seconds)}render(d,h,m,s){const dayEl=this.querySelector("[data-days]"),hourEl=this.querySelector("[data-hours]"),minEl=this.querySelector("[data-minutes]"),secEl=this.querySelector("[data-seconds]");dayEl&&(dayEl.textContent=d.toString().padStart(2,"0")),hourEl&&(hourEl.textContent=h.toString().padStart(2,"0")),minEl&&(minEl.textContent=m.toString().padStart(2,"0")),secEl&&this.showSeconds&&(secEl.textContent=s.toString().padStart(2,"0"))}handleExpiry(){this.timer&&clearInterval(this.timer);const endMessage=this.getAttribute("end-message");endMessage?this.innerHTML=`<div class="headline-m">${endMessage}</div>`:this.render(0,0,0,0),this.dispatchEvent(new CustomEvent("countdown:expired"))}};window.customElements.get("c-countdown")||window.customElements.define("c-countdown",Countdown)})()}catch(e){console.error(e)}})(),(function(){!__snippets__["description-main-products"]&&Shopify.designMode})(),(function(){if(!(!__snippets__["editor-copy-btn"]&&!Shopify.designMode))try{(function(){if(window.customElements.get("editor-copy-btn"))return;const STYLES=`
4    editor-copy-btn {
5      display: block;
6      position: absolute;
7      top: 10px;
8      right: 10px;
9      z-index: 9999;
10      pointer-events: none;
11    }
12    .ecb-btn {
13      pointer-events: auto;
14      background: #1a1a1a;
15      color: #fff;
16      border: none;
17      padding: 5px 13px;
18      border-radius: 4px;
19      cursor: pointer;
20      font: 11px/1.4 monospace;
21      letter-spacing: 0.05em;
22      opacity: 0.85;
23      transition: opacity 0.15s, background 0.15s;
24      box-shadow: 0 2px 8px rgba(0,0,0,0.28);
25    }
26    .ecb-btn:hover { opacity: 1; }
27    .ecb-btn.is-copied { background: #1d7a45; opacity: 1; }
28  `;function injectStyles(){if(document.getElementById("ecb-styles"))return;const s=document.createElement("style");s.id="ecb-styles",s.textContent=STYLES,document.head.appendChild(s)}function decodeHTML(str){return str.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'")}function parseScript(el){try{return JSON.parse(el.textContent||"{}")}catch{return null}}function compileConfig(sectionEl){const sectionScript=sectionEl.querySelector("script[data-config-section]"),sectionConfig=sectionScript?parseScript(sectionScript):{},blocks=Array.from(sectionEl.querySelectorAll("script[data-config-block]")).map(parseScript).filter(Boolean);return JSON.stringify({section:sectionConfig,blocks},null,2)}function copyText(text,btn){const confirm=()=>{btn.textContent="\u2713 Copied!",btn.classList.add("is-copied"),setTimeout(()=>{btn.textContent="{ } Copy config",btn.classList.remove("is-copied")},2e3)},ta=document.createElement("textarea");ta.value=text,ta.style.cssText="position:fixed;top:-9999px;left:-9999px;opacity:0",document.body.appendChild(ta),ta.focus(),ta.select();try{document.execCommand("copy"),confirm()}catch{const w=window.open("","_blank");
28w&&(w.document.open(),w.document.write("<pre>"+text.replace(/</g,"&lt;")+"</pre>"),w.document.close())}finally{document.body.removeChild(ta)}}window.customElements.define("editor-copy-btn",class extends HTMLElement{connectedCallback(){if(!window.Shopify?.designMode){this.hidden=!0;return}injectStyles();const parent=this.parentElement;parent&&getComputedStyle(parent).position==="static"&&(parent.style.position="relative");const btn=document.createElement("button");btn.className="ecb-btn",btn.type="button",btn.textContent="{ } Copy config",btn.setAttribute("aria-label","Copy section config as JSON"),btn.addEventListener("click",()=>{const sectionEl=this.closest(".shopify-section")||this.closest("[data-shopify-editor-section]")||this.parentElement;sectionEl&&copyText(compileConfig(sectionEl),btn)}),this.appendChild(btn)}})})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["filter-count"]&&!Shopify.designMode))try{(()=>{var TAG_CONTAINER="[data-filter-tag]",TAG_SELECTOR=".tag_filter",FilterCount=class extends HTMLElement{constructor(){super(...arguments),this.observer=null}connectedCallback(){this.update();const container=document.querySelector(TAG_CONTAINER);container&&(this.observer=new MutationObserver(()=>this.update()),this.observer.observe(container,{childList:!0,subtree:!0}))}disconnectedCallback(){this.observer?.disconnect(),this.observer=null}update(){const count=document.querySelectorAll(`${TAG_CONTAINER} ${TAG_SELECTOR}`).length,label=count>0?`(${count})`:"";this.textContent!==label&&(this.textContent=label),this.hasAttribute("hidden")!==(count===0)&&this.toggleAttribute("hidden",count===0)}};customElements.get("filter-count")||customElements.define("filter-count",FilterCount)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["gallery-main-product"]&&!Shopify.designMode))try{(()=>{var TWEEN_FACTOR_BASE=.2,ENGRAVING_INTRO_DELAY_MS=3e3,ENGRAVING_INTRO_DURATION_MS=1400,engravingIntroPlayed=!1,GalleryMainProduct=class extends HTMLElement{constructor(){super(...arguments),this.embla=null,this.sliderToScrollMobile="auto",this.sliderToScrollDesktop="auto",this.viewport=null,this.container=null,this.prevButton=null,this.nextButton=null,this.progressNode=null,this.prevContainer=null,this.nextContainer=null,this.firstSlideObserver=null,this.productDescription=null,this.galleryRoot=null,this.engravingTrigger=null,this.productTags=null,this.header=null,this.tweenFactor=0,this.tweenNodes=[],this.resizeObserver=null,this.descriptionObserver=null,this.lastViewportWidth=0,this.shortDescriptionHeight=0,this.engravingIntroTimeout=0,this.onPrevClick=()=>this.embla?.scrollPrev(),this.onNextClick=()=>this.embla?.scrollNext(),this.onPrevMouseMove=e=>this.followMouse(e,this.prevButton),this.onNextMouseMove=e=>this.followMouse(e,this.nextButton),this.onPrevMouseLeave=()=>this.resetButton(this.prevButton),this.onNextMouseLeave=()=>this.resetButton(this.nextButton)}connectedCallback(){const parentContainer=this.closest("c-gallery-container");this.viewport=this.querySelector(".embla__viewport"),this.container=this.querySelector(".embla__container"),this.prevButton=this.querySelector(".embla__prev"),this.nextButton=this.querySelector(".embla__next"),this.progressNode=this.querySelector(".embla__progress__bar"),this.prevContainer=this.querySelector(".container_embla__prev"),this.nextContainer=this.querySelector(".container_embla__next"),this.sliderToScrollMobile=this.dataset.slidesToScrollMobile||"auto",this.sliderToScrollDesktop=this.dataset.slidesToScrollDesktop||"auto",parentContainer?.classList.contains("v-slider")&&(this.initEmbla(),this.bindProgress(),this.bindMouseFollow()),this.productDescription=this.querySelector(".product-description--mobile"),this.galleryRoot=this.closest(".gallery-main-product"),this.engravingTrigger=this.galleryRoot?.querySelector(".engraving-trigger__wrapper")??null,this.productTags=document.querySelector(".main-product__tags"),this.header=document.querySelector("header"),this.classList.remove("shimmer"),this.playEngravingTriggerIntro(),this.bindFirstSlideAnimation(),this.embla&&this.setupParallax(),this.resizeObserver=new ResizeObserver(entries=>this.updateSlideSize(entries[0])),this.resizeObserver.observe(this),this.updateShortDescriptionHeight(),this.productDescription&&(this.descriptionObserver=new ResizeObserver(()=>this.updateShortDescriptionHeight()),this.descriptionObserver.observe(this.productDescription)),this.addEventListener("tuncat:resized",()=>{this.updateShortDescriptionHeight()||this.embla?.reInit()})}updateSlideSize(entry){const width=Math.round(entry?.contentRect.width??this.getBoundingClientRect().width);width===0||width===this.lastViewportWidth||(this.lastViewportWidth=width,this.embla?.reInit())}updateShortDescriptionHeight(){const target=this.galleryRoot??this.viewport;if(!target||!this.productDescription)return!1;const height=Math.round(this.productDescription.offsetHeight);return height<=0||height===this.shortDescriptionHeight?!1:(this.shortDescriptionHeight=height,target.style.setProperty("--short-description-height",`${height}px`),this.embla?.reInit(),!0)}disconnectedCallback(){window.clearTimeout(this.engravingIntroTimeout),this.engravingIntroTimeout=0,this.embla?.destroy(),this.embla=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.descriptionObserver?.disconnect(),this.descriptionObserver=null,this.firstSlideObserver?.disconnect(),this.firstSlideObserver=null,this.prevButton?.removeEventListener("click",this.onPrevClick),this.nextButton?.removeEventListener("click",this.onNextClick),this.prevContainer?.removeEventListener("mousemove",this.onPrevMouseMove),this.prevContainer?.removeEventListener("mouseleave",this.onPrevMouseLeave),this.nextContainer?.removeEventListener("mousemove",this.onNextMouseMove),this.nextContainer?.removeEventListener("mouseleave",this.onNextMouseLeave)}initEmbla(){!this.viewport||!this.container||(this.embla=EmblaCarousel(this.viewport,{dragFree:!1,active:!0,slidesToScroll:this.sliderToScrollMobile,"(min-width: 1024px)":{active:!1,dragFree:!0,slidesToScroll:"auto"}},[EmblaCarouselAutoHeight()]),this.prevButton?.addEventListener("click",this.onPrevClick),this.nextButton?.addEventListener("click",this.onNextClick))}bindProgress(){if(!this.embla||!this.progressNode)return;const progressNode=this.progressNode,applyProgress=()=>
28{if(!this.embla)return;const snapCount=this.embla.scrollSnapList().length,selected=this.embla.selectedScrollSnap();progressNode.style.width=`${100/snapCount}%`,progressNode.style.transform=`translate3d(${selected*100}%,0px,0px)`,this.prevButton?.parentElement?.toggleAttribute("data-disabled",!this.embla.canScrollPrev()),this.nextButton?.parentElement?.toggleAttribute("data-disabled",!this.embla.canScrollNext()),this.onScroll()};applyProgress(),this.embla.on("reinit",()=>applyProgress()).on("resize",()=>applyProgress()).on("scroll",()=>applyProgress()).on("slidefocus",()=>applyProgress())}bindMouseFollow(){this.prevContainer?.addEventListener("mousemove",this.onPrevMouseMove),this.prevContainer?.addEventListener("mouseleave",this.onPrevMouseLeave),this.nextContainer?.addEventListener("mousemove",this.onNextMouseMove),this.nextContainer?.addEventListener("mouseleave",this.onNextMouseLeave)}followMouse(e,button){if(!button)return;const rect=e.currentTarget.getBoundingClientRect(),offsetX=e.clientX-rect.left-rect.width/2,offsetY=e.clientY-rect.top-rect.height/2;button.style.transform=`translate(${offsetX}px, ${offsetY}px)`}resetButton(button){button&&(button.style.transform="")}playEngravingTriggerIntro(){engravingIntroPlayed||!this.engravingTrigger||this.engravingTrigger.offsetParent!==null&&(this.engravingIntroTimeout=window.setTimeout(()=>{engravingIntroPlayed||!this.engravingTrigger||this.engravingTrigger.offsetParent!==null&&(engravingIntroPlayed=!0,requestAnimationFrame(()=>{this.engravingTrigger?.classList.add("is-animate-engraving-trigger"),this.galleryRoot?.classList.contains("v-desktop")!==!0&&window.setTimeout(()=>{this.engravingTrigger?.classList.remove("is-animate-engraving-trigger")},ENGRAVING_INTRO_DURATION_MS)}))},ENGRAVING_INTRO_DELAY_MS))}bindFirstSlideAnimation(){const firstSlide=this.querySelector(".embla__slide:first-child");firstSlide&&(this.firstSlideObserver=new IntersectionObserver(entries=>{if(!entries[0].isIntersecting)return;this.firstSlideObserver?.disconnect(),this.firstSlideObserver=null;const quickBuyContainer=firstSlide.querySelector(".card-product-quick-buy__container");quickBuyContainer?.classList.add("is-animate-quick-buy"),window.setTimeout(()=>{quickBuyContainer?.classList.remove("is-animate-quick-buy")},ENGRAVING_INTRO_DURATION_MS)},{threshold:.8}),this.firstSlideObserver.observe(firstSlide))}setupParallax(){const embla=this.embla;this.setTweenNodes(),this.setTweenFactor(),this.clearParallax(),embla.on("reInit",()=>{this.setTweenNodes(),this.setTweenFactor(),this.clearParallax()}).on("scroll",(_api,eventName)=>this.tweenParallax(eventName)).on("slideFocus",()=>this.tweenParallax()).on("settle",()=>this.clearParallax()).on("pointerDown",()=>this.tweenParallax())}clearParallax(){this.tweenNodes.forEach(node=>{node&&(node.style.transform="")})}setTweenNodes(){this.tweenNodes=this.embla.slideNodes().map(slide=>slide.querySelector(".embla__parallax__layer"))}setTweenFactor(){this.tweenFactor=TWEEN_FACTOR_BASE*this.embla.scrollSnapList().length}tweenParallax(eventName){if(window.innerWidth>=1024){this.clearParallax();return}const embla=this.embla,engine=embla.internalEngine(),scrollProgress=embla.scrollProgress(),slidesInView=embla.slidesInView(),isScrollEvent=eventName==="scroll";embla.scrollSnapList().forEach((scrollSnap,snapIndex)=>{let diffToTarget=scrollSnap-scrollProgress;
28engine.slideRegistry[snapIndex].forEach(slideIndex=>{if(isScrollEvent&&!slidesInView.includes(slideIndex))return;engine.options.loop&&engine.slideLooper.loopPoints.forEach(loopItem=>{const target=loopItem.target();if(slideIndex===loopItem.index&&target!==0){const sign=Math.sign(target);sign===-1&&(diffToTarget=scrollSnap-(1+scrollProgress)),sign===1&&(diffToTarget=scrollSnap+(1-scrollProgress))}});const translate=diffToTarget*(-1*this.tweenFactor)*100,tweenNode=this.tweenNodes[slideIndex];tweenNode&&(tweenNode.style.transform=`translateX(${translate}%)`)})})}onScroll(){if(!this.embla||window.innerWidth>=1024)return;const viewportRect=this.embla.containerNode().parentElement.getBoundingClientRect();if(viewportRect.width===0)return;let editoRatio=0,nightRatio=0;this.embla.slideNodes().forEach(slide=>{const slideRect=slide.getBoundingClientRect();if(slideRect.right<=viewportRect.left||slideRect.left>=viewportRect.right)return;const overlapLeft=Math.max(viewportRect.left,slideRect.left),ratio=(Math.min(viewportRect.right,slideRect.right)-overlapLeft)/viewportRect.width;slide.classList.contains("v-edito-image-mobile")&&(editoRatio=Math.max(editoRatio,ratio)),slide.classList.contains("v-black")&&(nightRatio=Math.max(nightRatio,ratio))});const threshold=window.innerWidth>=1024?.5:.2,editoVisible=editoRatio>threshold,darkVisible=editoVisible||nightRatio>threshold,opacity=editoVisible?"0":"1",transition=editoVisible?"opacity 0.3s ease":"opacity 0.1s ease";[this.productDescription,this.engravingTrigger,this.productTags].forEach(el=>{el&&(el.style.transition=transition,el.style.opacity=opacity)}),window.innerWidth<1024&&this.header?.classList.toggle("is-edito-visible",darkVisible)}};window.customElements.get("c-gallery-main-product")||window.customElements.define("c-gallery-main-product",GalleryMainProduct)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["info-card"]&&!Shopify.designMode))try{(()=>{var InfoCard=class extends HTMLElement{connectedCallback(){}disconnectedCallback(){}};window.customElements.get("c-info-card")||window.customElements.define("c-info-card",InfoCard)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["main-product-reassurance"]&&!Shopify.designMode))try{(()=>{var MainProductReassurance=class extends HTMLElement{constructor(){super(...arguments),this.viewportNode=null,this.dotsNode=null,this.prevButton=null,this.nextButton=null,this.prevContainer=null,this.nextContainer=null,this.activeSidebar=null,this.isAnimating=!1,this.lastFocusedElement=null,this.onPrevClick=()=>{this.emblaApi?.scrollPrev()},this.onNextClick=()=>{this.emblaApi?.scrollNext()},this.onDocumentKeydown=e=>{e.key==="Escape"&&this.activeSidebar&&this._closeSidebar()}}connectedCallback(){if(this.viewportNode=this.querySelector(".embla__viewport"),this.dotsNode=this.querySelector(".embla__dots"),!this.viewportNode)return;const plugins=this.querySelectorAll(".embla__slide").length>1?[EmblaCarouselAutoplay({delay:3e3,stopOnInteraction:!1})]:[];this.emblaApi=EmblaCarousel(this.viewportNode,{loop:!0,dragFree:!1},plugins),this._buildDots(),this.emblaApi.on("select",()=>this._updateDots()),this.prevButton=this.querySelector(".embla__prev"),this.nextButton=this.querySelector(".embla__next"),this.prevContainer=this.querySelector(".container_embla__prev"),this.nextContainer=this.querySelector(".container_embla__next"),this.prevButton?.addEventListener("click",this.onPrevClick),this.nextButton?.addEventListener("click",this.onNextClick),this.prevContainer?.addEventListener("click",this.onPrevClick),this.nextContainer?.addEventListener("click",this.onNextClick),this._bindSidebar()}_buildDots(){if(!this.dotsNode)return;const count=this.emblaApi.scrollSnapList().length;if(this.dotsNode.innerHTML="",count<=1)return;const labelTemplate=this.dataset.slideLabelTemplate??"Slide __INDEX__ of __COUNT__";for(let i=0;i<count;i++){const btn=document.createElement("button");btn.type="button",btn.classList.add("embla__dot"),btn.setAttribute("aria-label",labelTemplate.replace("__INDEX__",String(i+1)).replace("__COUNT__",String(count))),bt
28n.addEventListener("click",()=>this.emblaApi.scrollTo(i)),this.dotsNode.appendChild(btn)}this._updateDots()}_updateDots(){if(!this.dotsNode)return;const selected=this.emblaApi.selectedScrollSnap();this.dotsNode.querySelectorAll(".embla__dot").forEach((dot,i)=>{const isActive=i===selected;dot.classList.toggle("is-active",isActive),isActive?dot.setAttribute("aria-current","true"):dot.removeAttribute("aria-current")})}_bindSidebar(){this.addEventListener("click",e=>{const trigger=e.target.closest("[data-reinsurance-sidebar]");trigger&&(e.preventDefault(),this._openSidebar(trigger.dataset.reinsuranceSidebar,trigger)),e.target.closest("[data-reinsurance-sidebar-close]")&&this.activeSidebar&&(e.preventDefault(),this._closeSidebar())}),document.addEventListener("keydown",this.onDocumentKeydown)}_syncTriggerExpanded(sidebarId){this.querySelectorAll("[data-reinsurance-sidebar]").forEach(trigger=>{const isOpen=trigger.dataset.reinsuranceSidebar===sidebarId;trigger.setAttribute("aria-expanded",isOpen?"true":"false")})}_openSidebar(sidebarId,trigger){if(this.isAnimating)return;const sidebar=this.querySelector(`[data-reinsurance-sidebar-content="${sidebarId}"]`);if(!sidebar)return;this.isAnimating=!0,this.activeSidebar=sidebarId,this.lastFocusedElement=trigger,this._syncTriggerExpanded(sidebarId),document.body.classList.add("is-overflow-hidden"),sidebar.classList.add("active"),sidebar.querySelector(".reinsurances-custom__sidebar-content")?.classList.add("active");const closeButton=sidebar.querySelector("button[data-reinsurance-sidebar-close]");closeButton&&closeButton.focus(),this.isAnimating=!1}_closeSidebar(){if(this.isAnimating||!this.activeSidebar)return;this.isAnimating=!0;const sidebar=this.querySelector(`[data-reinsurance-sidebar-content="${this.activeSidebar}"]`);if(!sidebar){this.isAnimating=!1;return}sidebar.querySelector(".reinsurances-custom__sidebar-content")?.classList.remove("active"),document.body.classList.remove("is-overflow-hidden"),sidebar.classList.remove("active"),this.activeSidebar=null,this._syncTriggerExpanded(null),this.isAnimating=!1,this.lastFocusedElement&&this.lastFocusedElement.isConnected&&(this.lastFocusedElement.querySelector("button")??this.lastFocusedElement).focus(),this.lastFocusedElement=null}disconnectedCallback(){document.removeEventListener("keydown",this.onDocumentKeydown),this.activeSidebar&&this._closeSidebar(),this.prevButton?.removeEventListener("click",this.onPrevClick),this.nextButton?.removeEventListener("click",this.onNextClick),this.prevContainer?.removeEventListener("click",this.onPrevClick),this.nextContainer?.removeEventListener("click",this.onNextClick),this.emblaApi?.destroy()}};window.customElements.get("c-main-product-reassurance")||window.customElements.define("c-main-product-reassurance",MainProductReassurance)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["main-product-tuncat-description"]&&!Shopify.designMode))try{(()=>{var Tuncat=class extends HTMLElement{constructor(){super(...arguments),this.seeMoreBtn=null,this.seeLessBtn=null,this.viewport=null,this.engravingBtn=null,this.resizeObserver=null,this.baseHeight=0,this.onSeeMore=()=>this.setExpanded(!0),this.onSeeLess=()=>this.setExpanded(!1)}connectedCallback(){this.seeMoreBtn=this.querySelector("[data-tuncat-see-more]"),this.seeLessBtn=this.querySelector("[data-tuncat-see-less]"),this.viewport=document.querySelector(".embla__viewport"),this.engravingBtn=document.querySelector(".engraving-trigger__wrapper"),this.seeMoreBtn?.addEventListener("click",this.onSeeMore),this.seeLessBtn?.addEventListener("click",this.onSeeLess),this.viewport&&this.observeResize()}disconnectedCallback(){this.seeMoreBtn?.removeEventListener("click",this.onSeeMore),this.seeLessBtn?.removeEventListener("click",this.onSeeLess),this.resizeObserver?.disconnect(),this.resizeObserver=null}setExpanded(expanded){this.classList.toggle("is-expanded",expanded),this.dispatchEvent(new CustomEvent("tuncat:toggled",{bubbles:!0,detail:{expanded}}))}observeResize(){this.resizeObserver=new ResizeObserver(entries=>{const height=entries[0].contentRect.height;if(this.baseHeight===0){this.baseHeight=height;return}const extra=Math.max(0,height-this.baseHeight);this.engravingBtn?.style.setProperty("--tuncat-expanded-height",`${extra}px`),this.viewport?.style.setProperty("--tuncat-expanded-height",`${extra}px`),this.viewport?.dispatchEvent(new CustomEvent("tuncat:resized",{bubbles:!0}))}),this.resizeObserver.observe(this)}};window.customElements.get("c-tuncat")||window.customElements.define("c-tuncat",Tuncat)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["media-card"]&&!Shopify.designMode))try{(()=>{var MediaCard=class extends HTMLElement{connectedCallback(){}disconnectedCallback(){}};window.customElements.get("c-media-card")||window.customElements.define("c-media-card",MediaCard)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["plp-night-toggle"]&&!Shopify.designMode))try{(()=>{var STORAGE_KEY="dptq_plp_night",URL_PARAM="night",ON="on",GRID_SELECTOR=".collection-grid, .collection-grid--next";function decodeKey(rawKey){try{return decodeURIComponent(rawKey.replace(/\+/g," "))}catch{return rawKey}}function withNightParam(search,night){const pairs=search.replace(/^\?/,"").split("&").filter(pair=>pair&&decodeKey(pair.split("=")[0])!==URL_PARAM);return night&&pairs.push(`${URL_PARAM}=${ON}`),pairs.length?`?${pairs.join("&")}`:""}var NIGHT_FIGURE_CLASS="card-product__night",NIGHT_READY_CLASS="card-product__night--ready",STRIP_ATTRIBUTE="plpNightStrip",FADE_ATTRIBUTE="plpNightFade",FADE_FALLBACK_MS=1200;function fadeWindowMs(){const raw=getComputedStyle(document.documentElement).getPropertyValue("--plp-night-duration").trim(),parsed=parseFloat(raw);return Number.isFinite(parsed)?(raw.endsWith("ms")?parsed:parsed*1e3)+100:FADE_FALLBACK_MS}function needsNightFigure(figure){const container=figure.parentElement;return!(!figure.dataset.nightSrc||!container||container.querySelector(`.${NIGHT_FIGURE_CLASS}`)||"nightFailed"in container.dataset)}function mountNightFigure(figure){if(!needsNightFigure(figure))return;
28const nightSrc=figure.dataset.nightSrc,container=figure.parentElement;if(!nightSrc||!container)return;const image=new Image;image.alt="",image.loading="eager",image.decoding="async",image.fetchPriority="low",image.width=600,image.height=800;const nightFigure=document.createElement("figure");nightFigure.className=NIGHT_FIGURE_CLASS,nightFigure.setAttribute("aria-hidden","true"),FADE_ATTRIBUTE in document.documentElement.dataset&&(nightFigure.dataset[FADE_ATTRIBUTE]=""),nightFigure.appendChild(image),container.appendChild(nightFigure),image.src=nightSrc,image.decode().then(()=>nightFigure.classList.add(NIGHT_READY_CLASS)).catch(()=>{if(image.naturalWidth>0){nightFigure.classList.add(NIGHT_READY_CLASS);return}container.dataset.nightFailed="",nightFigure.remove()})}var NIGHT_VIEWPORT_MARGIN="800px",watchedFigures=new WeakSet,viewportObserver=null;function nearViewportObserver(){return viewportObserver||(typeof IntersectionObserver!="function"?null:(viewportObserver=new IntersectionObserver(entries=>{for(const entry of entries)entry.isIntersecting&&(viewportObserver?.unobserve(entry.target),mountNightFigure(entry.target))},{rootMargin:NIGHT_VIEWPORT_MARGIN}),viewportObserver))}function stopMountingOnScroll(){viewportObserver?.disconnect(),viewportObserver=null,watchedFigures=new WeakSet}function mountNightFigures(){const io=nearViewportObserver();document.querySelectorAll(GRID_SELECTOR).forEach(grid=>grid.querySelectorAll("figure[data-night-src]").forEach(figure=>{if(needsNightFigure(figure)){if(!io){mountNightFigure(figure);return}watchedFigures.has(figure)||(watchedFigures.add(figure),io.observe(figure))}}))}var PlpNightToggle=class extends HTMLElement{constructor(){super(...arguments),this.observer=null,this.handleClick=event=>{const button=event.target?.closest("[data-plp-night-value]");!button||!this.contains(button)||this.apply(button.dataset.plpNightValue==="night")},this.fadeTimer=0,this.mountFrame=0}connectedCallback(){this.addEventListener("click",this.handleClick),this.sync()}disconnectedCallback(){this.removeEventListener("click",this.handleClick),this.stopObserving()}apply(night){const root=document.documentElement;night?root.dataset[STRIP_ATTRIBUTE]=ON:delete root.dataset[STRIP_ATTRIBUTE],document.body.offsetHeight,window.requestAnimationFrame(()=>{this.openFadeWindow(),night?root.dataset.plpNight=ON:delete root.dataset.plpNight,this.sync()});try{night?sessionStorage.setItem(STORAGE_KEY,ON):sessionStorage.removeItem(STORAGE_KEY)}catch{}const{pathname,search,hash}=window.location;history.replaceState(history.state,"",`${pathname}${withNightParam(search,night)}${hash}`)}sync(){const root=document.documentElement,night=root.dataset.plpNight===ON;night?root.dataset[STRIP_ATTRIBUTE]=ON:delete root.dataset[STRIP_ATTRIBUTE],night?(mountNightFigures(),this.startObserving()):this.stopObserving(),this.querySelectorAll("[data-plp-night-value]").forEach(button=>{const isNightButton=button.dataset.plpNightValue==="night";button.setAttribute("aria-pressed",String(isNightButton===night))})}openFadeWindow(){document.documentElement.dataset[FADE_ATTRIBUTE]="",window.clearTimeout(this.fadeTimer),this.fadeTimer=window.setTimeout(()=>{delete document.documentElement.dataset[FADE_ATTRIBUTE]},fadeWindowMs())}startObserving(){this.observer||(this.observer=new MutationObserver(()=>this.scheduleMount()),this.observer.observe(document.body,{childList:!0,subtree:!0}))}scheduleMount(){this.mountFrame||(this.mountFrame=requestAnimationFrame(()=>{this.mountFrame=0,mountNightFigures()}))}stopObserving(){this.observer?.disconnect(),this.observer=null,window.cancelAnimationFrame(this.mountFrame),this.mountFrame=0,stopMountingOnScroll()}};customElements.get("plp-night-toggle")||customElements.define("plp-night-toggle",PlpNightToggle)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["plp-view-toggle"]&&!Shopify.designMode))try{(()=>{var STORAGE_KEY="dptq_plp_grid",URL_PARAM="grid",COMPACT="compact";function decodeKey(rawKey){try{return decodeURIComponent(rawKey.replace(/\+/g," "))}catch{return rawKey}}function withGridParam(search,compact){const pairs=search.replace(/^\?/,"").split("&").filter(pair=>pair&&decodeKey(pair.split("=")[0])!==URL_PARAM);return compact&&pairs.push(`${URL_PARAM}=${COMPACT}`),pairs.length?`?${pairs.join("&")}`:""}var PlpViewToggle=class extends HTMLElement{constructor(){super(...arguments),this.handleClick=event=>{const button=event.target?.closest("[data-plp-grid-value]");!button||!this.contains(button)||this.transition(button.dataset.plpGridValue===COMPACT)}}connectedCallback(){this.addEventListener("click",this.handleClick),this.syncPressed()}disconnectedCallback(){this.removeEventListener("click",this.handleClick)}transition(compact){const start=document.startViewTransition;if(typeof start!="function"||window.matchMedia("(prefers-reduced-motion: reduce)").matches){this.apply(compact);return}start.call(document,()=>this.apply(compact))}apply(compact){const root=document.documentElement;compact?root.dataset.plpGrid=COMPACT:delete root.dataset.plpGrid,this.syncPressed();try{compact?sessionStorage.setItem(STORAGE_KEY,COMPACT):sessionStorage.removeItem(STORAGE_KEY)}catch{}const{pathname,search,hash}=window.location;history.replaceState(history.state,"",`${pathname}${withGridParam(search,compact)}${hash}`)}syncPressed(){const compact=document.documentElement.dataset.plpGrid===COMPACT;this.querySelectorAll("[data-plp-grid-value]").forEach(button=>{const isCompactButton=button.dataset.plpGridValue===COMPACT;button.setAttribute("aria-pressed",String(isCompactButton===compact))})}};customElements.get("plp-view-toggle")||customElements.define("plp-view-toggle",PlpViewToggle)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["product-card-v2"]&&!Shopify.designMode))try{(()=>{var ProductCardV2=class extends HTMLElement{connectedCallback(){}disconnectedCallback(){}};window.customElements.get("c-product-card-v2")||window.customElements.define("c-product-card-v2",ProductCardV2)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["product-form"]&&!Shopify.designMode))try{(()=>{var SECTION_PREFIX="shopify-section-";function getSectionId(el){return el?.id?.startsWith(SECTION_PREFIX)?el.id.slice(SECTION_PREFIX.length):null}function closestSectionId(el){const wrapper=el?.closest(`[id^="${SECTION_PREFIX}"]`);return getSectionId(wrapper)}function collectSectionIds(elements){const ids=new Set;for(const el of elements){const id=closestSectionId(el);id&&ids.add(id)}return[...ids]}function buildUrl(base,params){const url=new URL(base??window.location.pathname,window.location.origin);for(const[key,value]of Object.entries(params))url.searchParams.set(key,value);return url.toString()}function withQuery(params,query){return query?{...Object.fromEntries(Object.entries(query).map(([k,v])=>[k,String(v)])),...params}:params}async function fetchSections(ids,options={}){const url=buildUrl(options.url,withQuery({sections:ids.join(",")},options.query)),response=await fetch(url,{credentials:"same-origin"});if(!response.ok)throw new Error(`Sections fetch ${response.status}`);return response.json()}async function fetchSectionHTML(id,options={}){const url=buildUrl(options.url,withQuery({section_id:id},options.query)),response=await fetch(url,{credentials:"same-origin"});if(!response.ok)throw new Error(`Section fetch ${response.status}`);return response.text()}function swapInner(html,selector){const selectors=Array.isArray(selector)?selector:[selector],doc=new DOMParser().parseFromString(html,"text/html");
28selectors.forEach(sel=>{document.querySelectorAll(sel).forEach(element=>{const source=element.dataset.id?doc.querySelector(`${sel}[data-id="${element.dataset.id}"]`):doc.querySelector(sel);source&&(element.innerHTML=source.innerHTML)})})}function swapSection(id,html){const live=document.getElementById(`${SECTION_PREFIX}${id}`);if(!live)return;const doc=new DOMParser().parseFromString(html,"text/html"),next=doc.getElementById(`${SECTION_PREFIX}${id}`)||doc.body.firstElementChild;next instanceof HTMLElement?live.replaceWith(next):live.hidden=!0}async function renderSections(targets,options={}){if(targets.length===0)return;const map=options.sections??await fetchSections(targets.map(t=>t.id),options);for(const target of targets){const html=map[target.id];typeof html=="string"&&(target.selector?swapInner(html,target.selector):swapSection(target.id,html))}}async function renderSection(target,options={}){const html=await fetchSectionHTML(target.id,options);target.selector?swapInner(html,target.selector):swapSection(target.id,html)}var ERROR_MESSAGE_SELECTOR="[data-cart-limit-error-message]",ERROR_TEXT_SELECTOR="[data-cart-limit-error-text]",OPEN_ENGRAVING_PANEL_SELECTOR="c-engraving-panel.is-open",SEARCH_DIALOG_SELECTOR="dialog[data-search-dialog]",QUANTITY_LIMIT_PATTERNS=[/can'?t add more/i,/maximum allowed quantity/i,/maximum quantity/i,/quantity.*exceeded/i,/only add \d+/i];function getErrorMessageEl(){return document.querySelector(ERROR_MESSAGE_SELECTOR)}function getDefaultMessage(){return window.cartStrings?.addToCartLimitError??"The maximum allowed quantity for this product has been exceeded."}function isCartQuantityLimitError(status,description){if(status!==422)return!1;const normalized=description.trim();return normalized.length===0?!0:QUANTITY_LIMIT_PATTERNS.some(pattern=>pattern.test(normalized))}function closeOpenEngravingPanels(){document.querySelectorAll(OPEN_ENGRAVING_PANEL_SELECTOR).forEach(panel=>{panel.close()})}function closeHeaderSearchIfOpen(){const openDialogs=document.querySelectorAll(`${SEARCH_DIALOG_SELECTOR}[open]`);openDialogs.length!==0&&(document.documentElement.classList.remove("is-overflow-hidden"),openDialogs.forEac
28h(dialog=>{dialog.close()}))}function showCartLimitError(message){closeHeaderSearchIfOpen();const errorMessage=getErrorMessageEl();if(!errorMessage)return;const textEl=errorMessage.querySelector(ERROR_TEXT_SELECTOR);textEl&&(textEl.textContent=message??getDefaultMessage()),errorMessage.classList.remove("hidden"),errorMessage.removeAttribute("hidden"),errorMessage.setAttribute("aria-hidden","false"),closeOpenEngravingPanels(),window.scrollTo(0,0)}function hideCartLimitError(){const errorMessage=getErrorMessageEl();if(!errorMessage)return;const textEl=errorMessage.querySelector(ERROR_TEXT_SELECTOR);textEl&&(textEl.textContent=""),errorMessage.classList.add("hidden"),errorMessage.setAttribute("hidden",""),errorMessage.setAttribute("aria-hidden","true")}var CART_LIVE_STATUS_ID="cart-live-status",FOCUS_ANNOUNCE_DELAY_MS=300;function getOrCreateCartLiveRegion(){let region=document.getElementById(CART_LIVE_STATUS_ID);return region instanceof HTMLElement||(region=document.createElement("div"),region.id=CART_LIVE_STATUS_ID,region.className="sr-only form-status",region.setAttribute("role","status"),region.setAttribute("aria-live","polite"),region.setAttribute("aria-atomic","true"),document.body.appendChild(region)),region}function announceCartStatus(message,options={}){const trimmed=message.trim();if(!trimmed)return;const shouldFocus=options.focus!==!1,region=getOrCreateCartLiveRegion();if(shouldFocus){region.setAttribute("aria-live","off"),region.setAttribute("tabindex","-1"),region.textContent=trimmed,region.focus({preventScroll:!0}),window.setTimeout(()=>{region.setAttribute("aria-live","polite")},FOCUS_ANNOUNCE_DELAY_MS);return}region.textContent="",requestAnimationFrame(()=>{region.textContent=trimmed})}function fillCartStatusTemplate(template,values){let result=template;return values.title!==void 0&&(result=result.replace(/__TITLE__/g,values.title)),values.quantity!==void 0&&(result=result.replace(/__QUANTITY__/g,String(values.quantity))),result}var ENDPOINT="https://insights.algolia.io/1/events",AGENT="diptyque-theme",TOKEN_KEY="algolia_user_token",PIXEL_CONFIG_KEY="algolia_config",PIXEL_CLICK_KEY="algolia_analytics_clicked_objects",PIXEL_CLICK_MAX=50,MAX_OBJECT_IDS=20,THEME_EMITS_ADD_TO_CART=!0,OBJECT_ID_SELECTOR="[data-algolia-object-id]",CLICK_HOOKS="[data-algolia-click], [data-algolia-convert]";function readConfig(){const data=document.body?.dataset;return!data?.algoliaAppId||!data.algoliaApiKey||!data.algoliaIndex?null:{appId:data.algoliaAppId,apiKey:data.algoliaApiKey,index:data.algoliaIndex}}function readStorage(key){try{return window.localStorage.getItem(key)}catch{return null}}function writeStorage(key,value){try{window.localStorage.setItem(key,value)}catch{}}function randomUserToken(){const bytes=new Uint8Array(16);return crypto.getRandomValues(bytes),`anonymous-${Array.from(bytes,byte=>byte.toString(36).padStart(2,"0")).join("")}`}var cachedUserToken=null;function userToken(){if(cachedUserToken)return cachedUserToken;const stored=readStorage(TOKEN_KEY);return cachedUserToken=stored||randomUserToken(),stored||writeStorage(TOKEN_KEY,cachedUserToken),cachedUserToken}function authenticatedUserToken(){return document.body?.dataset.algoliaAuthenticatedUserToken||void 0}function normalizeObjectIDs(values){const ids=new Set;for(const value of values){const id=String(value??"").trim();id&&ids.add(id)}return Array.from(ids).slice(0,MAX_OBJECT_IDS)}function send(config,event){const params=new URLSearchParams({"X-Algolia-Application-Id":config.appId,"X-Algolia-API-Key":config.apiKey,"X-Algolia-Agent":AGENT}),url=`${ENDPOINT}?${params}`,body=JSON.stringify({events:[event]});navigator.sendBeacon?.(url,body)||fetch(url,{method:"POST",body,keepalive:!0}).catch(()=>{})}function track(config,objectIDs,event){objectIDs.length!==0&&send(config,{...event,index:config.index,objectIDs,userToken:userToken(),authenticatedUserToken:authenticatedUserToken()})}function writePixelConfig(config){writeStorage(PIXEL_CONFIG_KEY,JSON.stringify({app_id:config.appId,search_api_key:config.apiKey,index_name:config.index,user_token:userToken()}))}function recordClickForPixel(config,objectIDs,productId){const stored=readStorage(PIXEL_CLICK_KEY);let records=[];try{const parsed=stored?JSON.parse(stored):[];Array.isArray(parsed)&&(records=parsed)}catch{records=[]}records.push({index:config.index,objectIDs,productId}
28),writeStorage(PIXEL_CLICK_KEY,JSON.stringify(records.slice(-PIXEL_CLICK_MAX)))}function readObjectId(element){const above=element?.closest(OBJECT_ID_SELECTOR);return above?.dataset.algoliaObjectId?above.dataset.algoliaObjectId:element?.querySelector(OBJECT_ID_SELECTOR)?.dataset.algoliaObjectId??""}function readProductId(element){const above=element?.closest("[data-algolia-product-id]");return above?.dataset.algoliaProductId?above.dataset.algoliaProductId:element?.querySelector("[data-algolia-product-id]")?.dataset.algoliaProductId??""}function onDocumentClick(event){const target=event.target;if(!(target instanceof Element))return;const hook=target.closest(CLICK_HOOKS);if(!hook)return;const config=readConfig();if(!config)return;const objectIDs=normalizeObjectIDs([readObjectId(hook)]);objectIDs.length!==0&&(writePixelConfig(config),recordClickForPixel(config,objectIDs,readProductId(hook)),!hook.matches("[data-algolia-convert]")&&track(config,objectIDs,{eventType:"click",eventName:"Product Clicked"}))}function onCartAddSuccess(event){if(!THEME_EMITS_ADD_TO_CART)return;const target=event.target;if(!(target instanceof Element))return;const config=readConfig();if(!config)return;const objectIDs=normalizeObjectIDs([readObjectId(target)]);objectIDs.length!==0&&(writePixelConfig(config),track(config,objectIDs,{eventType:"conversion",eventSubtype:"addToCart",eventName:"Add To Cart"}))}function initAlgoliaInsights(){typeof window>"u"||window.algoliaInsightsReady||(window.algoliaInsightsReady=!0,document.addEventListener("click",onDocumentClick,!0),document.addEventListener("cart:add-success",onCartAddSuccess))}var CProductForm=class extends HTMLElement{constructor(){super(...arguments),this.SELECTORS={form:"form",submitButton:'button[type="submit"]',updatesInput:'input[name^="updates["]',qtyFixedInput:"[data-qty-fixed]",qtyButton:"[data-qty-btn]",notifyMeButton:"[data-notify-me-button]",notifyWidget:'.gw-float-widget[type="button"]',loaderId:"full-page-loader",cartRecommendRoot:"[data-cart-recommend-root]",samplesSection:"[data-samples-section]",samplesRoot:"[data-cart-samples]",packagingRoot:"[data-cart-packaging]",giftLine:"[data-gift-line]",headerCartLink:".header__action-link--cart",popupAtcContainer:"[data-popup-atc-container]",cartItems:"[data-cart-items]",cartLine:"[data-cart-items] [data-line-key]",engravingPanelCart:".engraving-panel-container-cart",cartSummary:"[data-cart-summary]",cartSummarySection:".section-cart-summary"},this.form=null,this.countCartItems=null,this.formId=null,this.btnSubmit=null,this.btnSubmitAlreadyInfos=null,this.type=null,this.isCart=null,this.itemKey=null,this.action="add",this.errorMessages={},this.quantitySnapshot=null,this.samplesSectionId=null,this.sectionsRenderSamples=[],this.sectionsRender=[],this.hasConnected=!1,this.submitForm=async()=>{if(!this.form)return;this.clearCartError();const hiddenElements=Array.from(this.form.querySelectorAll("input, select, textarea")).filter(el=>el.offsetParent===null&&el.type!=="hidden");hiddenElements.forEach(el=>{el.disabled=!0});const formData=new FormData(this.form);hiddenElements.forEach(el=>{el.disabled=!1});const config=this.fetchConfig("javascript"),targets=this.withGiftLineTarget(this.isCart?this.getCartPageTargets():this.sectionsRender),sectionsParam=targets.map(target=>target.id).join(",");if(formData.set("sections",sectionsParam),this.action==="change"&&this.itemKey){const properties={};for(const[key,value]of formData.entries())if(key.includes("properties")){const propKey=key.match(/\[(.*?)\]/g)?.pop()?.replace(/[[\]]/g,"");propKey&&(properties[propKey]=value)}config.body=JSON.stringify({id:this.itemKey,properties,sections:sectionsParam})}else config.body=formData,delete config.headers["Content-Type"];config.headers["X-Requested-With"]="XMLHttpRequest";try{const endpoints={add:"cart/add.js",change:"cart/change.js",update:"cart/update.js",remove:"cart/update.js",add_virtual_set:"cart/add.js"},endpoint=endpoints[this.action]??endpoints.add;if(this.action==="set_virtual_set"){await this.setVirtualSetQuantity(formData,sectionsParam,targets);return}const response=await fetch((window.Shopify?.routes?.root||"/")+endpoint,config);if(!response.ok){const errorData=await response.json().catch(()=>({})),rawMessage=errorData.description||errorData.message||`Erreur ${response.status}`,message=this.errorMessages[rawMessage]||rawMessage;throw isCartQuantityLimitError(response.status,rawMessage)?showCartLimitError():showCartLimitError(message),new Error(message)}const data=await response.json();hideCartLimitError(),this.quantitySnapshot=null;const statusAnnouncement=this.buildCartMutationAnnouncement();await renderSections(targets,{sections:data.sections}),statusAnnouncement&&announceCartStatus(statusAnnouncement),this.dispatchEvent(new CustomEvent("cart:add-success",{bubbles:!0,detail:{data,action:this.action}})),this.isCart&&(this.renderSampleSection(),await this.rerenderCartRecommendSections())}catch(error){this.restoreQuantitySnapshot(),console.error(error.message)}}}readDom(){this.form=this.querySelector(this.SELECTORS.form),this.countCartItems=this.dataset.countCartItems||null,this.formId=this.form?.id||null,this.btnSubmit=this.querySelector(this.SELECTORS.submitButton),this.btnSubmitAlreadyInfos=document.querySelector(`button[form="${this.formId}"]`),this.type=this.dataset.type||null,this.isCart=this.dataset.isCart||null,this.itemKey=this.dataset.itemKey||null,this.action=this.dataset.action||"add",this.errorMessages={error_product_gift_cart:this.dataset.errorProductGiftCart||""},this.samplesSectionId=this.getSamplesSectionId(),this.sectionsRenderSamples=this.samplesSectionId?[{id:this.samplesSectionId,selector:[this.SELECTORS.samplesRoot,this.SELECTORS.packagingRoot]}]:[],this.sectionsRender=[{id:"header",selector:[this.SELECTORS.headerCartLink]},{id:"popup-add-to-cart",selector:[this.SELECTORS.popupAtcContainer]}]}getSamplesSectionId(){const sectionChild=document.querySelector(this.SELECTORS.samplesSection);return closestSectionId(sectionChild)}getCartSummarySectionId(){return closestSectionId(document.querySelector(this.SELECTORS.cartSummarySection))??closestSectionId(document.querySelector(this.SELECTORS.cartSummary))}getCartPageTargets(){const cartSummarySectionId=this.getCartSummarySectionId();return[{id:"header",selector:[this.SELECTORS.headerCartLink]},{id:"popup-add-to-cart",selector:[this.SELECTORS.popupAtcContainer]},{id:"main-cart",selector:[this.SELECTORS.cartItems,this.SELECTORS.engravingPanelCart]},...cartSummarySectionId?[{id:cartSummarySectionId}]:[]]}withGiftLineTarget(targets){if(!this.form?.querySelector(this.SELECTORS.giftLine))return targets;const id=closestSectionId(this);if(!id)return targets;const existing=targets.find(target=>target.id===id);if(!existing)return[...targets,{id,selector:[this.SELECTORS.giftLine]}];if(!existing.selector)return targets;const selectors=Array.isArray(existing.selector)?existing.selector:[existing.selector];return selectors.includes(this.SELECTORS.giftLine)?targets:targets.map(target=>target===existing?{...target,selector:[...selectors,this.SELECTORS.giftLine]}:target)}connectedCallback(){this.hasConnected||(this.hasConnected=!0,setTimeout(()=>{this.readDom(),this.initNotifyMe(),this.checkNotifyMeHash()},0),this.addEventListener("submit",async e=>{if(this.readDom(),!this.form)return;e.preventDefault(),this.btnSubmit&&this.btnSubmit.setAttribute("disabled","true"),this.btnSubmitAlreadyInfos&&this.btnSubmitAlreadyInfos.setAttribute("disabled","true");const loader=document.getElementById(this.SELECTORS.loaderId);loader&&loader.setAttribute("aria-hidden","false"),await this.submitForm(
28),loader&&loader.setAttribute("aria-hidden","true"),this.btnSubmit&&this.btnSubmit.removeAttribute("disabled"),this.btnSubmitAlreadyInfos&&this.btnSubmitAlreadyInfos.removeAttribute("disabled")}),this.addEventListener("focusin",e=>{if(this.readDom(),this.action!=="update")return;e.target.name?.startsWith("updates[")&&this.captureQuantitySnapshot()}),this.addEventListener("change",e=>{e.target.name?.includes("updates[")&&(this.readDom(),this.form?.requestSubmit())}),this.addEventListener("click",e=>{const button=e.target.closest(this.SELECTORS.qtyButton);if(!button||(this.readDom(),!this.form))return;e.preventDefault();const step=parseInt(button.getAttribute("data-qty-step")||"0",10),inputs=Array.from(this.form.querySelectorAll(this.SELECTORS.updatesInput)),stepped=inputs.filter(el=>!el.matches(this.SELECTORS.qtyFixedInput)),fixed=inputs.filter(el=>el.matches(this.SELECTORS.qtyFixedInput));let blockedByLimit=!1;if(this.captureQuantitySnapshot(),stepped.forEach(el=>{const currentVal=parseInt(el.value||"0",10),maxAttr=el.getAttribute("max"),maxQuantity=maxAttr?parseInt(maxAttr,10):Number.NaN,nextVal=currentVal+step;if(step>0&&Number.isFinite(maxQuantity)&&nextVal>maxQuantity){blockedByLimit=!0;return}el.value=Math.max(0,nextVal).toString()}),blockedByLimit){this.quantitySnapshot=null,showCartLimitError();return}const parentRemains=stepped.some(el=>parseInt(el.value||"0",10)>0);fixed.forEach(el=>{el.value=parentRemains?"1":"0"}),this.form.requestSubmit()}))}initNotifyMe(){const notifyMeBtn=this.querySelector(this.SELECTORS.notifyMeButton);if(!notifyMeBtn)return;const href=notifyMeBtn.getAttribute("href")||"";href&&!href.includes("#notify-me")&&notifyMeBtn.setAttribute("href",`${href}#notify-me`);const bindNotifyWidget=(retries=20,interval=300)=>{const widget=document.querySelector(this.SELECTORS.notifyWidget);widget?(widget.style.display="none",notifyMeBtn.addEventListener("click",event=>{event.preventDefault(),widget.click()})):retries>0&&setTimeout(()=>bindNotifyWidget(retries-1,interval),interval)};bindNotifyWidget()}checkNotifyMeHash(){if(window.location.hash!=="#notify-me")return;const autoOpenNotifyWidget=(retries=20,interval=300)=>{const widget=document.querySelector(this.SELECTORS.notifyWidget);widget?(widget.click(),history.replaceState(null,"",window.location.pathname+window.location.search)):retries>0&&setTimeout(()=>autoOpenNotifyWidget(retries-1,interval),interval)};autoOpenNotifyWidget()}async renderSampleSection(){try{for(const section of this.sectionsRenderSamples)await renderSection(section)}catch(error){console.error("[CartSamples] section render error:",error),window.location.reload()}}async setVirtualSetQuantity(formData,sectionsParam,targets){const removals=new FormData,additions=new FormData;for(const[key,value]of formData.entries())key.startsWith("updates[")?removals.append(key,value):key.startsWith("items[")&&additions.append(key,value);if(![...additions.keys()].length)throw new Error("[VirtualSet] aucun items[\u2026] \xE0 reposer");additions.set("sections",sectionsParam);const order=this.readCartOrder(),root=window.Shopify?.routes?.root||"/",headers={"X-Requested-With":"XMLHttpRequest"};if([...removals.keys()].length){const removed=await fetch(`${root}cart/update.js`,{method:"POST",headers,body:removals});if(!removed.ok)throw new Error(await this.readCartError(removed))}const added=await fetch(`${root}cart/add.js`,{method:"POST",headers,body:additions});if(!added.ok)throw new Error(await this.readCartError(added));const data=await added.json();hideCartLimitError(),this.quantitySnapshot=null;const statusAnnouncement=this.buildCartMutationAnnouncement();await renderSections(targets,{sections:data.sections}),this.restoreCartOrder(order),statusAnnouncement&&announceCartStatus(statusAnnouncement),this.dispatchEvent(new CustomEvent("cart:add-success",{bubbles:!0,detail:{data,action:this.action}})),this.isCart&&(this.renderSampleSection(),await this.rerenderCartRecommendSections())}readCartOrder(){return[...document.querySelectorAll(this.SELECTORS.cartLine)].flatMap(card=>card.dataset.lineKey?[card.dataset.lineKey]:[])}restoreCartOrder(order){if(order.length<2)return;const cards=[...document.querySelectorAll(this.SELECTORS.cartLine)],parent=cards[0]?.parentElement;
28if(!parent)return;const byKey=new Map(cards.filter(card=>card.parentElement===parent&&card.dataset.lineKey).map(card=>[card.dataset.lineKey,card]));for(const key of order){const card=byKey.get(key);card&&(parent.appendChild(card),byKey.delete(key))}for(const card of byKey.values())parent.appendChild(card)}async readCartError(response){const errorData=await response.json().catch(()=>({})),rawMessage=errorData.description||errorData.message||`Erreur ${response.status}`;return isCartQuantityLimitError(response.status,rawMessage)?showCartLimitError():showCartLimitError(this.errorMessages[rawMessage]||rawMessage),rawMessage}captureQuantitySnapshot(){!this.form||this.action!=="update"||(this.quantitySnapshot=new Map,this.form.querySelectorAll(this.SELECTORS.updatesInput).forEach(input=>{this.quantitySnapshot.set(input.name,input.value)}))}restoreQuantitySnapshot(){!this.form||!this.quantitySnapshot||(this.form.querySelectorAll(this.SELECTORS.updatesInput).forEach(input=>{const saved=this.quantitySnapshot.get(input.name);saved!==void 0&&(input.value=saved)}),this.quantitySnapshot=null)}clearCartError(){hideCartLimitError()}buildCartMutationAnnouncement(){const title=this.dataset.productTitle?.trim()||"Item";if(this.action==="remove"){const template=this.dataset.itemRemovedTemplate||"__TITLE__ removed from bag";return fillCartStatusTemplate(template,{title})}if(this.action==="update"||this.action==="set_virtual_set"||this.action==="add_virtual_set"&&this.isCart){const quantity=this.readAnnouncedQuantity();if(quantity===0){const removedTemplate=this.dataset.itemRemovedTemplate||"__TITLE__ removed from bag";return fillCartStatusTemplate(removedTemplate,{title})}if(quantity!==null){const template=this.dataset.quantityUpdatedTemplate||"__TITLE__ quantity updated to __QUANTITY__";return fillCartStatusTemplate(template,{title,quantity})}}if((this.action==="add"||this.action==="add_virtual_set")&&this.isCart){const template=this.dataset.itemAddedTemplate||"__TITLE__ was added to bag";return fillCartStatusTemplate(template,{title})}return null}readAnnouncedQuantity(){if(!this.form)return null;if(this.action==="set_virtual_set"){const quantityInput=this.form.querySelector('input[name^="items["][name$="[quantity]"]');if(!quantityInput)return null;const value2=parseInt(quantityInput.value,10);return Number.isFinite(value2)?value2:null}if(this.action==="add_virtual_set"){const displayInput=this.closest("[data-line-key]")?.querySelector(`${this.SELECTORS.updatesInput}:not(${this.SELECTORS.qtyFixedInput})`);if(!displayInput)return null;const current=parseInt(displayInput.value,10);return Number.isFinite(current)?current+1:null}const updatesInput=this.form.querySelector(`${this.SELECTORS.updatesInput}:not(${this.SELECTORS.qtyFixedInput})`);if(!updatesInput)return null;const value=parseInt(updatesInput.value,10);return Number.isFinite(value)?value:null}fetchConfig(type="json"){return{method:"POST",headers:{"Content-Type":"application/json",Accept:`application/${type}`}}}async rerenderCartRecommendSections(){const roots=document.querySelectorAll(this.SELECTORS.cartRecommendRoot),sectionIds=collectSectionIds(roots);sectionIds.length!==0&&await renderSections(sectionIds.map(id=>({id})))}disconnectedCallback(){}};customElements.get("c-product-form")||customElements.define("c-product-form",CProductForm),initAlgoliaInsights()})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["product-images"]&&!Shopify.designMode))try{(()=>{var CARD_SELECTOR=".card-product:not(.set-to-compose)",ZONE_CONFIGS=[{selector:".card-product__meta",cssVar:"--card-meta-min-height"},{selector:".card-product__price",cssVar:"--card-price-min-height"}];function groupIndicesByRow(tops){const rows=[];for(const[index,top]of tops.entries()){const row=rows.find(group=>{const first=group[0];return first!==void 0&&Math.abs((tops[first]??0)-top)<=1});row?row.push(index):rows.push([index])}return rows}function alignProductCardZones(root){const cards=Array.from(root.querySelectorAll(CARD_SELECTOR));if(cards.length===0)return;const zones=ZONE_CONFIGS.map(({selector})=>cards.map(card=>card.querySelector(selector)));
28for(const[zoneIndex,elements]of zones.entries()){const cssVar=ZONE_CONFIGS[zoneIndex]?.cssVar;if(cssVar!==void 0)for(const el of elements)el?.style.setProperty(cssVar,"0px")}const tops=cards.map(card=>card.offsetTop),heights=zones.map(elements=>elements.map(el=>el?.scrollHeight??0)),rows=groupIndicesByRow(tops);for(const[zoneIndex,elements]of zones.entries()){const cssVar=ZONE_CONFIGS[zoneIndex]?.cssVar,zoneHeights=heights[zoneIndex];if(!(cssVar===void 0||zoneHeights===void 0))for(const row of rows){let maxHeight=0;for(const index of row)maxHeight=Math.max(maxHeight,zoneHeights[index]??0);const value=`${String(maxHeight)}px`;for(const index of row)elements[index]?.style.setProperty(cssVar,value)}}}var HOVER_IMAGE_SELECTOR=".card-product_image.is-hover-active figure:nth-child(even) img",NEAR_VIEWPORT_MARGIN="400px",seen=new WeakSet,observer=null;function whenIdle(task){if(typeof requestIdleCallback=="function"){requestIdleCallback(task,{timeout:2e3});return}window.setTimeout(task,200)}function decodeWhenLoaded(image){const decode=()=>whenIdle(()=>{image.decode().catch(()=>{})});if(image.complete&&image.naturalWidth>0){decode();return}image.addEventListener("load",decode,{once:!0})}function nearViewportObserver(){return observer||(typeof IntersectionObserver!="function"?null:(observer=new IntersectionObserver(entries=>{for(const entry of entries)entry.isIntersecting&&(observer?.unobserve(entry.target),decodeWhenLoaded(entry.target))},{rootMargin:NEAR_VIEWPORT_MARGIN}),observer))}function predecodeHoverVisuals(root){const images=root.querySelectorAll(HOVER_IMAGE_SELECTOR);if(images.length===0)return;const io=nearViewportObserver();for(const image of images)if(!seen.has(image)){if(seen.add(image),!io){decodeWhenLoaded(image);continue}io.observe(image)}}var GalleryListBase=class extends HTMLElement{constructor(){super(...arguments),this.embla=null,this.sliderToScrollMobile="auto",this.sliderToScrollDesktop="auto",this.parentContainer=null,this.viewport=null,this.container=null,this.prevButton=null,this.nextButton=null,this.progressNode=null,this.prevContainer=null,this.nextContainer=null,this.firstSlideObserver=null,this.zoneAlignObserver=null,this.isAligningZones=!1,this.lastAlignedWidth=0,this.onPrevClick=()=>this.embla?.scrollPrev(),this.onNextClick=()=>this.embla?.scrollNext(),this.onPrevMouseMove=e=>this.followMouse(e,this.prevButton),this.onNextMouseMove=e=>this.followMouse(e,this.nextButton),this.onPrevMouseLeave=()=>this.resetButton(this.prevButton),this.onNextMouseLeave=()=>this.resetButton(this.nextButton),this.alignZones=()=>{if(!(!this.container||this.isAligningZones)){this.isAligningZones=!0;try{alignProductCardZones(this.container),predecodeHoverVisuals(this.container)}finally{this.isAligningZones=!1}}}}followMouse(e,button){if(!button)return;const rect=e.currentTarget.getBoundingClientRect(),offsetX=e.clientX-rect.left-rect.width/2,offsetY=e.clientY-rect.top-rect.height/2;button.style.transform=`translate(${offsetX}px, ${offsetY}px)`}resetButton(button){button&&(button.style.transform="")}onScroll(){}connectedCallback(){this.parentContainer=this.closest("c-gallery-container"),this.viewport=this.querySelector(".embla__viewport"),this.container=this.querySelector(".embla__container"),this.prevButton=this.querySelector(".embla__prev"),this.nextButton=this.querySelector(".embla__next"),this.progressNode=this.querySelector(".embla__progress__bar"),this.prevContainer=this.querySelector(".container_embla__prev"),this.nextContainer=this.querySelector(".container_embla__next"),this.sliderToScrollMobile=this.dataset.slidesToScrollMobile||"auto",this.sliderToScrollDesktop=this.dataset.slidesToScrollDesktop||"auto",this.parentContainer?.classList.contains("v-slider")&&(this.initEmbla(),this.bindProgress(),this.bindMouseFollow()),this.classList.remove("shimmer"),this.bindFirstSlideAnimation(),this.bindZoneAlignment()}bindZoneAlignment(){const container=this.container;container&&(this.alignZones(),this.zoneAlignObserver=new ResizeObserver(entries=>{const width=Math.round(entries[0]?.contentRect.width??0);width===0||width===this.lastAlignedWidth||(this.lastAlignedWidth=width,this.alignZones())}),this.lastAlignedWidth=Math.round(container.getBoundingClientRect().width),this.zoneAlignObserver.observe(container),document.fonts.ready.then(()=>this.alignZones()),this.embla?.on("reinit",()=>this.alignZones()).on("resize",()=>this.alignZones()))}bindFirstSlideAnimation(){const firstSlide=this.querySelector(".embla__slide:first-child");firstSlide&&(this.firstSlideObserver=new IntersectionObserver(entries=>{if(!entries[0].isIntersecting)return;this.firstSlideObserver?.disconnect(),this.firstSlideObserver=null;const quickBuyContainer=firstSlide.querySelector(".card-product-quick-buy__container");quickBuyContainer&&(quickBuyContainer.classList.add("is-animate-quick-buy"),setTimeout(()=>quickBuyContainer.classList.remove("is-animate-quick-buy"),1400))},{threshold:.8}),this.firstSlideObserver.observe(firstSlide))}bindMouseFollow(){this.prevContainer?.addEventListener("mousemove",this.onPrevMouseMove),this.prevContainer?.addEventListener("mouseleave",this.onPrevMouseLeave),this.nextContainer?.addEventListener("mousemove",this.onNextMouseMove),this.nextContainer?.addEventListener("mouseleave",this.onNextMouseLeave)}initEmbla(){!this.viewport||!this.container||(this.embla=EmblaCarousel(this.viewport,{dragFree:!1,active:!0,slidesToScroll:this.sliderToScrollMobile,"(min-width: 1024px)":{active:!1,dragFree:!0,slidesToScroll:this.sliderToScrollDesktop}},[EmblaCarouselAutoHeight()]),this.prevButton?.addEventListener("click",this.onPrevClick),this.nextButton?.addEventListener("click",this.onNextClick))}bindProgress(){if(!this.embla||!this.progressNode)return;const progressNode=this.progressNode,applyProgress=()=>
28{if(!this.embla)return;const snapCount=this.embla.scrollSnapList().length,selected=this.embla.selectedScrollSnap();progressNode.style.width=`${100/snapCount}%`,progressNode.style.transform=`translate3d(${selected*100}%,0px,0px)`,this.prevButton?.parentElement?.toggleAttribute("data-disabled",!this.embla.canScrollPrev()),this.nextButton?.parentElement?.toggleAttribute("data-disabled",!this.embla.canScrollNext()),this.onScroll()};applyProgress(),this.embla.on("reinit",()=>applyProgress()).on("resize",()=>applyProgress()).on("scroll",()=>applyProgress()).on("slidefocus",()=>applyProgress())}disconnectedCallback(){this.zoneAlignObserver?.disconnect(),this.zoneAlignObserver=null,this.lastAlignedWidth=0,this.embla?.destroy(),this.embla=null,this.firstSlideObserver?.disconnect(),this.firstSlideObserver=null,this.prevButton?.removeEventListener("click",this.onPrevClick),this.nextButton?.removeEventListener("click",this.onNextClick),this.prevContainer?.removeEventListener("mousemove",this.onPrevMouseMove),this.prevContainer?.removeEventListener("mouseleave",this.onPrevMouseLeave),this.nextContainer?.removeEventListener("mousemove",this.onNextMouseMove),this.nextContainer?.removeEventListener("mouseleave",this.onNextMouseLeave)}},GalleryList=class extends GalleryListBase{};window.customElements.get("c-gallery-list")||window.customElements.define("c-gallery-list",GalleryList)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["quick-buy"]&&!Shopify.designMode))try{(()=>{var SECTION_PREFIX="shopify-section-";function getSectionId(el){return el?.id?.startsWith(SECTION_PREFIX)?el.id.slice(SECTION_PREFIX.length):null}function closestSectionId(el){const wrapper=el?.closest(`[id^="${SECTION_PREFIX}"]`);return getSectionId(wrapper)}function collectSectionIds(elements){const ids=new Set;for(const el of elements){const id=closestSectionId(el);id&&ids.add(id)}return[...ids]}function buildUrl(base,params){const url=new URL(base??window.location.pathname,window.location.origin);for(const[key,value]of Object.entries(params))url.searchParams.set(key,value);return url.toString()}function withQuery(params,query){return query?{...Object.fromEntries(Object.entries(query).map(([k,v])=>[k,String(v)])),...params}:params}async function fetchSections(ids,options={}){const url=buildUrl(options.url,withQuery({sections:ids.join(",")},options.query)),response=await fetch(url,{credentials:"same-origin"});if(!response.ok)throw new Error(`Sections fetch ${response.status}`);return response.json()}async function fetchSectionHTML(id,options={}){const url=buildUrl(options.url,withQuery({section_id:id},options.query)),response=await fetch(url,{credentials:"same-origin"});if(!response.ok)throw new Error(`Section fetch ${response.status}`);return response.text()}function swapInner(html,selector){const selectors=Array.isArray(selector)?selector:[selector],doc=new DOMParser().parseFromString(html,"text/html");selectors.forEach(sel=>{document.querySelectorAll(sel).forEach(element=>{const source=element.dataset.id?doc.querySelector(`${sel}[data-id="${element.dataset.id}"]`):doc.querySelector(sel);source&&(element.innerHTML=source.innerHTML)})})}function swapSection(id,html){const live=document.getElementById(`${SECTION_PREFIX}${id}`);if(!live)return;const doc=new DOMParser().parseFromString(html,"text/html"),next=doc.getElementById(`${SECTION_PREFIX}${id}`)||doc.body.firstElementChild;next instanceof HTMLElement?live.replaceWith(next):live.hidden=!0}
28async function renderSections(targets,options={}){if(targets.length===0)return;const map=options.sections??await fetchSections(targets.map(t=>t.id),options);for(const target of targets){const html=map[target.id];typeof html=="string"&&(target.selector?swapInner(html,target.selector):swapSection(target.id,html))}}async function renderSection(target,options={}){const html=await fetchSectionHTML(target.id,options);target.selector?swapInner(html,target.selector):swapSection(target.id,html)}var ERROR_MESSAGE_SELECTOR="[data-cart-limit-error-message]",ERROR_TEXT_SELECTOR="[data-cart-limit-error-text]",OPEN_ENGRAVING_PANEL_SELECTOR="c-engraving-panel.is-open",SEARCH_DIALOG_SELECTOR="dialog[data-search-dialog]",QUANTITY_LIMIT_PATTERNS=[/can'?t add more/i,/maximum allowed quantity/i,/maximum quantity/i,/quantity.*exceeded/i,/only add \d+/i];function getErrorMessageEl(){return document.querySelector(ERROR_MESSAGE_SELECTOR)}function getDefaultMessage(){return window.cartStrings?.addToCartLimitError??"The maximum allowed quantity for this product has been exceeded."}function isCartQuantityLimitError(status,description){if(status!==422)return!1;const normalized=description.trim();return normalized.length===0?!0:QUANTITY_LIMIT_PATTERNS.some(pattern=>pattern.test(normalized))}function closeOpenEngravingPanels(){document.querySelectorAll(OPEN_ENGRAVING_PANEL_SELECTOR).forEach(panel=>{panel.close()})}function closeHeaderSearchIfOpen(){const openDialogs=document.querySelectorAll(`${SEARCH_DIALOG_SELECTOR}[open]`);openDialogs.length!==0&&(document.documentElement.classList.remove("is-overflow-hidden"),openDialogs.forEac
28h(dialog=>{dialog.close()}))}function showCartLimitError(message){closeHeaderSearchIfOpen();const errorMessage=getErrorMessageEl();if(!errorMessage)return;const textEl=errorMessage.querySelector(ERROR_TEXT_SELECTOR);textEl&&(textEl.textContent=message??getDefaultMessage()),errorMessage.classList.remove("hidden"),errorMessage.removeAttribute("hidden"),errorMessage.setAttribute("aria-hidden","false"),closeOpenEngravingPanels(),window.scrollTo(0,0)}function hideCartLimitError(){const errorMessage=getErrorMessageEl();if(!errorMessage)return;const textEl=errorMessage.querySelector(ERROR_TEXT_SELECTOR);textEl&&(textEl.textContent=""),errorMessage.classList.add("hidden"),errorMessage.setAttribute("hidden",""),errorMessage.setAttribute("aria-hidden","true")}var CART_LIVE_STATUS_ID="cart-live-status",FOCUS_ANNOUNCE_DELAY_MS=300;function getOrCreateCartLiveRegion(){let region=document.getElementById(CART_LIVE_STATUS_ID);return region instanceof HTMLElement||(region=document.createElement("div"),region.id=CART_LIVE_STATUS_ID,region.className="sr-only form-status",region.setAttribute("role","status"),region.setAttribute("aria-live","polite"),region.setAttribute("aria-atomic","true"),document.body.appendChild(region)),region}function announceCartStatus(message,options={}){const trimmed=message.trim();if(!trimmed)return;const shouldFocus=options.focus!==!1,region=getOrCreateCartLiveRegion();if(shouldFocus){region.setAttribute("aria-live","off"),region.setAttribute("tabindex","-1"),region.textContent=trimmed,region.focus({preventScroll:!0}),window.setTimeout(()=>{region.setAttribute("aria-live","polite")},FOCUS_ANNOUNCE_DELAY_MS);return}region.textContent="",requestAnimationFrame(()=>{region.textContent=trimmed})}function fillCartStatusTemplate(template,values){let result=template;return values.title!==void 0&&(result=result.replace(/__TITLE__/g,values.title)),values.quantity!==void 0&&(result=result.replace(/__QUANTITY__/g,String(values.quantity))),result}var ENDPOINT="https://insights.algolia.io/1/events",AGENT="diptyque-theme",TOKEN_KEY="algolia_user_token",PIXEL_CONFIG_KEY="algolia_config",PIXEL_CLICK_KEY="algolia_analytics_clicked_objects",PIXEL_CLICK_MAX=50,MAX_OBJECT_IDS=20,THEME_EMITS_ADD_TO_CART=!0,OBJECT_ID_SELECTOR="[data-algolia-object-id]",CLICK_HOOKS="[data-algolia-click], [data-algolia-convert]";function readConfig(){const data=document.body?.dataset;return!data?.algoliaAppId||!data.algoliaApiKey||!data.algoliaIndex?null:{appId:data.algoliaAppId,apiKey:data.algoliaApiKey,index:data.algoliaIndex}}function readStorage(key){try{return window.localStorage.getItem(key)}catch{return null}}function writeStorage(key,value){try{window.localStorage.setItem(key,value)}catch{}}function randomUserToken(){const bytes=new Uint8Array(16);return crypto.getRandomValues(bytes),`anonymous-${Array.from(bytes,byte=>byte.toString(36).padStart(2,"0")).join("")}`}var cachedUserToken=null;function userToken(){if(cachedUserToken)return cachedUserToken;const stored=readStorage(TOKEN_KEY);return cachedUserToken=stored||randomUserToken(),stored||writeStorage(TOKEN_KEY,cachedUserToken),cachedUserToken}function authenticatedUserToken(){return document.body?.dataset.algoliaAuthenticatedUserToken||void 0}function normalizeObjectIDs(values){const ids=new Set;for(const value of values){const id=String(value??"").trim();id&&ids.add(id)}return Array.from(ids).slice(0,MAX_OBJECT_IDS)}function send(config,event){const params=new URLSearchParams({"X-Algolia-Application-Id":config.appId,"X-Algolia-API-Key":config.apiKey,"X-Algolia-Agent":AGENT}),url=`${ENDPOINT}?${params}`,body=JSON.stringify({events:[event]});navigator.sendBeacon?.(url,body)||fetch(url,{method:"POST",body,keepalive:!0}).catch(()=>{})}function track(config,objectIDs,event){objectIDs.length!==0&&send(config,{...event,index:config.index,objectIDs,userToken:userToken(),authenticatedUserToken:authenticatedUserToken()})}function writePixelConfig(config){writeStorage(PIXEL_CONFIG_KEY,JSON.stringify({app_id:config.appId,search_api_key:config.apiKey,index_name:config.index,user_token:userToken()}))}function recordClickForPixel(config,objectIDs,productId){const stored=readStorage(PIXEL_CLICK_KEY);let records=[];try{const parsed=stored?JSON.parse(stored):[];Array.isArray(parsed)&&(records=parsed)}catch{records=[]}records.push({index:config.index,objectIDs,productId}
28),writeStorage(PIXEL_CLICK_KEY,JSON.stringify(records.slice(-PIXEL_CLICK_MAX)))}function readObjectId(element){const above=element?.closest(OBJECT_ID_SELECTOR);return above?.dataset.algoliaObjectId?above.dataset.algoliaObjectId:element?.querySelector(OBJECT_ID_SELECTOR)?.dataset.algoliaObjectId??""}function readProductId(element){const above=element?.closest("[data-algolia-product-id]");return above?.dataset.algoliaProductId?above.dataset.algoliaProductId:element?.querySelector("[data-algolia-product-id]")?.dataset.algoliaProductId??""}function onDocumentClick(event){const target=event.target;if(!(target instanceof Element))return;const hook=target.closest(CLICK_HOOKS);if(!hook)return;const config=readConfig();if(!config)return;const objectIDs=normalizeObjectIDs([readObjectId(hook)]);objectIDs.length!==0&&(writePixelConfig(config),recordClickForPixel(config,objectIDs,readProductId(hook)),!hook.matches("[data-algolia-convert]")&&track(config,objectIDs,{eventType:"click",eventName:"Product Clicked"}))}function onCartAddSuccess(event){if(!THEME_EMITS_ADD_TO_CART)return;const target=event.target;if(!(target instanceof Element))return;const config=readConfig();if(!config)return;const objectIDs=normalizeObjectIDs([readObjectId(target)]);objectIDs.length!==0&&(writePixelConfig(config),track(config,objectIDs,{eventType:"conversion",eventSubtype:"addToCart",eventName:"Add To Cart"}))}function initAlgoliaInsights(){typeof window>"u"||window.algoliaInsightsReady||(window.algoliaInsightsReady=!0,document.addEventListener("click",onDocumentClick,!0),document.addEventListener("cart:add-success",onCartAddSuccess))}var CProductForm=class extends HTMLElement{constructor(){super(...arguments),this.SELECTORS={form:"form",submitButton:'button[type="submit"]',updatesInput:'input[name^="updates["]',qtyFixedInput:"[data-qty-fixed]",qtyButton:"[data-qty-btn]",notifyMeButton:"[data-notify-me-button]",notifyWidget:'.gw-float-widget[type="button"]',loaderId:"full-page-loader",cartRecommendRoot:"[data-cart-recommend-root]",samplesSection:"[data-samples-section]",samplesRoot:"[data-cart-samples]",packagingRoot:"[data-cart-packaging]",giftLine:"[data-gift-line]",headerCartLink:".header__action-link--cart",popupAtcContainer:"[data-popup-atc-container]",cartItems:"[data-cart-items]",cartLine:"[data-cart-items] [data-line-key]",engravingPanelCart:".engraving-panel-container-cart",cartSummary:"[data-cart-summary]",cartSummarySection:".section-cart-summary"},this.form=null,this.countCartItems=null,this.formId=null,this.btnSubmit=null,this.btnSubmitAlreadyInfos=null,this.type=null,this.isCart=null,this.itemKey=null,this.action="add",this.errorMessages={},this.quantitySnapshot=null,this.samplesSectionId=null,this.sectionsRenderSamples=[],this.sectionsRender=[],this.hasConnected=!1,this.submitForm=async()=>{if(!this.form)return;this.clearCartError();const hiddenElements=Array.from(this.form.querySelectorAll("input, select, textarea")).filter(el=>el.offsetParent===null&&el.type!=="hidden");hiddenElements.forEach(el=>{el.disabled=!0});const formData=new FormData(this.form);hiddenElements.forEach(el=>{el.disabled=!1});const config=this.fetchConfig("javascript"),targets=this.withGiftLineTarget(this.isCart?this.getCartPageTargets():this.sectionsRender),sectionsParam=targets.map(target=>target.id).join(",");if(formData.set("sections",sectionsParam),this.action==="change"&&this.itemKey){const properties={};for(const[key,value]of formData.entries())if(key.includes("properties")){const propKey=key.match(/\[(.*?)\]/g)?.pop()?.replace(/[[\]]/g,"");propKey&&(properties[propKey]=value)}config.body=JSON.stringify({id:this.itemKey,properties,sections:sectionsParam})}else config.body=formData,delete config.headers["Content-Type"];config.headers["X-Requested-With"]="XMLHttpRequest";try{const endpoints={add:"cart/add.js",change:"cart/change.js",update:"cart/update.js",remove:"cart/update.js",add_virtual_set:"cart/add.js"},endpoint=endpoints[this.action]??endpoints.add;if(this.action==="set_virtual_set"){await this.setVirtualSetQuantity(formData,sectionsParam,targets);return}const response=await fetch((window.Shopify?.routes?.root||"/")+endpoint,config);if(!response.ok){const errorData=await response.json().catch(()=>({})),rawMessage=errorData.description||errorData.message||`Erreur ${response.status}`,message=this.errorMessages[rawMessage]||rawMessage;throw isCartQuantityLimitError(response.status,rawMessage)?showCartLimitError():showCartLimitError(message),new Error(message)}const data=await response.json();hideCartLimitError(),this.quantitySnapshot=null;const statusAnnouncement=this.buildCartMutationAnnouncement();await renderSections(targets,{sections:data.sections}),statusAnnouncement&&announceCartStatus(statusAnnouncement),this.dispatchEvent(new CustomEvent("cart:add-success",{bubbles:!0,detail:{data,action:this.action}})),this.isCart&&(this.renderSampleSection(),await this.rerenderCartRecommendSections())}catch(error){this.restoreQuantitySnapshot(),console.error(error.message)}}}readDom(){this.form=this.querySelector(this.SELECTORS.form),this.countCartItems=this.dataset.countCartItems||null,this.formId=this.form?.id||null,this.btnSubmit=this.querySelector(this.SELECTORS.submitButton),this.btnSubmitAlreadyInfos=document.querySelector(`button[form="${this.formId}"]`),this.type=this.dataset.type||null,this.isCart=this.dataset.isCart||null,this.itemKey=this.dataset.itemKey||null,this.action=this.dataset.action||"add",this.errorMessages={error_product_gift_cart:this.dataset.errorProductGiftCart||""},this.samplesSectionId=this.getSamplesSectionId(),this.sectionsRenderSamples=this.samplesSectionId?[{id:this.samplesSectionId,selector:[this.SELECTORS.samplesRoot,this.SELECTORS.packagingRoot]}]:[],this.sectionsRender=[{id:"header",selector:[this.SELECTORS.headerCartLink]},{id:"popup-add-to-cart",selector:[this.SELECTORS.popupAtcContainer]}]}getSamplesSectionId(){const sectionChild=document.querySelector(this.SELECTORS.samplesSection);return closestSectionId(sectionChild)}getCartSummarySectionId(){return closestSectionId(document.querySelector(this.SELECTORS.cartSummarySection))??closestSectionId(document.querySelector(this.SELECTORS.cartSummary))}getCartPageTargets(){const cartSummarySectionId=this.getCartSummarySectionId();return[{id:"header",selector:[this.SELECTORS.headerCartLink]},{id:"popup-add-to-cart",selector:[this.SELECTORS.popupAtcContainer]},{id:"main-cart",selector:[this.SELECTORS.cartItems,this.SELECTORS.engravingPanelCart]},...cartSummarySectionId?[{id:cartSummarySectionId}]:[]]}withGiftLineTarget(targets){if(!this.form?.querySelector(this.SELECTORS.giftLine))return targets;const id=closestSectionId(this);if(!id)return targets;const existing=targets.find(target=>target.id===id);if(!existing)return[...targets,{id,selector:[this.SELECTORS.giftLine]}];if(!existing.selector)return targets;const selectors=Array.isArray(existing.selector)?existing.selector:[existing.selector];return selectors.includes(this.SELECTORS.giftLine)?targets:targets.map(target=>target===existing?{...target,selector:[...selectors,this.SELECTORS.giftLine]}:target)}connectedCallback(){this.hasConnected||(this.hasConnected=!0,setTimeout(()=>{this.readDom(),this.initNotifyMe(),this.checkNotifyMeHash()},0),this.addEventListener("submit",async e=>{if(this.readDom(),!this.form)return;e.preventDefault(),this.btnSubmit&&this.btnSubmit.setAttribute("disabled","true"),this.btnSubmitAlreadyInfos&&this.btnSubmitAlreadyInfos.setAttribute("disabled","true");const loader=document.getElementById(this.SELECTORS.loaderId);loader&&loader.setAttribute("aria-hidden","false"),await this.submitForm(
28),loader&&loader.setAttribute("aria-hidden","true"),this.btnSubmit&&this.btnSubmit.removeAttribute("disabled"),this.btnSubmitAlreadyInfos&&this.btnSubmitAlreadyInfos.removeAttribute("disabled")}),this.addEventListener("focusin",e=>{if(this.readDom(),this.action!=="update")return;e.target.name?.startsWith("updates[")&&this.captureQuantitySnapshot()}),this.addEventListener("change",e=>{e.target.name?.includes("updates[")&&(this.readDom(),this.form?.requestSubmit())}),this.addEventListener("click",e=>{const button=e.target.closest(this.SELECTORS.qtyButton);if(!button||(this.readDom(),!this.form))return;e.preventDefault();const step=parseInt(button.getAttribute("data-qty-step")||"0",10),inputs=Array.from(this.form.querySelectorAll(this.SELECTORS.updatesInput)),stepped=inputs.filter(el=>!el.matches(this.SELECTORS.qtyFixedInput)),fixed=inputs.filter(el=>el.matches(this.SELECTORS.qtyFixedInput));let blockedByLimit=!1;if(this.captureQuantitySnapshot(),stepped.forEach(el=>{const currentVal=parseInt(el.value||"0",10),maxAttr=el.getAttribute("max"),maxQuantity=maxAttr?parseInt(maxAttr,10):Number.NaN,nextVal=currentVal+step;if(step>0&&Number.isFinite(maxQuantity)&&nextVal>maxQuantity){blockedByLimit=!0;return}el.value=Math.max(0,nextVal).toString()}),blockedByLimit){this.quantitySnapshot=null,showCartLimitError();return}const parentRemains=stepped.some(el=>parseInt(el.value||"0",10)>0);fixed.forEach(el=>{el.value=parentRemains?"1":"0"}),this.form.requestSubmit()}))}initNotifyMe(){const notifyMeBtn=this.querySelector(this.SELECTORS.notifyMeButton);if(!notifyMeBtn)return;const href=notifyMeBtn.getAttribute("href")||"";href&&!href.includes("#notify-me")&&notifyMeBtn.setAttribute("href",`${href}#notify-me`);const bindNotifyWidget=(retries=20,interval=300)=>{const widget=document.querySelector(this.SELECTORS.notifyWidget);widget?(widget.style.display="none",notifyMeBtn.addEventListener("click",event=>{event.preventDefault(),widget.click()})):retries>0&&setTimeout(()=>bindNotifyWidget(retries-1,interval),interval)};bindNotifyWidget()}checkNotifyMeHash(){if(window.location.hash!=="#notify-me")return;const autoOpenNotifyWidget=(retries=20,interval=300)=>{const widget=document.querySelector(this.SELECTORS.notifyWidget);widget?(widget.click(),history.replaceState(null,"",window.location.pathname+window.location.search)):retries>0&&setTimeout(()=>autoOpenNotifyWidget(retries-1,interval),interval)};autoOpenNotifyWidget()}async renderSampleSection(){try{for(const section of this.sectionsRenderSamples)await renderSection(section)}catch(error){console.error("[CartSamples] section render error:",error),window.location.reload()}}async setVirtualSetQuantity(formData,sectionsParam,targets){const removals=new FormData,additions=new FormData;for(const[key,value]of formData.entries())key.startsWith("updates[")?removals.append(key,value):key.startsWith("items[")&&additions.append(key,value);if(![...additions.keys()].length)throw new Error("[VirtualSet] aucun items[\u2026] \xE0 reposer");additions.set("sections",sectionsParam);const order=this.readCartOrder(),root=window.Shopify?.routes?.root||"/",headers={"X-Requested-With":"XMLHttpRequest"};if([...removals.keys()].length){const removed=await fetch(`${root}cart/update.js`,{method:"POST",headers,body:removals});if(!removed.ok)throw new Error(await this.readCartError(removed))}const added=await fetch(`${root}cart/add.js`,{method:"POST",headers,body:additions});if(!added.ok)throw new Error(await this.readCartError(added));const data=await added.json();hideCartLimitError(),this.quantitySnapshot=null;const statusAnnouncement=this.buildCartMutationAnnouncement();await renderSections(targets,{sections:data.sections}),this.restoreCartOrder(order),statusAnnouncement&&announceCartStatus(statusAnnouncement),this.dispatchEvent(new CustomEvent("cart:add-success",{bubbles:!0,detail:{data,action:this.action}})),this.isCart&&(this.renderSampleSection(),await this.rerenderCartRecommendSections())}readCartOrder(){return[...document.querySelectorAll(this.SELECTORS.cartLine)].flatMap(card=>card.dataset.lineKey?[card.dataset.lineKey]:[])}restoreCartOrder(order){if(order.length<2)return;const cards=[...document.querySelectorAll(this.SELECTORS.cartLine)],parent=cards[0]?.parentElement;
28if(!parent)return;const byKey=new Map(cards.filter(card=>card.parentElement===parent&&card.dataset.lineKey).map(card=>[card.dataset.lineKey,card]));for(const key of order){const card=byKey.get(key);card&&(parent.appendChild(card),byKey.delete(key))}for(const card of byKey.values())parent.appendChild(card)}async readCartError(response){const errorData=await response.json().catch(()=>({})),rawMessage=errorData.description||errorData.message||`Erreur ${response.status}`;return isCartQuantityLimitError(response.status,rawMessage)?showCartLimitError():showCartLimitError(this.errorMessages[rawMessage]||rawMessage),rawMessage}captureQuantitySnapshot(){!this.form||this.action!=="update"||(this.quantitySnapshot=new Map,this.form.querySelectorAll(this.SELECTORS.updatesInput).forEach(input=>{this.quantitySnapshot.set(input.name,input.value)}))}restoreQuantitySnapshot(){!this.form||!this.quantitySnapshot||(this.form.querySelectorAll(this.SELECTORS.updatesInput).forEach(input=>{const saved=this.quantitySnapshot.get(input.name);saved!==void 0&&(input.value=saved)}),this.quantitySnapshot=null)}clearCartError(){hideCartLimitError()}buildCartMutationAnnouncement(){const title=this.dataset.productTitle?.trim()||"Item";if(this.action==="remove"){const template=this.dataset.itemRemovedTemplate||"__TITLE__ removed from bag";return fillCartStatusTemplate(template,{title})}if(this.action==="update"||this.action==="set_virtual_set"||this.action==="add_virtual_set"&&this.isCart){const quantity=this.readAnnouncedQuantity();if(quantity===0){const removedTemplate=this.dataset.itemRemovedTemplate||"__TITLE__ removed from bag";return fillCartStatusTemplate(removedTemplate,{title})}if(quantity!==null){const template=this.dataset.quantityUpdatedTemplate||"__TITLE__ quantity updated to __QUANTITY__";return fillCartStatusTemplate(template,{title,quantity})}}if((this.action==="add"||this.action==="add_virtual_set")&&this.isCart){const template=this.dataset.itemAddedTemplate||"__TITLE__ was added to bag";return fillCartStatusTemplate(template,{title})}return null}readAnnouncedQuantity(){if(!this.form)return null;if(this.action==="set_virtual_set"){const quantityInput=this.form.querySelector('input[name^="items["][name$="[quantity]"]');if(!quantityInput)return null;const value2=parseInt(quantityInput.value,10);return Number.isFinite(value2)?value2:null}if(this.action==="add_virtual_set"){const displayInput=this.closest("[data-line-key]")?.querySelector(`${this.SELECTORS.updatesInput}:not(${this.SELECTORS.qtyFixedInput})`);if(!displayInput)return null;const current=parseInt(displayInput.value,10);return Number.isFinite(current)?current+1:null}const updatesInput=this.form.querySelector(`${this.SELECTORS.updatesInput}:not(${this.SELECTORS.qtyFixedInput})`);if(!updatesInput)return null;const value=parseInt(updatesInput.value,10);return Number.isFinite(value)?value:null}fetchConfig(type="json"){return{method:"POST",headers:{"Content-Type":"application/json",Accept:`application/${type}`}}}async rerenderCartRecommendSections(){const roots=document.querySelectorAll(this.SELECTORS.cartRecommendRoot),sectionIds=collectSectionIds(roots);sectionIds.length!==0&&await renderSections(sectionIds.map(id=>({id})))}disconnectedCallback(){}};customElements.get("c-product-form")||customElements.define("c-product-form",CProductForm),initAlgoliaInsights()})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["related-products-v2"]&&!Shopify.designMode))try{(()=>{var SECTION_PREFIX="shopify-section-";function buildUrl(base,params){const url=new URL(base??window.location.pathname,window.location.origin);for(const[key,value]of Object.entries(params))url.searchParams.set(key,value);return url.toString()}function withQuery(params,query){return query?{...Object.fromEntries(Object.entries(query).map(([k,v])=>[k,String(v)])),...params}:params}async function fetchSections(ids,options={}){const url=buildUrl(options.url,withQuery({sections:ids.join(",")},options.query)),response=await fetch(url,{credentials:"same-origin"});if(!response.ok)throw new Error(`Sections fetch ${response.status}`);return response.json()}function swapInner(html,selector){const selectors=Array.isArray(selector)?selector:[selector],doc=new DOMParser().parseFromString(html,"text/html");
28selectors.forEach(sel=>{document.querySelectorAll(sel).forEach(element=>{const source=element.dataset.id?doc.querySelector(`${sel}[data-id="${element.dataset.id}"]`):doc.querySelector(sel);source&&(element.innerHTML=source.innerHTML)})})}function swapSection(id,html){const live=document.getElementById(`${SECTION_PREFIX}${id}`);if(!live)return;const doc=new DOMParser().parseFromString(html,"text/html"),next=doc.getElementById(`${SECTION_PREFIX}${id}`)||doc.body.firstElementChild;next instanceof HTMLElement?live.replaceWith(next):live.hidden=!0}async function renderSections(targets,options={}){if(targets.length===0)return;const map=options.sections??await fetchSections(targets.map(t=>t.id),options);for(const target of targets){const html=map[target.id];typeof html=="string"&&(target.selector?swapInner(html,target.selector):swapSection(target.id,html))}}var EMBLA_OPTIONS={loop:!1,dragFree:!0,align:"start",watchDrag:!0,containScroll:"trimSnaps"},OVERFLOW_EPSILON_PX=1,ARROW_BREAKPOINTS=[{minWidth:1440,maxVisibleItems:5},{minWidth:1024,maxVisibleItems:3},{minWidth:0,maxVisibleItems:Number.POSITIVE_INFINITY}];function getMaxVisibleItems(windowWidthPx){for(const breakpoint of ARROW_BREAKPOINTS)if(windowWidthPx>=breakpoint.minWidth)return breakpoint.maxVisibleItems;return Number.POSITIVE_INFINITY}function getEmblaFactory(){if(typeof EmblaCarousel=="function")return EmblaCarousel;const fromWindow=window.EmblaCarousel;return typeof fromWindow=="function"?fromWindow:null}var RelatedProductsV2=class extends HTMLElement{constructor(){super(),this.relatedProducts=[],this.viewportNode=null,this.containerNode=null,this.emblaApi=null,this.sectionsRender=[],this.prevButton=null,this.nextButton=null,this.prevContainer=null,this.nextContainer=null,this.resizeObserver=null,this.lastMeasureKey="",this.emblaRetryTimeoutId=0,this.onPrevClick=()=>{if(this.getArrowState().canPrev){if(this.emblaApi?.canScrollPrev()){this.emblaApi.scrollPrev();return}this.ensureEmblaScroll("prev")}},this.onNextClick=()=>{if(this.getArrowState().canNext){if(this.emblaApi?.canScrollNext()){this.emblaApi.scrollNext();return}this.ensureEmblaScroll("next")}},this.onWindowResize=()=>{this.syncCarousel()},this.updateButtonStates=()=>{const{canPrev,canNext}=this.getArrowState();this.prevContainer?.toggleAttribute("data-disabled",!canPrev),this.nextContainer?.toggleAttribute("data-disabled",!canNext)},this.syncCarousel=()=>{const state=this.measureCarouselState();if(!state)return;const{overflowing,showArrow,width,slidesWidth,slideCount,maxVisibleItems}=state;if(this.toggleAttribute("data-overflow",overflowing),this.toggleAttribute("data-arrows",showArrow),!overflowing){this.destroyEmbla(),this.lastMeasureKey="",this.updateButtonStates();return}const measureKey=`${width}:${slidesWidth}:${maxVisibleItems}`;this.emblaApi?measureKey!==this.lastMeasureKey?(this.lastMeasureKey=measureKey,this.emblaApi.reInit({...EMBLA_OPTIONS}),this.updateButtonStates()):this.updateButtonStates():(this.createEmbla(),this.lastMeasureKey=measureKey,this.reInitEmblaAfterLayout())},this.relatedProducts=[...this.querySelectorAll("[data-related-product]")],this.viewportNode=this.querySelector(".embla__viewport"),this.containerNode=this.querySelector(".embla__container"),this.prevButton=this.querySelector(".embla__prev"),this.nextButton=this.querySelector(".embla__next"),this.prevContainer=this.querySelector(".container_embla__prev"),this.nextContainer=this.querySelector(".container_embla__next"),this.sectionsRender=[{id:"main-product-v2",selector:["[data-render-gallery-main-product]","[data-render-related-product]","[data-render-buy-main-product]","[data-render-tuncat-description]","[data-render-product-title]","[data-render-reassurance-main-product]"]},{id:"engraving-panel",selector:["[data-render-engraving-panel]"]}]}getArrowState(){if(!this.hasAttribute("data-arrows"))return{canPrev:!1,canNext:!1};if(this.emblaApi){const canPrev=this.emblaApi.canScrollPrev(),canNext=this.emblaApi.canScrollNext();if(canPrev||canNext)return{canPrev,canNext}}if(!this.viewportNode||!this.containerNode)return{canPrev:!1,canNext:!0};const viewportRect=this.viewportNode.getBoundingClientRect(),containerRect=this.containerNode.getBoundingClientRect();return{canPrev:containerRect.left<viewportRect.left-OVERFLOW_EPSILON_PX,canNext:containerRect.right>viewportRect.right+OVERFLOW_EPSILON_PX}}ensureEmblaScroll(direction){this.emblaApi||this.createEmbla(),this.emblaApi&&(this.emblaApi.reInit({...EMBLA_OPTIONS}),direction==="prev"&&this.emblaApi.canScrollPrev()&&this.emblaApi.scrollPrev(),direction==="next"&&this.emblaApi.canScrollNext()&&this.emblaApi.scrollNext(),this.updateButtonStates())}measureCarouselState(){if(!this.viewportNode||!this.containerNode)return null;const width=this.viewportNode.clientWidth;if(width<=0)return null;const slides=this.containerNode.querySelectorAll(".embla__slide"),slideCount=slides.length;let slidesWidth=0;for(const slide of slides)slidesWidth+=slide.offsetWidth;const maxVisibleItems=getMaxVisibleItems(window.innerWidth),enoughItems=slideCount>maxVisibleItems,overflowing=slidesWidth>width+OVERFLOW_EPSILON_PX;return{overflowing,showArrow:enoughItems&&overflowing,width,slidesWidth,slideCount,maxVisibleItems}}reInitEmblaAfterLayout(){this.emblaApi&&requestAnimationFrame(()=>{!this.emblaApi||!this.hasAttribute("data-overflow")||(this.emblaApi.reInit({...EMBLA_OPTIONS}),this.updateButtonStates())})}createEmbla(){if(!this.viewportNode||this.emblaApi)return;const factory=getEmblaFactory();if(!factory){window.clearTimeout(this.emblaRetryTimeoutId),this.emblaRetryTimeoutId=window.setTimeout(()=>{this.syncCarousel()},100);return}this.containerNode&&(this.containerNode.style.transform="",this.containerNode.style.marginInline="",this.containerNode.style.width=""),this.emblaApi=factory(this.viewportNode,{...EMBLA_OPTIONS}),this.prevButton?.addEventListener("click",this.onPrevClick),this.nextButton?.addEventListener("click",this.onNextClick),this.prevContainer?.addEventListener("click",this.onPrevClick),this.nextContainer?.addEventListener("click",this.onNextClick),this.emblaApi.on("select",this.updateButtonStates).on("scroll",this.updateButtonStates).on("reInit",this.updateButtonStates)}destroyEmbla(){window.clearTimeout(this.emblaRetryTimeoutId),this.emblaApi&&(this.prevButton?.removeEventListener("click",this.onPrevClick),this.nextButton?.removeEventListener("click",this.onNextClick),this.prevContainer?.removeEventListener("click",this.onPrevClick),this.nextContainer?.removeEventListener("click",this.onNextClick),this.emblaApi.destroy(),this.emblaApi=null),this.containerNode&&(this.containerNode.style.transform="")}connectedCallback(){this.syncCarousel(),this.viewportNode&&(this.resizeObserver=new ResizeObserver(()=>{this.syncCarousel()}),this.resizeObserver.observe(this.viewportNode)),window.addEventListener("resize",this.onWindowResize),window.addEventListener("load",this.onWindowResize),requestAnimationFrame(()=>{requestAnimationFrame(()=>this.syncCarousel())}),this.dataset.disabled!=="true"&&this.querySelectorAll("[data-related-product]").forEach(el=>{el.addEventListener("click",async e=>{e.preventDefault();const url=new URL(el.href);history.pushState("","",url.href),this.setLoading(!0);try{await renderSections(this.sectionsRender,{url})}catch(error){console.error("[RelatedProductsV2] section render failed:",error),window.location.reload();return}finally{this.setLoading(!1)}})})}setLoading(loading){document.getElementById("full-page-loader")?.setAttribute("aria-hidden",loading?"false":"true")}disconnectedCallback(){window.removeEventListener("resize",this.onWindowResize),window.removeEventListener("load",this.onWindowResize),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.destroyEmbla()}};window.customElements.get("c-related-products-v2")||window.customElements.define("c-related-products-v2",RelatedProductsV2)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["set-to-compose-form"]&&!Shopify.designMode))try{(()=>{var COMPOSE_QUANTITY_CHANGE_EVENT="set-to-compose:quantity-change";function clampToNonNegativeInteger(value){const floored=Math.floor(value);return floored<0?0:floored}function getBundleSize(){const root=document.querySelector("c-set-to-compose-product");return root?Number(root.dataset.bundleSize??0):0}function getAllowDuplicates(){const root=document.querySelector("c-set-to-compose-product");return root?root.dataset.allowDuplicates==="true":!0}function getTotalSelectedQuantity(){const inputs=document.querySelectorAll('c-set-to-compose-form input[name="quantity"]');let total=0;for(const input of inputs)total+=clampToNonNegativeInteger(Number(input.value));return total}
28function syncAllIncrementDisabled(){const bundleSize=getBundleSize();if(bundleSize<=0)return;const shouldDisableBundle=getTotalSelectedQuantity()>=bundleSize,allowDuplicates=getAllowDuplicates(),forms=document.querySelectorAll("c-set-to-compose-form");for(const form of forms){const incrementButton=form.querySelector("button.set-to-compose-form__increment");if(!incrementButton)continue;const quantityInput=form.querySelector('input[name="quantity"]'),quantity=quantityInput?clampToNonNegativeInteger(Number(quantityInput.value)):0,maxAttr=quantityInput?.getAttribute("max")??"",shouldDisableStock=quantity>=Number(maxAttr),shouldDisableDuplicateRule=!allowDuplicates&&quantity>=1,shouldDisable=shouldDisableBundle||shouldDisableDuplicateRule||shouldDisableStock;incrementButton.toggleAttribute("disabled",shouldDisable)}}var SetToComposeForm=class extends HTMLElement{constructor(){super(...arguments),this.quantityInput=null,this.decrementButton=null,this.incrementButton=null,this.quantityValue=null,this.incrementQuantity=()=>
28{if(!this.quantityInput)return;const currentQty=clampToNonNegativeInteger(Number(this.quantityInput.value)),maxQuantity=this.getMaxQuantity();if(Number.isFinite(maxQuantity)&&currentQty>=maxQuantity){syncAllIncrementDisabled();return}if(!getAllowDuplicates()&&currentQty>=1){syncAllIncrementDisabled();return}const bundleSize=getBundleSize();if(bundleSize>0&&getTotalSelectedQuantity()>=bundleSize){syncAllIncrementDisabled();return}const next=clampToNonNegativeInteger(Number(this.quantityInput.value)+1);this.quantityInput.value=next.toString(),this.syncUIFromInput(),this.emitQuantityChange(next),syncAllIncrementDisabled()},this.decrementQuantity=()=>{if(!this.quantityInput)return;const next=clampToNonNegativeInteger(Number(this.quantityInput.value)-1);this.quantityInput.value=next.toString(),this.syncUIFromInput(),this.emitQuantityChange(next),syncAllIncrementDisabled()}}connectedCallback(){this.quantityInput=this.querySelector('input[name="quantity"]'),this.quantityValue=this.querySelector(".set-to-compose-form__quantity-value"),this.decrementButton=this.querySelector("button.set-to-compose-form__decrement"),this.incrementButton=this.querySelector("button.set-to-compose-form__increment"),this.syncUIFromInput(),syncAllIncrementDisabled(),this.decrementButton?.addEventListener("click",this.decrementQuantity),this.incrementButton?.addEventListener("click",this.incrementQuantity)}disconnectedCallback(){this.decrementButton?.removeEventListener("click",this.decrementQuantity),this.incrementButton?.removeEventListener("click",this.incrementQuantity)}getItemFromDataset(){const variantId=this.dataset.composeVariantId??"",title=this.dataset.composeTitle??"",imageUrl=this.dataset.composeImage??"",priceCents=Number(this.dataset.composePrice??0);return variantId.length===0||title.length===0||imageUrl.length===0?null:{variantId,title,imageUrl,priceCents}}emitQuantityChange(quantity){const item=this.getItemFromDataset();if(!item)return;const detail={item,quantity};document.dispatchEvent(new CustomEvent(COMPOSE_QUANTITY_CHANGE_EVENT,{detail}))}syncUIFromInput(){if(!this.quantityInput||!this.quantityValue)return;const qty=clampToNonNegativeInteger(Number(this.quantityInput.value));this.quantityInput.value=qty.toString(),this.quantityValue.textContent=this.quantityInput.value,qty<1?this.decrementButton?.setAttribute("disabled","true"):this.decrementButton?.removeAttribute("disabled")}getMaxQuantity(){const maxAttr=this.quantityInput?.getAttribute("max")??"";return Number(maxAttr)}};window.customElements.get("c-set-to-compose-form")||window.customElements.define("c-set-to-compose-form",SetToComposeForm)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["sticky-composition-bar"]&&!Shopify.designMode))try{(()=>{var SECTION_PREFIX="shopify-section-";function buildUrl(base,params){const url=new URL(base??window.location.pathname,window.location.origin);for(const[key,value]of Object.entries(params))url.searchParams.set(key,value);return url.toString()}function withQuery(params,query){return query?{...Object.fromEntries(Object.entries(query).map(([k,v])=>[k,String(v)])),...params}:params}async function fetchSections(ids,options={}){const url=buildUrl(options.url,withQuery({sections:ids.join(",")},options.query)),response=await fetch(url,{credentials:"same-origin"});if(!response.ok)throw new Error(`Sections fetch ${response.status}`);return response.json()}function bundledSectionsParams(ids,sectionsUrl){const params={sections:ids.join(",")};return sectionsUrl&&(params.sections_url=sectionsUrl),params}function swapInner(html,selector){const selectors=Array.isArray(selector)?selector:[selector],doc=new DOMParser().parseFromString(html,"text/html");selectors.forEach(sel=>{document.querySelectorAll(sel).forEach(element=>{const source=element.dataset.id?doc.querySelector(`${sel}[data-id="${element.dataset.id}"]`):doc.querySelector(sel);source&&(element.innerHTML=source.innerHTML)})})}function swapSection(id,html){const live=document.getElementById(`${SECTION_PREFIX}${id}`);if(!live)return;const doc=new DOMParser().parseFromString(html,"text/html"),next=doc.getElementById(`${SECTION_PREFIX}${id}`)||doc.body.firstElementChild;next instanceof HTMLElement?live.replaceWith(next):live.hidden=!0}
28async function renderSections(targets,options={}){if(targets.length===0)return;const map=options.sections??await fetchSections(targets.map(t=>t.id),options);for(const target of targets){const html=map[target.id];typeof html=="string"&&(target.selector?swapInner(html,target.selector):swapSection(target.id,html))}}var COMPOSE_QUANTITY_CHANGE_EVENT="set-to-compose:quantity-change",SECTIONS_RENDER=[{id:"header",selector:[".header__action-link--cart"]},{id:"popup-add-to-cart",selector:["[data-popup-atc-container]"]}];function clampToNonNegativeInteger(value){if(!Number.isFinite(value))return 0;const floored=Math.floor(value);return floored<0?0:floored}function setImg(img,url,alt){if(url.length===0){img.removeAttribute("src"),img.alt="";return}img.src=url,img.alt=alt}var _StickyCompositionBar=class _StickyCompositionBar2 extends HTMLElement{constructor(){super(...arguments),this.header=this.querySelector(".sticky-composition-bar_header"),this.content=this.querySelector(".sticky-composition-bar_content"),this.selectedCountEl=this.querySelector("[data-sticky-selected-count]"),this.priceEl=this.querySelector("[data-sticky-price]"),this.slotEls=Array.from(this.querySelectorAll("[data-sticky-slot]")),this.removeButtonsSelector="button.sticky-composition-bar_content_item_button--remove",this.selectionByVariantId=new Map,this.errorMessage=document.querySelector("[data-set-to-compose-error-message]"),this.closedHeight=this.header?.clientHeight??0,this.openHeight=(this.content?.clientHeight??0)+(this.header?.clientHeight??0),this.stickyForm=null,this.handleHeaderClick=()=>{this.classList.contains("open")?this.classList.remove("open"):this.classList.add("open")},this.handleOutsideClick=event=>{if(!this.classList.contains("open"))return;const target=event.target;!(target instanceof Element)||this.contains(target)||target.closest(_StickyCompositionBar2.INTERACTIVE_SELECTOR)!==null||this.classList.remove("open")},this.handleQuantityChange=event=>{if(!(event instanceof CustomEvent))return;const detail=event.detail;if(!detail||typeof detail.quantity!="number"||!detail.item||typeof detail.item.variantId!="string"||typeof detail.item.priceCents!="number")return;const qty=clampToNonNegativeInteger(detail.quantity),key=detail.item.variantId;if(qty===0)this.selectionByVariantId.delete(key);else{const previous=this.selectionByVariantId.get(key);this.selectionByVariantId.set(key,{item:detail.item,quantity:qty,updatedAt:previous?previous.updatedAt:Date.now()})}this.buildFlatItems().length===this.slotEls.length&&this.handleHeaderClick(),this.render()},this.handleRemoveButtonClick=event=>{const target=event.target;if(!(target instanceof Element))return;const removeButton=target.closest(this.removeButtonsSelector);if(!removeButton)return;const slotEl=removeButton.closest("[data-sticky-slot]");if(!slotEl)return;const variantId=slotEl.dataset.composeVariantId??"";if(variantId.length===0)return;const formEl=document.querySelector(`c-set-to-compose-form[data-compose-variant-id="${CSS.escape(variantId)}"]`);if(!formEl)return;const quantityInput=formEl.querySelector('input[name="quantity"]'),decrementButton=formEl.querySelector("button.set-to-compose-form__decrement");!quantityInput||!decrementButton||clampToNonNegativeInteger(Number(quantityInput.value))<=0||decrementButton.click()},this.handleStickySubmit=async event=>{try{event.preventDefault(),event.stopPropagation(),event.stopImmediatePropagation();const requiredCount=this.slotEls.length,bundleVariantId=this.getBundleVariantId();if(requiredCount<=0||bundleVariantId<=0||this.buildFlatItems().length!==requiredCount)return;const pricingMode=this.getPricingMode(),componentEntries=Array.from(this.selectionByVariantId.values());if(componentEntries.reduce((acc,entry)=>acc+entry.quantity,0)!==requiredCount||componentEntries.length<=0)return;if(pricingMode==="fixed"){const components=componentEntries.map(entry=>{const variantIdNumber=Number(entry.item.variantId);return!Number.isFinite(variantIdNumber)||variantIdNumber<=0?null:{variantId:`gid://shopify/ProductVariant/${variantIdNumber}`,qty:entry.quantity}}).filter(c=>c!==null);if(components.length!==componentEntries.length)return;const body2={items:[{id:bundleVariantId,quantity:1,properties:{_components:JSON.stringify(components),_bundle_pricing:"fixed"}}]};await this.submitBundlePayload(body2);return}const bundleId=this.generateBundleId(),items=[{id:bundleVariantId,quantity:1,properties:{_bundle_id:bundleId,_bundle_role:"parent"}},...componentEntries.map(entry=>{const variantIdNumber=Number(entry.item.variantId);return!Number.isFinite(variantIdNumber)||variantIdNumber<=0?null:{id:variantIdNumber,quantity:entry.quantity,properties:{_bundle_id:bundleId,_bundle_role:"child"}}}).filter(c=>c!==null)];if(items.length<=1)return;const body={items};await this.submitBundlePayload(body)}catch(error){console.error("[StickyCompositionBar] handleStickySubmit failed",error)}}}syncCardSelectionIcons(){const icons=Array.from(document.querySelectorAll("[data-compose-check-variant-id]"));for(const iconWrapper of icons){const variantId=iconWrapper.dataset.composeCheckVariantId??"",isSelected=this.selectionByVariantId.has(variantId);iconWrapper.classList.toggle("is-selected",isSelected)}}getPricingMode(){return(this.dataset.pricingMode??"fixed").toLowerCase()}
28getBundleVariantId(){const raw=this.dataset.bundleVariantId;if(!raw)return 0;const parsed=Number(raw);return!Number.isFinite(parsed)||parsed<=0?0:parsed}generateBundleId(){const cryptoObj=window.crypto;if(cryptoObj&&typeof cryptoObj.randomUUID=="function")return cryptoObj.randomUUID();const randomPart=Math.random().toString(16).slice(2);return`bundle_${Date.now()}_${randomPart}`}getSubmitButton(){const form=document.querySelector('form[id*="sticky-composition-bar-form"]');return form?form.querySelector("[data-product-form-submit]"):null}connectedCallback(){this.style.setProperty("--closed-height",`${this.closedHeight}px`),this.style.setProperty("--open-height",`${this.openHeight}px`),this.header?.addEventListener("click",this.handleHeaderClick),document.addEventListener(COMPOSE_QUANTITY_CHANGE_EVENT,this.handleQuantityChange),this.content?.addEventListener("click",this.handleRemoveButtonClick),document.addEventListener("click",this.handleOutsideClick),this.stickyForm=document.querySelector('form[id*="sticky-composition-bar-form"]'),this.stickyForm?.addEventListener("submit",this.handleStickySubmit,!0),this.render()}disconnectedCallback(){this.header?.removeEventListener("click",this.handleHeaderClick),document.removeEventListener(COMPOSE_QUANTITY_CHANGE_EVENT,this.handleQuantityChange),this.content?.removeEventListener("click",this.handleRemoveButtonClick),document.removeEventListener("click",this.handleOutsideClick),this.stickyForm?.removeEventListener("submit",this.handleStickySubmit,!0)}async submitBundlePayload(body){try{const payload={...body,...bundledSectionsParams(["header","popup-add-to-cart"])},res=await fetch(`${window.Shopify?.routes?.root??"/"}cart/add.js`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/javascript","X-Requested-With":"XMLHttpRequest"},body:JSON.stringify(payload)});let data=null,rawText=null;try{data=await res.json()}catch{try{rawText=await res.text()}catch{rawText=null}}if(this.classList.remove("open"),!res.ok){window.scrollTo(0,0),this.errorMessage&&this.errorMessage.classList.contains("hidden")&&this.errorMessage.classList.remove("hidden"),console.error("Bundle add request failed",{status:res.status,data,rawText,requestBody:payload});return}if(data&&typeof data=="object"&&data!==null){const statusValue=data.status;if(typeof statusValue=="number"&&statusValue!==200){console.error("Cart add error:",data);return}}const sections=data&&typeof data=="object"&&data!==null&&"sections"in data?data.sections:null;await renderSections(SECTIONS_RENDER,{sections}),document.dispatchEvent(new CustomEvent("cart:add-success",{bubbles:!0,detail:{data,action:"add"}}))}catch(error){console.error("Request failed:",error)}}buildFlatItems(){const entries=Array.from(this.selectionByVariantId.values()).sort((a,b)=>a.updatedAt-b.updatedAt),flat=[];for(const entry of entries)for(let i=0;i<entry.quantity;i+=1)flat.push(entry.item);return flat}renderSelectedCount(count){this.selectedCountEl&&(this.selectedCountEl.textContent=count.toString())}renderSlots(items){const max=this.slotEls.length,clamped=items.slice(0,max);for(let i=0;i<max;i+=1){const slotEl=this.slotEls[i],img=slotEl.querySelector("img"),title=slotEl.querySelectorAll(".sticky-composition-bar_content_item_title-text"),item=clamped[i];if(!(!img||!title)){if(!item){setImg(img,"",""),title.forEach(t=>t.textContent=""),slotEl.classList.remove("has-content"),delete slotEl.dataset.composeVariantId;continue}setImg(img,item.imageUrl,item.title),title.forEach(t=>t.textContent=item.title),slotEl.classList.add("has-content"),slotEl.dataset.composeVariantId=item.variantId}}this.openHeight=(this.content?.clientHeight??0)+(this.header?.clientHeight??0),this.style.setProperty("--open-height",`${this.openHeight}px`)}render(){const flat=this.buildFlatItems();this.renderSelectedCount(flat.length),this.renderSlots(flat),this.syncSubmitDisabled(flat.length),this.syncDynamicPrice(flat),this.syncCardSelectionIcons()}syncSubmitDisabled(selectedCount){const submitButton=this.getSubmitButton();if(!submitButton)return;const requiredCount=this.slotEls.length,isEnabled=selectedCount===requiredCount&&requiredCount>0;submitButton.toggleAttribute("disabled",!isEnabled)}syncDynamicPrice(items){if(!this.priceEl||this.getPricingMode()!=="dynamic")return;const totalCents=items.reduce((acc,item)=>acc+item.priceCents,0);this.priceEl.textContent=(totalCents/100).toString()}};_StickyCompositionBar.INTERACTIVE_SELECTOR="a, button, input";var StickyCompositionBar=_StickyCompositionBar;window.customElements.get("c-sticky-composition-bar")||window.customElements.define("c-sticky-composition-bar",StickyCompositionBar)})()}catch(e){console.error(e)}})(),(function(){if(!(!__snippets__["story-list"]&&!Shopify.designMode))try{(()=>{var STORY_DESKTOP_QUERY="(min-width: 1024px)",REDUCED_MOTION_QUERY="(prefers-reduced-motion: reduce)",VISIBILITY_RATIO=.25,VISIBILITY_HEIGHT_RATIO=.5,THRESHOLDS=Array.from({length:21},(_,i)=>i/20),HOLD_DELAY=220,MOVE_TOLERANCE=10,TAP_PREV_ZONE=.3,TAP_NEXT_ZONE=.7,SOUND_EVENT="story-list:sound",STALL_TIMEOUT=8e3;function cleanLabel(value){return value&&!value.includes("Translation missing")?value:null}var StoryList=class extends HTMLElement{constructor(){super(...arguments),this.current=0,this.count=0,this.regime="timed",this.autoLoop=!1,this.userPaused=!1,this.holdPaused=!1,this.focusPaused=!1,this.playBlocked=!1,this.inView=!1,this.tabHidden=document.hidden,this.finished=!1,this.muted=!0,this.stage=null,this.activeVideo=null,this.observer=null,this.desktopQuery=null,this.listeners=null,this.segmentListeners=null,this.holdTimer=null,this.frameHandle=null,this.lastFrameAt=0,this.lastVideoTime=-1,this.stalledFor=0,this.failures=0,this.tickProgress=now=>{this.frameHandle=null;const video=this.activeVideo;if(!video)return;const elapsed=now-this.lastFrameAt;if(this.lastFrameAt=now,video.paused)this.stalledFor=0;else if(video.currentTime===this.lastVideoTime){if(this.stalledFor+=elapsed,this.stalledFor>=STALL_TIMEOUT){this.skipSegment();return}}else this.lastVideoTime=video.currentTime,this.stalledFor=0,this.failures=0;if(video.duration&&Number.isFinite(video.duration)){const progress=Math.min(video.currentTime/video.duration,1);this.setProp("--story-progress",progress.toFixed(4))}this.frameHandle=window.requestAnimationFrame(this.tickProgress)},this.handleMediaEnded=()=>{this.regime==="media"&&(this.failures=0,this.handleSegmentEnd())},this.handleMediaError=()=>{this.regime==="media"&&this.skipSegment()},this.handleAnimationEnd=event=>{if(this.regime!=="timed"||event.animationName!=="story-fill")return;const bar=event.target?.closest("[data-story-bar]");!bar||bar.dataset.storyBar!==String(this.current)||(this.failures=0,this.handleSegmentEnd())},this.handleForeignSound=event=>{const{source}=event.detail??{};source!==this&&this.setMuted(!0)},this.handleVisibility=entries=>{const entry=entries[entries.length-1];if(!entry)return;const tallEnough=entry.intersectionRect.height>=window.innerHeight*VISIBILITY_HEIGHT_RATIO,visible=entry.isIntersecting&&(entry.intersectionRatio>=VISIBILITY_RATIO||tallEnough);
28visible!==this.inView&&(this.inView=visible,this.tuneBuffering(this.current),this.syncPlayback(),this.syncControls())},this.handleFocusIn=event=>{!event.target?.closest(".story-list__cards")||this.focusPaused||(this.focusPaused=!0,this.syncPlayback(),this.syncControls())},this.handleFocusOut=event=>{!this.focusPaused||event.relatedTarget?.closest(".story-list__cards")||(this.focusPaused=!1,this.syncPlayback(),this.syncControls())},this.handleTabVisibility=()=>{document.hidden!==this.tabHidden&&(this.tabHidden=document.hidden,this.syncPlayback(),this.syncControls())},this.handleBreakpoint=()=>{if(this.finished||this.regime!=="media")return;const segment=this.segmentAt(this.current),video=segment?this.visibleVideoOf(segment):null;if(!video||video===this.activeVideo)return;const previous=this.activeVideo,at=previous?.currentTime??0;previous?.pause(),this.segmentListeners?.abort(),this.segmentListeners=new AbortController,this.attachVideo(video,this.segmentListeners.signal),Number.isFinite(video.duration)&&video.duration>0&&(video.currentTime=Math.min(at,video.duration)),this.lastVideoTime=-1,this.stalledFor=0,this.syncPlayback()}}connectedCallback(){if(this.listeners||(this.stage=this.querySelector("[data-story-stage]"),this.count=this.querySelectorAll("[data-story-slot]").length,!this.stage||this.count===0))return;this.autoLoop=this.dataset.autoLoop==="true",this.tabHidden=document.hidden,this.listeners=new AbortController;const{signal}=this.listeners;window.matchMedia(REDUCED_MOTION_QUERY).matches&&(this.userPaused=!0),this.bindControls(signal),this.bindSurface(signal),this.bindKeyboard(signal),this.addEventListener("animationend",this.handleAnimationEnd,{signal}),this.desktopQuery=window.matchMedia(STORY_DESKTOP_QUERY),this.desktopQuery.addEventListener("change",this.handleBreakpoint,{signal}),document.addEventListener("visibilitychange",this.handleTabVisibility,{signal}),this.addEventListener("focusin",this.handleFocusIn,{signal}),this.addEventListener("focusout",this.handleFocusOut,{signal}),document.addEventListener(SOUND_EVENT,this.handleForeignSound,{signal}),this.observer=new IntersectionObserver(this.handleVisibility,{threshold:THRESHOLDS}),this.observer.observe(this),this.activate(0),this.syncMuteControls(),this.nameInstances()}nameInstances(){const all=document.querySelectorAll("c-story-list");all.forEach((host,index)=>{const base=cleanLabel(host.dataset.labelStory);base&&this.setLabel(host,all.length>1?`${base} ${index+1}`:base)})}disconnectedCallback(){this.listeners?.abort(),this.listeners=null,this.segmentListeners?.abort(),this.segmentListeners=null,this.observer?.disconnect(),this.observer=null,this.desktopQuery=null,this.clearHoldTimer(),this.stopProgressLoop()}setHidden(el,hidden){!el||el.hasAttribute("hidden")===hidden||(hidden?el.setAttribute("hidden",""):el.removeAttribute("hidden"))}setLabel(el,label){!el||!label||el.getAttribute("aria-label")===label||el.setAttribute("aria-label",label)}setProp(name,value){this.style.getPropertyValue(name)!==value&&this.style.setProperty(name,value)}get isPlayIntended(){return this.inView&&!this.tabHidden&&!this.userPaused&&!this.holdPaused&&!this.focusPaused&&!this.playBlocked&&!this.finished}get isDesktop(){return this.desktopQuery?this.desktopQuery.matches:window.matchMedia(STORY_DESKTOP_QUERY).matches}get loops(){return this.autoLoop||this.count===1}segmentAt(index){return this.querySelector(`[data-story-slot="${index}"]`)}visibleVideoOf(segment){const variants=[...segment.querySelectorAll(".story-list__variant")];return(variants.find(v=>v.offsetParent!==null||v.offsetWidth>0)??variants[0])?.querySelector("video")??null}activate(index){if(!this.stage)return;this.segmentListeners?.abort(),this.segmentListeners=new AbortController;const{signal}=this.segmentListeners;this.current=index,this.activeVideo=null,this.playBlocked=!1,this.stopProgressLoop();const segment=this.segmentAt(index);if(segment){if(this.querySelectorAll("[data-story-slot]").forEach(el=>{this.setHidden(el,el!==segment)}),this.regime=segment.dataset.kind==="video"?"media":"timed",this.dataset.storyRegime!==this.regime&&(this.dataset.storyRegime=this.regime),this.setProp("--story-fg-desktop",segment.dataset.fgDesktop||"#ffffff"),this.setProp("--story-fg-subtle-desktop",segment.dataset.fgSubtleDesktop||"#c8c8c8"),this.setProp("--story-fg-mobile",segment.dataset.fgMobile||"#ffffff"),this.setProp("--story-fg-subtle-mobile",segment.dataset.fgSubtleMobile||"#c8c8c8"),this.regime==="media"){const video=this.visibleVideoOf(segment);if(!video){this.skipSegment();return}
28this.attachVideo(video,signal)}else this.setProp("--story-duration",`${segment.dataset.duration}s`);this.resetBars(),this.announce(),this.tuneBuffering(index),this.syncControls(),this.syncMuteControls(),this.syncPlayback()}}attachVideo(video,signal){this.activeVideo=video,video.loop=!1,video.playsInline=!0,video.muted=this.muted,video.preload="auto",video.addEventListener("ended",this.handleMediaEnded,{signal}),video.addEventListener("error",this.handleMediaError,{signal}),video.networkState===video.NETWORK_EMPTY&&video.load()}announce(){const status=this.querySelector("[data-story-status]");if(!status)return;const template=cleanLabel(this.dataset.labelPosition),index=String(this.current+1),text=template?template.replace("__INDEX__",index):`${index} / ${this.count}`;status.textContent!==text&&(status.textContent=text)}restart(){this.lastVideoTime=-1,this.stalledFor=0,this.activeVideo&&(this.activeVideo.currentTime=0),this.resetBars(),this.syncControls(),this.syncPlayback()}goTo(index){const next=Math.min(Math.max(index,0),this.count-1),wasFinished=this.finished;if(this.finished=!1,next===this.current&&!wasFinished&&this.stage?.firstElementChild){this.restart();return}this.activate(next)}next(){this.current>=this.count-1||this.goTo(this.current+1)}prev(){this.goTo(this.current-1)}handleSegmentEnd(){if(this.current<this.count-1){this.next();return}if(this.loops){this.goTo(0);return}this.finish()}skipSegment(){if(this.failures+=1,this.failures>=this.count){this.finish();return}this.handleSegmentEnd()}finish(){this.finished=!0,this.setProp("--story-progress","1"),this.querySelectorAll("[data-story-bar]").forEach(bar=>{bar.removeAttribute("data-story-active");const fill=this.fillOf(bar);fill&&(fill.style.transform="scaleX(1)")}),this.syncPlayback(),this.syncControls()}replay(){this.goTo(0)}fillOf(bar){return bar.querySelector(".story-bar__fill")}resetBars(){this.setProp("--story-progress","0"),this.querySelectorAll("[data-story-bar]").forEach(bar=>{const index=Number(bar.dataset.storyBar),fill=this.fillOf(bar);if(!fill)return;if(index===this.current){bar.setAttribute("data-story-active",""),fill.style.transform="",fill.style.animation="none",fill.offsetWidth,fill.style.animation="";return}bar.removeAttribute("data-story-active");const done=index<this.current;fill.style.animation="none",fill.style.transform=done?"scaleX(1)":"scaleX(0)"})}startProgressLoop(){this.frameHandle===null&&(this.lastFrameAt=performance.now(),this.lastVideoTime=-1,this.stalledFor=0,this.frameHandle=window.requestAnimationFrame(this.tickProgress))}stopProgressLoop(){this.frameHandle!==null&&(window.cancelAnimationFrame(this.frameHandle),this.frameHandle=null)}syncPlayback(){const playing=this.isPlayIntended;this.setProp("--story-play-state",playing?"running":"paused");const video=this.activeVideo;if(playing&&this.regime==="media"&&video?this.startProgressLoop():this.stopProgressLoop(),!!video){if(playing&&video.paused){const played=video.play();played&&typeof played.catch=="function"&&played.catch(error=>{error?.name==="NotAllowedError"&&(this.playBlocked=!0,this.syncPlayback(),this.syncControls())});return}!playing&&!video.paused&&video.pause()}}syncControls(){const done=this.finished&&!this.loops,paused=!done&&!this.isPlayIntended;this.setHidden(this.querySelector("[data-icon-play]"),!paused),this.setHidden(this.querySelector("[data-icon-pause]"),done||paused),this.setHidden(this.querySelector("[data-icon-restart]"),!done);let label=this.dataset.labelPause;done?label=this.dataset.labelReplay:paused&&(label=this.dataset.labelPlay),this.setLabel(this.querySelector("[data-play-btn]"),cleanLabel(label)),this.querySelector("[data-story-prev]")?.toggleAttribute("disabled",this.current===0),this.querySelector("[data-story-next]")?.toggleAttribute("disabled",this.current===this.count-1)}syncMuteControls(){this.setHidden(this.querySelector("[data-icon-muted]"),!this.muted),this.setHidden(this.querySelector("[data-icon-unmuted]"),this.muted),this.setLabel(this.querySelector("[data-mute-btn]"),cleanLabel(this.muted?this.dataset.labelUnmute:this.dataset.labelMute))}togglePlay(){if(this.finished){this.replay();return}this.userPaused=!this.userPaused,this.playBlocked=!1,this.syncPlayback(),this.syncControls()}setMuted(muted){this.muted!==muted&&(this.muted=muted,this.querySelectorAll("video").forEach(video=>{video.muted=muted}),this.syncMuteControls())}toggleMute(){const muted=!this.muted;this.setMuted(muted),muted||document.dispatchEvent(new CustomEvent(SOUND_EVENT,{detail:{source:this}}))}
28tuneBuffering(index){this.querySelectorAll("[data-story-slot]").forEach(segment=>{const rank=Number(segment.dataset.storySlot),shown=this.visibleVideoOf(segment);segment.querySelectorAll("video").forEach(video=>{const wanted=video!==shown?"none":rank===index?this.inView?"auto":"metadata":rank===index+1&&this.inView?"metadata":"none";video===shown&&wanted!=="none"&&video.dataset.poster&&(video.poster=video.dataset.poster,delete video.dataset.poster),video.preload!==wanted&&(video.preload=wanted),video.muted!==this.muted&&(video.muted=this.muted),video!==this.activeVideo&&!video.paused&&video.pause()})})}bindControls(signal){const on=(selector,handler)=>{this.querySelector(selector)?.addEventListener("click",handler,{signal})};on("[data-play-btn]",()=>this.togglePlay()),on("[data-mute-btn]",()=>this.toggleMute()),on("[data-story-prev]",()=>this.prev()),on("[data-story-next]",()=>this.next())}clearHoldTimer(){this.holdTimer!==null&&(window.clearTimeout(this.holdTimer),this.holdTimer=null)}bindSurface(signal){const surface=this.querySelector("[data-story-surface]");if(!surface)return;let startX=0,startY=0,moved=!1,held=!1;surface.addEventListener("pointerdown",event=>{event.isPrimary&&(startX=event.clientX,startY=event.clientY,moved=!1,held=!1,surface.setPointerCapture(event.pointerId),this.clearHoldTimer(),event.pointerType!=="mouse"&&(this.holdTimer=window.setTimeout(()=>{held=!0,this.holdPaused=!0,this.syncPlayback(),this.syncControls()},HOLD_DELAY)))},{signal}),surface.addEventListener("pointermove",event=>{moved||Math.hypot(event.clientX-startX,event.clientY-startY)<=MOVE_TOLERANCE||(moved=!0,this.clearHoldTimer())},{signal});const release=(event,navigate)=>{if(this.clearHoldTimer(),surface.hasPointerCapture(event.pointerId)&&surface.releasePointerCapture(event.pointerId),held){held=!1,this.holdPaused=!1,this.syncPlayback(),this.syncControls();return}!navigate||moved||this.handleTap(event,surface)};surface.addEventListener("pointerup",event=>release(event,!0),{signal}),surface.addEventListener("pointercancel",event=>release(event,!1),{signal})}handleTap(event,surface){if(this.isDesktop||this.count<2){this.togglePlay();return}const rect=surface.getBoundingClientRect();if(rect.width===0)return;const ratio=(event.clientX-rect.left)/rect.width;ratio<TAP_PREV_ZONE?this.prev():ratio>TAP_NEXT_ZONE?this.next():this.togglePlay()}bindKeyboard(signal){this.addEventListener("keydown",event=>{event.key==="ArrowLeft"?(event.preventDefault(),this.prev()):event.key==="ArrowRight"&&(event.preventDefault(),this.next())},{signal})}};window.customElements.get("c-story-list")||window.customElements.define("c-story-list",StoryList)})()}catch(e){console.error(e)}})()})();
29//# sourceMappingURL=/cdn/shop/t/91/compiled_assets/snippet-scripts.js.map?v=18972120271862874511790771807

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.