(()=>{const e=async()=>{window.__rdmWidgetReady=!1,window.__rdmWidgetMessageQueue=[],window._rediemMessageHandlerBound||(window._rediemMessageHandlerBound=!0,window.__rdmLaunchPending=!1,window.addEventListener("message",e=>{switch(e.data?.type){case"openRipplUrl":window.open(e.data.url,"_blank");break;case"ripplRewardSaveData":sessionStorage.setItem("ripplRewardData",JSON.stringify(e.data.data)),e?.data?.data?.action_deeplink&&sessionStorage.setItem("action_deeplink",JSON.stringify(e.data.data.action_deeplink));break;case"addProductToCart":sessionStorage.setItem("freeProducts",JSON.stringify(e.data?.data)),sessionStorage.setItem("opt_type",e.data.type),U({products:e.data.products});break;case"addToCart":!async function({products:e}){let r=await W();try{if(e?.requiredPaidProduct){if(!G({cartItems:r}))throw new Error("You must add a paid product before claiming this free product.")}if(e?.perCartLimit){if(function({cartItems:e,products:t}){return!!e.find(e=>e.properties?._rediem_gift_card)}({cartItems:r,products:e}))throw new Error("Free product is already in your cart.")}const o=r.map(e=>e.variant_id),n=e?.varient?.filter(e=>!o.includes(e.id));if(0===n.length)throw new Error("Product already in cart!");const i=n.map(async t=>{const r=new URLSearchParams;r.append("id",Number(t.id).toString()),r.append("quantity",Number(t.qty).toString()),r.append("properties[_rediem_gift_card]",e.docId),e?.requiredPaidProduct&&r.append("properties[_rediem_paid]","true"),e?.perCartLimit&&r.append("properties[_rediem_per_cart]","true");const o=await fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});if(!o.ok){const e=await o.json();throw new Error(`${e?.message}: ${e?.description}`)}return o});await Promise.all(i);const s=await async function({vid:e,docId:r,pid:o}){const n=new Headers,i=`user_${t}`,s=JSON.parse(sessionStorage.getItem(i)||"{}");if(!s?.data?.token)return console.error("No customer token found"),!1;n.append("Authorization",`Bearer ${s?.data?.token}`),n.append("Content-Type","application/json");const c={method:"POST",headers:n,body:JSON.stringify({vid:e,id:r,pid:o}),redirect:"follow"};try{const e=await fetch(`${a}/product-reward/coupon`,c);if(e.ok){const t=await e.json();return await D(t.coupon),!0}return console.error("Failed to generate coupon:"),!1}catch(e){return console.error("Error generating coupon:"),!1}}({vid:n?.[0]?.id,docId:e?.docId,pid:e?.pid});s?(sessionStorage.setItem("cartFlags",JSON.stringify({_rediem_gift_card:!0})),window.location.href="/cart"):(F({message:"Failed to generate coupon",items:r}),console.error("Failed to generate coupon"))}catch(e){console.error(e.message),F({message:e?.message??"Failed to add product to cart!",items:r})}}({products:e.data.data});break;case"addProductToCartSubscription":sessionStorage.setItem("freeProductsSubscription",JSON.stringify(e.data?.data)),sessionStorage.setItem("opt_type",e.data.type),U({products:e.data.products,subscription:!0});break;case"exclusiveProduct":!async function({products:e}){try{const t=e.map(async e=>{const t=new URLSearchParams,r=e.product?.split("/")?.at(-1);t.append("id",r),t.append("quantity",1);const o=await fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!o.ok){const e=await o.json();throw new Error(`${e?.message}: ${e?.description}`)}return o});await Promise.all(t),window.location.href="/cart"}catch(e){console.error(e.message),F({message:e?.message??"Failed to add product to cart!"})}}({products:[e.data.item]});break;case"trigger_wiget_open":x(!0);break;case"access_session_data":{const t=e.data.key,r=JSON.parse(sessionStorage.getItem(t)??"{}");if("link_actions"===t){B(window.location.href)===B(r?.trackingLink)&&J({type:"link_actions",payload:r})}else F(r,t);break}case"remove_session_data":sessionStorage.removeItem(e.data.key);break;case"rdm_request_user":{const e=`user_${t}`;J({type:"rdm_user_data",payload:JSON.parse(sessionStorage.getItem(e)||"{}")});break}case"rdm_request_settings":{const e=`setting_${t}`;J({type:"rdm_setting_data",payload:JSON.parse(sessionStorage.getItem(e)||"{}")});break}case"rdm_widget_ready":case"rdm_widget_ready_user":window.__rdmWidgetReady=!0;(window.__rdmWidgetMessageQueue||[]).forEach(e=>J(e)),window.__rdmWidgetMessageQueue=[],window.__rdmLaunchPending&&(console.info("🚀 Widget Ready - Firing Pending Launch"),J({type:"rdm_dash_launched",payload:"{}"}),window.__rdmLaunchPending=!1);break;case"rdm_apply_discount":if(!e.data.code)return void F({message:"No discount code provided"});sessionStorage.setItem("discount_code",e.data.code),A(),window.location.href="/cart"}}));const e=document.querySelector("#rdmWidgetLoadDiv"),t=e?.getAttribute("data-rdm_domain"),r=e?.getAttribute("data-rdm_id"),o=`https://ripplrewards.nyc3.digitaloceanspaces.com/live/store/${t||window.location.hostname}/store_setting.json?v=${Date.now()}`,n="https://storepanel.rediem.io/api",a="https://api.rediem.io/api",i=new URL(window.location.href),s=window.location.pathname,c=document.body,d=["/cart/add.js","/cart/update.js","/cart/change.js","/cart/clear.js","/cart/add","/cart/update","/cart/change","/cart/clear"],p="__staging-1stapril-store.myshopify.com___"===t?"https://wear-phases-favors-hometown.trycloudflare.com":"https://widget.rediem.io",l=i.hash||"",u=i.searchParams.get("widgetpreview")||"",m=u.trim().length>0,g=new URLSearchParams({shopDomain:t,rediem_hash:l}),w=`${p}${g.toString()?`?${g.toString()}`:""}`,h=await async function(e){if(!e)return null;const t=`setting_${e}`;try{const e=await fetch(o,{headers:{Accept:"application/json"}});if(!e.ok)return console.warn("Failed to fetch settings:",e.status,e.statusText),null;const r=await e.json();if(r?.shopId)return sessionStorage.setItem(t,JSON.stringify({data:r,timestamp:Date.now()})),r}catch(e){console.warn("Error fetching settings:",e)}return null}(t);if(!h)return void console.warn("Settings not found");const{launchIconPlacement:f="top_left",launchButtonIndex:y=50}=h,_=(h?.launchText??"Rewards")?.trim().length?h?.launchText:h?.programName,S=h?.launchTextGuest?.trim().length?h?.launchTextGuest:_,v=`${h?.widgetPlacement}: ${h?.sideSpacing}px;`,I=document.createElement("style");I.textContent=`@import url(${h?.fontFamilyLink});`,document.head.appendChild(I);const k=h?.hideOn?.trim(),b=k?k.split(",").map(e=>e.trim()).filter(Boolean):[],P=b.length>0&&b.some(e=>s.includes(e)),$=h?.showOn?.trim(),C=$?$.split(",").map(e=>e.trim()).filter(Boolean):[],L=C.length>0&&C.some(e=>s.includes(e)),O=sessionStorage.getItem("hideRediemBtn");($?!L||O:P||O)&&c.classList.add("hide-rediem-btn");const T=`\n \n
\n \n
`,E=document.createRange().createContextualFragment(T);if(E.querySelector("#ripplFectButton")?.addEventListener("click",x),E.querySelector("#rippleRewardBtnClose")?.addEventListener("click",function(){const e=document.querySelector(".ripple-frame-container"),t=document.querySelector("#rippleFect-container"),r=document.querySelector("body");e?.classList.remove("show"),t?.classList.remove("widget-open"),r?.classList.remove("rippl-widget--open")}),E.querySelector("#hideRediemBtn")?.addEventListener("click",function(e){e.stopPropagation(),c.classList.add("hide-rediem-btn"),sessionStorage.setItem("hideRediemBtn","true")}),m&&u==h?.uniqueCode)return N()?void console.warn("Rippl widget already injected. Skipping..."):(c.appendChild(E),void x());if("active"!==h?.programStatus||h?.finishLater)return;const R=await async function(){const e=`user_${t}`;let r;try{const t=await fetch("/apps/next-proxy",{method:"GET",headers:{"Content-Type":"application/json"}});if(t.ok){const{data:o}=await t.json();return sessionStorage.setItem(e,JSON.stringify({data:o,timestamp:Date.now()})),r=o,o}if(404===t.status){if("User not found"===(await t.json()).message)throw new Error("User not found")}}catch(e){console.warn(`Error fetching customer: ${e.message}`)}finally{!function(e){try{if(!e||"delete"===e.status||!e.memberSince||(e?.tags??[])?.includes("rediem-loyalty-member"))return;fetch(`${a}/dash/tags`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.token}`},body:JSON.stringify({tag:"rediem-loyalty-member"})}).then(e=>{e.ok||console.warn("Failed to update customer tags:",e.statusText)}).catch(e=>{console.warn(`Error updating customer tags: ${e.message}`)})}catch(e){console.warn("Unexpected error while adding loyalty tag:",e)}}(r)}}();if(r||sessionStorage.removeItem(`user_${t}`),r&&R&&!["active","delete"].includes(R?.status))return;if(N())return void console.warn("Rippl widget already injected. Skipping...");if(R){const e=E.querySelector("#RippleRewards");if(e){const t=new URL(e.src);if(R?.status&&t.searchParams.set("status",R.status),R?.token){t.searchParams.set("token",R.token);const e=!!R.memberSince;"1"!==h?.optIn||e||t.searchParams.set("optIn","true")}e.src=t.toString()}}if(c.appendChild(E),r&&R){const e=JSON.parse(sessionStorage.getItem("ripplRewardData")??"{}");if(e?.rdashtrigger){if(!R?.token)return void console.warn("[Rediem] rdashtrigger: skipping auto-launch, customer has no token.");if(!R.memberSince){R.memberSince=(new Date).toISOString();try{await fetch(`${a}/dash/opt-in`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${R?.token}`}})}catch(e){console.warn("[Rediem] opt-in request failed:",e.message)}}if(!R?.widgetSignup)try{await async function(){try{await fetch(`${a}/dash/customer`,{headers:{"Content-Type":"application/json",Authorization:`Bearer ${R?.token}`},method:"PATCH",body:JSON.stringify({widgetSignup:!0})})}catch(e){return console.warn(`Error in API request: ${e.message}`),null}}(),sessionStorage.removeItem("ripplRewardData")}catch(e){console.warn("[Rediem] updateCustomer failed:",e.message)}x()}}if("active"==h?.tierStatus&&R?.freeShipping&&R?.couponCode){var j=R?.couponCode;D(j)}const q=document.querySelectorAll(`a[href="${h?.embedLink}"]`);function N(){return null!==document.querySelector("#rippleFect-container")||null!==document.querySelector("#ripplFectButton")}function x(e){const t=document.querySelector(".ripple-frame-container");if(!t)return;const o=document.querySelector("#rippleFect-container"),n=t?.classList.contains("show");if(n){if(e)return void(window.__rdmWidgetReady?J({type:"rdm_dash_launched",payload:"{}"}):(console.info("⏳ Launch triggered but widget not ready. Setting Pending flag."),window.__rdmLaunchPending=!0));t?.classList.remove("show"),o?.classList.remove("widget-open"),c.classList.remove("rippl-widget--open")}else r&&async function(e){if("delete"!=R?.status)try{const t=sessionStorage.getItem("action_deeplink");t&&(e.action_deeplink=JSON.parse(t));const r=await fetch(`${a}/dash/customer/activity`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:`Bearer ${R?.token}`}});r.ok||console.warn("Activity tracking failed:",r.statusText)}catch(e){console.warn({activityError:e})}}({type:"dash-view",docId:void 0}),window.__rdmWidgetReady?J({type:"rdm_dash_launched",payload:"{}"}):(console.info("⏳ Launch triggered (Open). Setting Pending flag."),window.__rdmLaunchPending=!0),t?.classList.add("show"),o?.classList.add("widget-open"),c.classList.add("rippl-widget--open")}function F(e,t="cartUpdated"){const r=document.getElementById("RippleRewards"),o={type:t,data:e,..."cartUpdated"===t&&{cart:e}};r?.contentWindow.postMessage(o,"*")}function J(e){if(!window.__rdmWidgetReady)return window.__rdmWidgetMessageQueue=window.__rdmWidgetMessageQueue||[],void window.__rdmWidgetMessageQueue.push(e);const t=document.getElementById("RippleRewards");t?.contentWindow.postMessage(e,"*")}function B(e){return e?e.split("#")[0].split("?")[0].replace(/\/$/,""):""}async function D(e){if(e){sessionStorage.setItem("discount_code",e);try{await fetch(`/discount/${e}`)}catch(e){console.warn("Error applying discount:",e)}}}async function A(){const e=sessionStorage.getItem("discount_code");if(e)try{const t=await fetch("/cart.js"),r=await t.json();r.items.some(t=>t.discounts?.some(t=>t.title===e))||await fetch(`/discount/${e}`)}catch(e){console.warn("Error applying stored discount:")}}async function M(){try{const e=(await W()).map(e=>e.variant_id),r=sessionStorage.getItem("previousCartItemIds");(function(e,t){if(e.length!==t.length)return!1;const r=[...e].sort(),o=[...t].sort();return r.every((e,t)=>e===o[t])})(e,r?JSON.parse(r):[])&&0!==e.length||(await async function({varients:e,empty:r=!1}){const o=new Headers,n=`user_${t}`,i=JSON.parse(sessionStorage.getItem(n)||"{}");if(!i?.data?.token)return console.error("No customer token found"),!1;o.append("Authorization",`Bearer ${i?.data?.token}`),o.append("Content-Type","application/json");const s={method:"POST",headers:o,body:JSON.stringify({varients:e,empty:r})};await fetch(`${a}/product-reward/remove`,s)}({varients:e}),sessionStorage.setItem("previousCartItemIds",JSON.stringify(e)))}catch(e){console.error("Error updating cart variants:",e)}}async function U({products:e,subscription:t=!1}){let r=await W();const o=sessionStorage.getItem("opt_type");try{const a=t?z():H();if(!a)return;if(a?.requiredPaidProduct){if(!await Q({cartItems:r,freeProducts:a}))return}if(a?.perCartLimit){const e=function({cartItems:e,freeProducts:t}){const r=e?.filter(e=>t?.productData?.find(t=>t?.varientId==e.variant_id));if(r?.length>0)throw new Error("You can only add one free product!");return!1}({cartItems:r,freeProducts:a});if(e)return}const i=r.map(e=>e.variant_id),s=e.filter(e=>!i.includes(e.variantId));if(0===s.length)throw new Error("Product already in cart!");const c=s.map(async e=>{const t=new URLSearchParams,r=e.variantId;t.append("id",r),t.append("quantity",e.quantity);const o=await fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!o.ok){const e=await o.json();throw new Error(`${e?.message}: ${e?.description}`)}return o});await Promise.all(c),r=await W();const d=r?.find(e=>e.discounts.length>0)?.discounts[0].title??null,p=a?.perCartLimit?a?.productData.filter(t=>e.some(e=>e.variantId===t.varientId)):a?.productData.filter(e=>r.some(t=>t.variant_id===e.varientId)),l=a?.productDocId,u="addProductToCartSubscription"==o?p.map(e=>e.docId):p.map(e=>e.productDocId),m=t?await async function({freeProductsData:e,couponCode:t}){const r=new Headers;r.append("Authorization",`Bearer ${e?.token}`),r.append("Content-Type","application/json");const o={method:"POST",headers:r,body:JSON.stringify({id:e?.docId,couponCode:t}),redirect:"follow"};try{const e=await fetch(`${n}/waysToEarn/subscription/`,o);if(e.ok){const t=await e.json();return await D(t?.data?.couponCode),!0}return console.error("Failed to generate coupon:",e.statusText),!1}catch(e){console.error("Error generating coupon:",e)}}({freeProductsData:a,productDocIds:u,couponCode:d}):await async function({freeProductsData:e,productDocIds:t,couponCode:r,currProdId:o}){const a=new Headers;a.append("Authorization",`Bearer ${e?.token}`),a.append("Content-Type","application/json");const i={method:"POST",headers:a,body:JSON.stringify({actionDocId:e?.actionDocId,productDocId:t,couponCode:r,productId:o}),redirect:"follow"};try{const e=await fetch(`${n}/waysToRedeem/free_product/`,i);if(e.ok){const t=await e.json();return await D(t.coupon),!0}return console.error("Failed to generate coupon:"),!1}catch(e){return console.error("Error generating coupon:"),!1}}({freeProductsData:a,productDocIds:u,couponCode:d,currProdId:l});m?window.location.href="/cart":(F({message:"Failed to generate coupon",items:r}),console.error("Failed to generate coupon"))}catch(e){console.error(e.message),F({message:e?.message??"Failed to add product to cart!",items:r})}}async function W(){const e=await fetch("/cart.js");if(!e.ok)throw new Error("Failed to fetch cart contents");return(await e.json()).items}function z(){const e=sessionStorage.getItem("freeProductsSubscription");if(!e)throw new Error("Something went wrong!");return JSON.parse(e)}function H(){const e=sessionStorage.getItem("freeProducts");if(!e)throw new Error("Something went wrong!");return JSON.parse(e)}async function Q({cartItems:e,freeProducts:t,error:r=!0}){const o=e?.filter(e=>t?.productData?.find(t=>t?.varientId!=e.variant_id));if(o?.length<1){if(r)throw new Error("To redeem a free product, you must add a paid product to cart!");await Y(e)}return!0}function G({cartItems:e,error:t=!0}){return e.reduce((e,t)=>e+t.final_line_price,0)>0}async function Y(e){try{for(const t of e){const e=new URLSearchParams;e.append("id",t.id),e.append("quantity",0);(await fetch("/cart/change.js",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()})).ok||console.error("Error removing item:")}}catch(e){console.error("Error removing items:")}finally{try{await M()}catch(e){console.error("Error in finally block:",e)}location.reload()}}q&&q.length>0&&q.forEach(e=>{e.addEventListener("click",function(e){e.preventDefault(),x()})}),async function(e){const t=i.hash,r=e.replace("#","");""!=t.replace("#","")&&window.location.hash.includes(r)&&x()}(h?.embedLink),async function(e){if(!e)return null;const t=sessionStorage.getItem("link_actions");if(t)try{const e=JSON.parse(t);if(e)return e}catch(e){console.warn("Failed to parse cached link actions:",e)}try{const t=await fetch(`${a}/v0/dash/link-actions?shop=${encodeURIComponent(e)}`);if(!t.ok)return null;const r=await t.json(),o=B(window.location.href),n=r?.data?.find(e=>B(e?.trackingLink)===o);return!!n&&(sessionStorage.setItem("link_actions",JSON.stringify(n)),n)}catch(e){console.warn("Error getting link actions:",e)}}(t);const X=window.fetch;window.fetch=async function(...e){try{const t=await X.apply(this,e);let r="";if("string"==typeof e?.[0]?r=e[0]:e?.[0]instanceof Request?r=e?.[0].url:t?.url&&(r=t.url),"string"==typeof r&&r){if(!d.some(e=>r.includes(e)))return t;try{const e=t.clone(),r=await e.json();if(r?.items?.length>0){const e=sessionStorage.getItem("opt_type"),t=r?.items?.some(e=>e.properties?._rediem_paid),o=r?.items?.some(e=>e.properties?._rediem_per_cart);if(t){G({cartItems:r?.items})||await Y(r?.items)}if(o&&async function(e){const t=[],r=e?.filter(e=>e.properties&&e.properties._rediem_gift_card);try{r?.length>0&&r.forEach(e=>{e.quantity>1&&t.push({id:e.variant_id,quantity:1})}),t.length>0&&(alert("Only single quantity is allowed for some items in your cart!"),await Promise.all(t.map(e=>{const t=new URLSearchParams;return t.append("id",e.id.toString()),t.append("quantity",e.quantity.toString()),fetch("/cart/change.js",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()})})))}catch(e){console.error("Error enforcing single item quantity:",e)}finally{try{await M()}catch(e){console.error("Error sending cart variants:",e)}t.length>0&&location.reload()}}(r?.items),e){const t="addProductToCart"===e?H():"addProductToCartSubscription"===e?z():null;t?.requiredPaidProduct&&await Q({cartItems:r?.items,freeProducts:t,error:!1}),t?.perCartLimit&&await async function({cartJson:e,freeProduct:t}){const r=[],o=e?.items?.filter(e=>t?.productData?.find(t=>t?.varientId==e.variant_id));o?.length>0&&o.forEach(e=>{e.quantity>1&&r.push({id:e.variant_id,quantity:1})}),r.length>0&&(alert("Only single quantity is allowed!"),await Promise.all(r.map(e=>{const t=new URLSearchParams;return t.append("id",e.id),t.append("quantity",e.quantity),fetch("/cart/change.js",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()})})),location.reload())}({cartJson:r,freeProduct:t})}}}catch(e){console.error("Error in custom cart handling:")}finally{const e=JSON.parse(sessionStorage.getItem("cartFlags")||"{}");("true"===e._rediem_gift_card||!0===e._rediem_gift_card)&&await M()}}return t}catch(e){throw console.error("Fetch error:"),e}},A()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()})();