var h = /* @__PURE__ */ ((e) => (e.COLLECTION_VIEW = "collection_view", e.PRODUCT_VIEW = "product_view", e.PRODUCT_CLICK = "product_click", e.ADD_TO_CART = "add_to_cart", e.SEARCH = "search", e))(h || {}), a = /* @__PURE__ */ ((e) => (e.BROWSE = "browse", e.SEARCH = "search", e.SIMILAR = "similar", e))(a || {}); const E = { LAYERS_CONFIG: '#layers-config, script[type="application/layers-config"]', LAYERS_CONTEXT: "#layers-session-context", CART_FORMS: 'form[action*="/cart/add"]', PRODUCT_FORM: 'input[name="form_type"][value="product"]', ATTRIBUTION_INPUT: 'input[name="properties[_layers_attribution]"]' }, y = { STATE: "_layersnextpage", REF: "_layersnextpageref" }, M = { SHOPIFY_SESSION: "_shopify_y", TAG_USER: "tag_user_id" }, k = { PRODUCTS: "/products/", COLLECTIONS: "/collections/", SEARCH: "/search" }, O = { CART_ADD: /\/cart\/add\.js/, BROWSE_HANDLE: /\/browse\/([^/?]+)/, SEARCH_QUERY: /\/search\/([^/?]+)\/execute/, SEARCH_PRODUCT: /\/search\/product\/(\d+)/, SIMILAR_PRODUCT: /\/similar\/(\d+)/ }, V = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"], Y = [ h.COLLECTION_VIEW, h.PRODUCT_VIEW, h.PRODUCT_CLICK, h.ADD_TO_CART, h.SEARCH ], _ = (e) => { try { return JSON.parse(e); } catch { return null; } }, v = (e) => { const r = `; ${document.cookie}`.split(`; ${e}=`); return r.length === 2 ? r.pop()?.split(";").shift() : void 0; }, K = (e, t) => { const r = document.createElement("input"); return r.type = "hidden", r.name = e, r.value = t, r; }, X = (e) => e >= 200 && e < 300, J = (e) => typeof e == "string" ? +e.replace(/[^0-9.]/g, "") : e / 100, x = (e) => e.split("/").filter(Boolean), P = /* @__PURE__ */ new Map(), b = (e, t) => t.some((r) => { if (!P.has(r)) { const n = r.replace(/\{[^}]+\}/g, "[^/?]+").replace(/\//g, "\\/").replace(/\./g, "\\."); P.set(r, new RegExp(`${n}(?:\\?|$)`)); } return P.get(r).test(e); }), j = (e) => { if (!e.startsWith(k.COLLECTIONS)) return null; const t = x(e); return t.length > 1 ? t[1] : null; }, Z = () => ({ attributionTokens: { [a.BROWSE]: null, [a.SEARCH]: null, [a.SIMILAR]: null }, experimentId: null, experimentGroup: null, results: [], collectionHandleFromBrowse: null, searchQuery: null, similarProductId: null }); function ee() { const e = localStorage.getItem(y.STATE), t = localStorage.getItem(y.REF), r = location.href; if (e && (t === document.referrer || t === r)) { const n = _(e); if (n) return n.attributionToken && !n.attributionTokens && (n.attributionTokens = { [a.BROWSE]: n.attributionToken, [a.SEARCH]: null, [a.SIMILAR]: null }, n.attributionToken = void 0), n; } return te(), Z(); } function te() { localStorage.removeItem(y.STATE), localStorage.removeItem(y.REF); } function D(e) { localStorage.setItem(y.STATE, JSON.stringify(e)), localStorage.setItem(y.REF, location.href); } const re = { fb: "facebook", ig: "instagram", tw: "twitter", x: "twitter", li: "linkedin", yt: "youtube", goog: "google", pin: "pinterest", tiktok: "tiktok", snap: "snapchat", reddit: "reddit", email: "email" }, ne = { cpc: "cpc", ppc: "cpc", paid: "cpc", organic: "organic", seo: "organic", referral: "referral", ref: "referral", social: "social", email: "email", display: "display", banner: "display", affiliate: "affiliate", aff: "affiliate" }; function oe(e) { if (!e || e.trim() === "") return null; const t = e.toLowerCase().trim(); return re[t] ?? t; } function ie(e) { if (!e || e.trim() === "") return null; const t = e.toLowerCase().trim(); return ne[t] ?? t; } function se(e) { return !e || e.trim() === "" ? null : e.toLowerCase().trim(); } function ce() { const e = {}, t = document.querySelector(E.LAYERS_CONTEXT); t?.innerHTML && Object.assign(e, _(t.innerHTML) || {}); const r = new URLSearchParams(location.search); for (const n of V) { const i = r.get(n); if (i) { let o = i; n === "utm_source" ? o = oe(i) : n === "utm_medium" ? o = ie(i) : n === "utm_campaign" && (o = se(i)), o && (localStorage.setItem(`lyrs_${n}`, o), e[n.replace("utm_", "marketing_")] = o); } } return e; } function H(e) { let t = v(M.SHOPIFY_SESSION); if (!t) { for (const r of e.sessionCookieFallbacks) if (t = v(r), t) break; } return t ?? crypto.randomUUID(); } const B = () => { const e = window.ShopifyAnalytics?.meta?.page?.customerId; return e ? String(e) : null; }, ae = () => "edgetag" in window ? window.edgetag("getUserId") : v(M.TAG_USER); function le() { const e = window.Shopify; return e?.customerPrivacy ? e.customerPrivacy.analyticsProcessingAllowed() : !0; } const ue = () => (/* @__PURE__ */ new Date()).toISOString(); function A(e, t) { const r = t ? e.attributionTokens[t] : e.attributionTokens.browse ?? e.attributionTokens.search ?? e.attributionTokens.similar; return { experiment_id: e.experimentId, experiment_group: e.experimentGroup, attribution_token: r }; } const R = /* @__PURE__ */ new Set(); let g = null; const de = 50; function L(e) { if (!R.size) return; const t = new URL(e.endpoints.beacon); e.apiToken && t.searchParams.set("token", e.apiToken); const r = [...R].reverse(); R.clear(), g && (clearTimeout(g), g = null); const n = new Blob([JSON.stringify({ events: r })], { type: "application/json" }); if (navigator.sendBeacon?.(t.toString(), n)) { console.debug(`Sent ${r.length} events via beacon`); return; } fetch(t.toString(), { method: "POST", body: n, keepalive: !0, headers: { "Content-Type": "application/json" } }).catch((i) => { console.error("Failed to send events:", i), r.forEach((o) => R.add(o)); }); } const pe = (e) => { g || (g = requestAnimationFrame(() => { g = null, L(e); })); }, fe = (e) => { if (window.__eventFlushRegistered) return; const t = () => L(e); addEventListener("visibilitychange", () => document.visibilityState === "hidden" && t()), addEventListener("beforeunload", t), addEventListener("focus", () => R.size && t()), window.__eventFlushRegistered = !0; }; function I(e, t, r) { if (!le()) { console.debug("Analytics not allowed, skipping event:", e); return; } if (e === h.PRODUCT_CLICK && (!t.product_id || !t.position)) { console.error("Missing required fields for product_click event:", t); return; } if (!Y.includes(e)) { console.warn("Invalid event type:", e); return; } R.add({ event_id: crypto.randomUUID(), event_type: e, timestamp: ue(), session_id: H(r), customer_id: B(), ...t }), console.debug("Queued event:", e, t), fe(r), pe(r), R.size >= de && L(r); } function me(e, t, r, n, i, o) { if (e.attributionToken && (n.attributionTokens[r] = e.attributionToken), r === a.BROWSE && o?.collectionHandle ? n.collectionHandleFromBrowse = o.collectionHandle : r === a.SEARCH && o?.searchQuery ? n.searchQuery = o.searchQuery : r === a.SIMILAR && o?.similarProductId && (n.similarProductId = o.similarProductId), e.results?.length) { const c = e.results.map((s) => ({ handle: s.handle, id: +s.id, source: r, attributionToken: e.attributionToken })); n.results = n.results.filter((s) => s.source !== r), n.results.push(...c), console.debug(`Stored ${c.length} ${r} results for click tracking`, { newResults: c.length, totalResults: n.results.length, resultsBySource: Object.fromEntries( Object.values(a).map((s) => [s, n.results.filter((l) => l.source === s).length]) ) }); } if (e._meta?.experimentsRan?.length) { const c = e._meta.experimentsRan[0]; n.experimentId = c.experimentId, n.experimentGroup = c.experimentGroup, typeof window.gtag == "function" && window.gtag("event", "experience_impression", { exp_variant_string: `LAYERS-${c.experimentId}-${c.experimentGroup}` }); } r === a.BROWSE && I( h.COLLECTION_VIEW, { ...A(n, r), sort_order_id: t.sort_order_code, collection_handle: o?.collectionHandle }, i ), D(n); } function q(e, t, r, n) { if (!t || t.error) return; const i = Array.isArray(e.items) ? e.items : [e]; for (const o of i) { const c = o.product_id ?? o["product-id"], s = o.id ?? o.variant_id, l = +(o.quantity ?? 1); let d = 0; if (t.items) { const S = t.items.find( (p) => String(p.variant_id) === String(s) || String(p.product_id) === String(c) ); S && (d = S.price / 100 * l); } else t.price && t.variant_id === +s && (d = t.price / 100 * l); I( h.ADD_TO_CART, { ...A(r), product_id: c, variant_id: s, quantity: l, value: d }, n ); } } function U(e, t) { return b(e, t.routePatterns[a.BROWSE]) ? a.BROWSE : b(e, t.routePatterns[a.SEARCH]) ? a.SEARCH : b(e, t.routePatterns[a.SIMILAR]) ? a.SIMILAR : null; } function N(e, t, r) { const n = {}; if (t === a.BROWSE) { if (r.routePatterns[a.BROWSE].find((o) => b(e, [o]))?.includes("{collectionHandle}")) { const o = e.match(O.BROWSE_HANDLE); o && (n.collectionHandle = decodeURIComponent(o[1])); } } else if (t === a.SEARCH) { const i = e.match(O.SEARCH_QUERY); i && (n.searchQuery = decodeURIComponent(i[1])); const o = e.match(O.SEARCH_PRODUCT); o && (n.searchProductId = +o[1]), e.includes("/search/image") && (n.searchType = "image"); } else if (t === a.SIMILAR) { const i = e.match(O.SIMILAR_PRODUCT); i && (n.similarProductId = +i[1]); } return n; } const he = [ { name: "layers-api", match: (e, t) => e.method.toUpperCase() !== "POST" ? !1 : U(e.url, t) !== null }, { name: "cart-add", match: (e) => O.CART_ADD.test(e.url) } ], Se = { "layers-api": { name: "layers-api", processRequest: (e, t, r) => { const n = typeof e == "string" ? _(e) || {} : e; return n.identity ??= { sessionId: H(r), customerId: B() ?? void 0, deviceId: ae() }, n.context = { ...t, ...n.context ?? {} }, JSON.stringify(n); } }, "cart-add": { name: "cart-add", processRequest: (e, t, r) => Ce(e, r) } }, W = { "layers-api": { name: "layers-api", processResponse: (e, t, r, n, i, o) => { const c = typeof t == "string" ? _(t) || {} : t; me(e, c, i, r, n, o); } }, "cart-add": { name: "cart-add", processResponse: (e, t, r, n) => { q(t, e, r, n); } } }; function _e(e, t, r, n) { Re(e, t, r), ge(e, t, r); } function Re(e, t, r) { const n = window.fetch; window.fetch = async (...i) => { const [o, c] = i, s = ye(o, c); if (!s.url || !s.method) return n(...i); const l = z(s, r); if (l.length === 0) return n(...i); let d = i, S = s.body, p = null, f = {}; for (const u of l) { u === "layers-api" && (p = U(s.url, r), f = { ...N(s.url, p, r) }); const C = $(u, s, t, r); C.modifiedBody && (d = Te(i, C.modifiedBody), C.originalData && (S = C.originalData)); } const m = await n(...d); for (const u of l) Ee(u, m, S, e, r, p ?? u, f); return m; }; } function ge(e, t, r) { const n = XMLHttpRequest.prototype.open, i = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.open = function(o, c, s = !0, l, d) { return this.__layers_request = { method: o, url: c.toString() }, n.apply(this, [o, c, s, l, d]); }, XMLHttpRequest.prototype.send = function(o) { const c = this.__layers_request; if (!c) return i.apply(this, [o]); const s = { url: c.url, method: c.method, body: o }, l = z(s, r); if (l.length === 0) return i.apply(this, [o]); let d = o, S = o, p = null, f = {}; for (const m of l) { m === "layers-api" && (p = U(s.url, r), f = { ...N(s.url, p, r) }); const u = $(m, s, t, r); u.modifiedBody && (d = u.modifiedBody, u.originalData && (S = u.originalData)); } for (const m of l) this.addEventListener("load", function() { if (X(this.status)) try { const u = _(this.responseText); u && W[m]?.processResponse( u, S, e, r, p ?? m, f ); } catch (u) { console.error(`Error handling ${m} response:`, u); } }); return i.apply(this, [d]); }; } function z(e, t) { return he.filter((r) => r.match(e, t)).map((r) => r.name); } function $(e, t, r, n) { try { const i = Se[e]; if (!i) return {}; let o = null; return e === "cart-add" && t.body && (o = Ie(t.body)), { modifiedBody: i.processRequest(t.body, r, n), originalData: o }; } catch (i) { return console.error(`Error processing ${e} request:`, i), {}; } } function Ee(e, t, r, n, i, o, c) { const s = W[e]; if (s) try { t.clone().json().then((d) => { s.processResponse(d, r, n, i, o, c); }); } catch (l) { console.error(`Error processing ${e} response:`, l), e === "cart-add" && r && q(r, null, n, i); } } function ye(e, t) { let r, n; if (Q(e)) r = e.url, n = e.method; else if (typeof e == "string" || e instanceof URL) r = e.toString(), n = t?.method ?? "GET"; else return { url: "", method: "" }; return { url: r, method: n, body: t?.body }; } function Q(e) { return e && typeof e == "object" && "url" in e && "method" in e && typeof e.url == "string"; } function Te(e, t) { const [r, n] = e; return Q(r) ? [new Request(r, { body: t }), n] : [r, { ...n, body: t }]; } function Ie(e) { if (!e) return null; try { if (typeof e == "string") return e.startsWith("{") ? _(e) : Object.fromEntries(new URLSearchParams(e).entries()); if (e instanceof FormData) return Object.fromEntries(e.entries()); } catch (t) { console.error("Error parsing request body:", t); } return null; } function Ce(e, t) { if (!e) return e; const r = H(t); if (typeof e == "string") { if (e.startsWith("{")) { const i = _(e) || {}; return i.attributes = i.attributes ?? {}, i.attributes._layers_session_id = r, JSON.stringify(i); } const n = new URLSearchParams(e); return n.has("attributes[_layers_session_id]") || n.set("attributes[_layers_session_id]", r), n.toString(); } return e instanceof FormData && (e.has("attributes[_layers_session_id]") || e.set("attributes[_layers_session_id]", r)), e; } function Oe(e) { let t = {}; const r = document.querySelector(E.LAYERS_CONFIG); return r?.textContent && (t = _(r.textContent) ?? {}), { sessionCookieFallbacks: t.sessionCookieFallbacks ?? e.sessionCookieFallbacks, apiToken: t.apiToken, endpoints: e.endpoints, routePatterns: e.routePatterns, productCardSelectors: t.productCardSelectors ?? e.productCardSelectors }; } function Ae(e, t, r, n, i) { if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey || e.button !== 0) return; const o = e.target?.closest("a"); if (!o?.href?.includes(k.PRODUCTS)) return; let c; try { const f = new URL(o.href, location.origin), m = x(f.pathname), u = m.indexOf("products"); if (u === -1 || u + 1 >= m.length || (c = m[u + 1], !c)) return; } catch (f) { console.error("Error parsing product URL:", o.href, f); return; } const s = r.results.find((f) => f.handle === c); if (!s) { console.debug(`No tracking data found for product handle: ${c}`); return; } const l = s.attributionToken ?? r.attributionTokens[s.source], S = r.results.filter((f) => f.source === s.source).findIndex((f) => f.handle === c) + 1; if (!s.id || S <= 0) { console.error("Invalid click tracking data:", { productId: s.id, position: S, handle: c, source: s.source }); return; } const p = {}; s.source === a.BROWSE ? p.collection_handle = r.collectionHandleFromBrowse ?? t : s.source === a.SEARCH ? p.search_query = r.searchQuery : s.source === a.SIMILAR && (p.similar_product_id = r.similarProductId), I( h.PRODUCT_CLICK, { product_id: s.id, product_handle: c, position: S, attribution_token: l, request_source: s.source, contextual_data: p }, i ), L(i), D(r); } const T = /* @__PURE__ */ new Map(); let w = null; function be(e, t, r, n) { I(h.PRODUCT_VIEW, { product_id: e.product.id, ...A(t) }, n), F(e.product.id).length > 0 && (ke(), G(e, t, n), Pe(e, t, n)); } const ke = () => { T.forEach((e) => e()), T.clear(), w?.disconnect(), w = null; }, F = (e) => [...document.querySelectorAll(E.CART_FORMS)].filter( (t) => t.querySelector(E.PRODUCT_FORM) && t.querySelector(`input[name="product-id"][value="${e}"]`) ), we = (e, t) => { const r = t.attributionTokens.browse ?? t.attributionTokens.search ?? t.attributionTokens.similar; if (r) try { let n = e.querySelector(E.ATTRIBUTION_INPUT); n ? n.value = r : (n = K("properties[_layers_attribution]", r), e.appendChild(n)); } catch (n) { console.error("Failed to add attribution to form", n); } }, Le = (e, t, r, n) => () => { const i = new FormData(e), o = i.get("id")?.toString(), c = +(i.get("quantity")?.toString() ?? "1"); if (o) { const s = t.product.variants.find((d) => String(d.id) === o), l = s?.price ? J(s.price) * c : 0; I( h.ADD_TO_CART, { ...A(r), product_id: t.product.id, variant_id: o, quantity: c, value: l }, n ); } }, G = (e, t, r) => { const n = F(e.product.id); for (const i of n) { if (T.has(i)) continue; we(i, t); const o = Le(i, e, t, r); i.addEventListener("submit", o), T.set(i, () => i.removeEventListener("submit", o)); } }, Pe = (e, t, r) => { F(e.product.id).length && (w = new MutationObserver((n) => { n.some((o) => o.type === "childList" ? [...o.addedNodes, ...o.removedNodes].some( (c) => c instanceof HTMLElement && (c.querySelector(E.CART_FORMS) || [...c.querySelectorAll("form")].some((s) => T.has(s))) ) : o.type === "attributes" && o.target instanceof HTMLFormElement && T.has(o.target)) && G(e, t, r); }), w.observe(document.body, { childList: !0, subtree: !0, attributes: !0, attributeFilter: ["action", "id"] })); }; function ve(e, t, r, n) { I(h.SEARCH, { search_query: e.search_query, ...A(t) }, n); } function He() { const e = new AbortController(), t = ee(); addEventListener("beforeunload", () => { e.abort("navigation"); }); const r = Oe({ sessionCookieFallbacks: ["_ga"], endpoints: { beacon: "https://cl.uselayers.com/beacon" }, routePatterns: { [a.BROWSE]: ["/api/storefront/v1/browse/{collectionHandle}"], [a.SEARCH]: [ "/api/storefront/v1/search/image", "/api/storefront/v1/search/{searchQuery}/execute", "/api/storefront/v1/search/product/{searchProductId}" ], [a.SIMILAR]: ["/api/storefront/v1/similar/{productId}"] }, productCardSelectors: [".product-card", ".product-item", "product-card"] }), n = ce(); _e(t, n, r), Ue(t, n, r); } function Ue(e, t, r) { const n = location.pathname, i = j(n); if (window.__layersClickTrackingInitialized || (document.addEventListener( "click", (o) => { try { Ae(o, i, e, t, r); } catch (c) { console.error("Error in click tracking:", c); } }, { passive: !0 } ), window.__layersClickTrackingInitialized = !0), n.includes(k.PRODUCTS) && fetch(`${n}.json`, { priority: "low" }).then((o) => o.ok ? o.json() : null).then((o) => { o && be(o, e, t, r); }).catch((o) => console.error("Error fetching product data:", o)), n.includes(k.SEARCH)) { const o = new URLSearchParams(window.location.search); o.has("q") && ve( { search_query: o.get("q") }, e, t, r ); } } He();