(self.webpackChunkclient=self.webpackChunkclient||[]).push([[3],{3:(e,t,n)=>{"use strict";n.d(t,{default:()=>y});var a=n(258);const i=(...e)=>{console.log("[klarna-osm]",...e)},r=e=>new Promise((t=>setTimeout(t,e)));var o=n(991);const s={"Europe/Vienna":"AT","Australia/Lord_Howe":"AU","Antarctica/Macquarie":"AU","Australia/Hobart":"AU","Australia/Currie":"AU","Australia/Melbourne":"AU","Australia/Sydney":"AU","Australia/Broken_Hill":"AU","Australia/Brisbane":"AU","Australia/Lindeman":"AU","Australia/Adelaide":"AU","Australia/Darwin":"AU","Australia/Perth":"AU","Australia/Eucla":"AU","Europe/Brussels":"BE","America/St_Johns":"CA","America/Halifax":"CA","America/Glace_Bay":"CA","America/Moncton":"CA","America/Goose_Bay":"CA","America/Blanc-Sablon":"CA","America/Toronto":"CA","America/Nipigon":"CA","America/Thunder_Bay":"CA","America/Iqaluit":"CA","America/Pangnirtung":"CA","America/Resolute":"CA","America/Atikokan":"CA","America/Rankin_Inlet":"CA","America/Winnipeg":"CA","America/Rainy_River":"CA","America/Regina":"CA","America/Swift_Current":"CA","America/Edmonton":"CA","America/Cambridge_Bay":"CA","America/Yellowknife":"CA","America/Inuvik":"CA","America/Creston":"CA","America/Dawson_Creek":"CA","America/Vancouver":"CA","America/Whitehorse":"CA","America/Dawson":"CA","Europe/Zurich":"CH","Europe/Prague":"CZ","Europe/Berlin":"DE","Europe/Busingen":"DE","Europe/Copenhagen":"DK","Europe/Madrid":"ES","Africa/Ceuta":"ES","Atlantic/Canary":"ES","Europe/Helsinki":"FI","Europe/Paris":"FR","Europe/Budapest":"HU","Europe/Rome":"IT","America/Mexico_City":"MX","America/Cancun":"MX","America/Merida":"MX","America/Monterrey":"MX","America/Matamoros":"MX","America/Mazatlan":"MX","America/Chihuahua":"MX","America/Ojinaga":"MX","America/Hermosillo":"MX","America/Tijuana":"MX","America/Santa_Isabel":"MX","America/Bahia_Banderas":"MX","Europe/Amsterdam":"NL","Arctic/Longyearbyen":"NO","Europe/Oslo":"NO","Europe/Warsaw":"PL","Europe/Lisbon":"PT","Atlantic/Madeira":"PT","Atlantic/Azores":"PT","Europe/Stockholm":"SE","Europe/Bratislava":"SK"},c="klarnaosm_user_locale";class l{static getCountryFromTimeZone(){var e;const{timeZone:t}=Intl.DateTimeFormat().resolvedOptions(),n=null!==(e=s[t])&&void 0!==e?e:null;return n||i("[getCountryFromTimeZone] unsupported country or time zone",{timeZone:t}),n}static async getUsersCountry(){let e=l.getCachedUsersCountry();if(e)return i("Found users country in cache"),e;try{const t=new AbortController;setTimeout((()=>t.abort()),1500);const n=window.location.hostname,a=Shopify.shop,i=n!==a?n:"",r=new URL(o.GEOSERVICE_URL);r.searchParams.set("defaultDomain",a),r.searchParams.set("customDomain",i);const s=await fetch(r,{signal:t.signal});if(!s.ok)throw new Error(s.statusText);e=(await s.json()).country}catch(e){return i("[getUsersCountry] Failed",e),i("[getUsersCountry] trying to parse from time zone"),this.getCountryFromTimeZone()}return e&&l.setCachedUsersCountry(e),e}static getCachedUsersCountry(){return localStorage.getItem(c)||null}static setCachedUsersCountry(e){i("Setting users country to cache",e),localStorage.setItem(c,e)}constructor(e){this.midLocales=e}static findLocale(e,t,n){var a,r;if(e){i("[getMatchingLocale] Valid locales for users country",e);const o=null!==(a=e[0])&&void 0!==a?a:null;let s="";if(t&&"undefined"!=typeof Shopify?(s=Shopify.locale,i("[getMatchingLocale] Using Shopify.locale",s)):navigator.language&&(s=navigator.language.slice(0,2),i("[getMatchingLocale] Using browser language",s)),s){const t=e.find((e=>e.startsWith(s)));if(t)return t}return n&&null!==(r=e.find((e=>e.startsWith("en"))))&&void 0!==r?r:o}return null}getMatchingLocale(e,t,n){if(!e||!this.midLocales)return i("[getMatchingLocale] Invalid data",e,this.midLocales),null;i("[getMatchingLocale] Available countries for merchant",n);const a=this.getFilteredLocales(n);i("[getMatchingLocale] Valid locales for merchant",a);const r=null==a?void 0:a[e];return l.findLocale(r,t,!0)}getFilteredLocales(e){if(!e)return this.midLocales;const t=new Set(e);return Object.keys(this.midLocales).reduce(((e,n)=>(t.has(n)&&(e[n]=this.midLocales[n]),e)),{})}getMatchingLocaleWithMidLocales(e,t){if(!e||!this.midLocales||0===Object.keys(this.midLocales).length)return i("[getMatchingLocale] Invalid data",e,this.midLocales),null;const n=this.midLocales[e];return l.findLocale(n,t,!1)}}const d=l;class u{constructor(e){this.store=e}inject(){if(!this.isOSMScriptAlreadyInjected())try{this.injectKlarnaOSMScriptTag(),i("Klarna OSM Script Tag has been added successfully")}catch(e){i("Could not add script element",e)}}isOSMScriptAlreadyInjected(){return null!==document.getElementById("klarna-osm-script-tag")}logIfEmptyClientId(){this.store.client_id||i("Creating OSM script element without data-client-id. This will cause placements not to show up. Check your configuration of Klarna OSM on the Klarna Merchant Portal.")}injectKlarnaOSMScriptTag(){const e=this.createKlarnaOSMScriptTag(),t=document.querySelector("body");t.insertBefore(e,t.children[0])}createKlarnaOSMScriptTag(){this.logIfEmptyClientId();const e=document.createElement("script"),t=this.store.playground_active?"playground":"production";return e.id="klarna-osm-script-tag",e.async=!0,e.setAttribute("data-environment",t),e.src="https://js.klarna.com/web-sdk/v1/klarna.js",e.setAttribute("data-client-id",this.store.client_id),e}}class p{static getVariantIdFromQueryString(){const e=new URLSearchParams(window.location.search).get("variant");return e?Number.parseInt(e,10):null}constructor(e,t){this.store=e,this.productVariants=t,this.conflictingAppIds=[],this.eventHandler=()=>{this.updatePlacements()},this.localeService=new d(e.mid_locales)}async init(){var e;window.klarna_OSMP=window.klarna_OSMP||{},window.klarna_OSMP.updaterId=null!==(e=window.klarna_OSMP.updaterId)&&void 0!==e?e:0,window.klarna_OSMP.rerenders=new Array(this.calculateRerendersLenBasedOnPlacementsCount()),this.conflictingAppIds=["tmenu-app"].filter((e=>!!document.getElementById(e))),this.logIfConflictingAppsDetected(),this.injectOnSiteScript(),await this.initPurchaseAmountIfCartOrProductPage(),this.listenForInputChange()}calculateRerendersLenBasedOnPlacementsCount(){var e,t,n;return 5+2*(null!==(n=null===(t=null===(e=window.klarna_OSMP)||void 0===e?void 0:e.placements)||void 0===t?void 0:t.filter((e=>e.placement_page===this.currentPageType)).length)&&void 0!==n?n:0)}logIfConflictingAppsDetected(){this.conflictingAppIds.length>0&&i(`Detected apps conflicting with Klarna placements: ${this.conflictingAppIds.join(", ")}. It may cause unwanted behaviour.`)}injectOnSiteScript(){new u(this.store).inject()}async initPurchaseAmountIfCartOrProductPage(){["cart","product"].includes(this.currentPageType)&&await this.updatePurchaseAmount()}listenForInputChange(){"cart"===this.currentPageType&&(0!==this.conflictingAppIds.length?this.updatePlacementsOnInputEvents():this.updatePlacementsOnDomMutations()),"product"===this.currentPageType&&new MutationObserver((e=>{this.getKlarnaPlacements().forEach((e=>{const t=String(this.getDataPurchaseAmount()||0),n=e.getAttribute("data-purchase-amount");t!==e.getAttribute("data-purchase-amount")&&(i(`amount changed to ${t} from ${n}`),e.setAttribute("data-purchase-amount",t))}))})).observe(document.body,{childList:!0,subtree:!0})}updatePlacementsOnDomMutations(){const e=new MutationObserver((async t=>{window.klarna_OSMP.updaterId+=1;const n=window.klarna_OSMP.updaterId,a=[void 0,void 0,await this.getCartTotal()];let o=5;if(p.addCurrentTimeToRerenders(),p.calculateMaxTimeBetweenRerenders()<1e3)return i("Detected too frequent placement rerenders based on DOM modifications. Switching logic to input related one."),o=-1,e.disconnect(),void this.updatePlacementsOnInputEvents();const s=async()=>{const e=await this.getCartTotal();return i("Comparing amount and history",e,a),!!a.some((t=>t!==e))&&(this.updatePurchaseAmount(e),a.shift(),a.push(e),!0)};for(;o>0&&n===window.klarna_OSMP.updaterId;)o-=1,await r(1e3),await s()}));e.observe(document.body,{childList:!0,subtree:!0})}static addCurrentTimeToRerenders(){const{rerenders:e}=window.klarna_OSMP;e.shift(),e.push(new Date)}static calculateMaxTimeBetweenRerenders(){var e,t;const{rerenders:n}=window.klarna_OSMP;return((null===(e=n[n.length-1])||void 0===e?void 0:e.getTime())||1/0)-((null===(t=n[0])||void 0===t?void 0:t.getTime())||-1/0)}updatePlacementsOnInputEvents(){document.querySelectorAll("select, input").forEach((e=>{e.removeEventListener("change",this.eventHandler,!0),e.addEventListener("change",this.eventHandler,!0)}))}async updatePlacements(){await r(20),window.klarna_OSMP.updaterId+=1;const e=window.klarna_OSMP.updaterId;i("Updater started with id",e);let t=await this.getCartTotal();const n=async e=>{await r(e);const n=await this.getCartTotal();return n!==t&&(this.updatePurchaseAmount(n),t=n,!0)};for(;;){let t=10,a=50;for(;t&&!(e{i("updating placement",e),e.setAttribute("data-purchase-amount",String(n))})),0!==this.conflictingAppIds.length&&this.listenForInputChange()}async getCartTotal(){const e=await fetch("/cart.json");if(!e.ok)throw new Error;const t=await e.json();return t.total_price?t.total_price:0}}const m={getCompetitorElement(e){return i("[getCompetitorElement]",e),"afterpay"===e?this.findAfterpayElement():null},findAfterpayElement(){var e;let t=null;if(window.afterpay_product_selector)return window.afterpay_product_selector;if(window.Afterpay&&window.Afterpay.supportedTheme&&window.Afterpay.supportedTheme.product){i("[findAfterpayElement] Found window.Afterpay.supportedTheme");const e=window.Afterpay.supportedTheme.product;t=e[Object.keys(e).reduce(((e,t)=>e&&e>t?e:t),"")].selector}else window.Afterpay&&void 0===window.Afterpay.supportedTheme&&window.Afterpay.commonElements.product&&window.Afterpay.commonElements.product.price_selector&&(i("[findAfterpayElement] Found window.Afterpay.commonElements"),t=null!==(e=window.Afterpay.commonElements.product.price_selector.find((e=>{try{if(document.querySelector(e))return e}catch(e){}return null})))&&void 0!==e?e:null);return i("[findAfterpayElement] got productElement",t),t}},h=[["/products/","product"],["/collections","collections"],["/pages/","static"],["/cart","cart"],["/checkouts","checkout"]],g={product:"product",home:"home",collection:"collections",page:"static"};class A extends p{static initObserver(e,t){return i("initObserver",{rootNode:e,element:t}),new a.MutationSummary({callback:e=>{if(void 0===e)return;const n=e[0];if(0===n.added.length)return;const a=n.added[0];a.classList.contains("afterpay-paragraph")&&(a.previousSibling&&a.previousSibling.innerHTML.includes("klarna")||(i("Detected competitor widget change in the DOM, inserting Ad position above it."),a.parentNode.insertBefore(t,a)))},rootNode:e,observeOwnChanges:!0,queries:[{all:!0}]})}constructor(){var e,t,n,a;super(window.klarna_OSMP.store,null!==(a=null===(n=null===(t=null===(e=null===window||void 0===window?void 0:window.ShopifyAnalytics)||void 0===e?void 0:e.meta)||void 0===t?void 0:t.product)||void 0===n?void 0:n.variants)&&void 0!==a?a:[]),this.placements=window.klarna_OSMP.placements,this.detectedAfterpayElement=null,this.usersCountry=null,window.klarna_OSMP=window.klarna_OSMP||{},window.KlarnaOnsiteService=window.KlarnaOnsiteService||[],window.Klarna=window.Klarna||{},this.currentPageType=A.getCurrentPage()}static getCurrentPage(){if(this.isHomePage())return"home";const e=this.determineCurrentPageBasedOnPath(),t=this.getCurrentPageFromShopifyAnalytics();return e||t}static isHomePage(){var e,t,n,a;const i=(null===(a=null!==(t=null===(e=null===Shopify||void 0===Shopify?void 0:Shopify.routes)||void 0===e?void 0:e.root)&&void 0!==t?t:null===(n=null===Shopify||void 0===Shopify?void 0:Shopify.routes)||void 0===n?void 0:n.root_url)||void 0===a?void 0:a.slice(0,-1))||"/";return window.location.pathname===i}static determineCurrentPageBasedOnPath(){for(const[e,t]of h)if(window.location.pathname.includes(e))return t;return""}static getCurrentPageFromShopifyAnalytics(){var e,t,n;const a=null===(n=null===(t=null===(e=null===window||void 0===window?void 0:window.ShopifyAnalytics)||void 0===e?void 0:e.meta)||void 0===t?void 0:t.page)||void 0===n?void 0:n.pageType;return g[a]||""}async init(){var e;if(i("init"),!this.placements||!this.store)return void i("Insufficient data. exiting...");const{Shopify:t}=window,n=null!==(e=t.currency&&t.currency.active)&&void 0!==e?e:t.Checkout.currency;void 0!==t&&(i(`Selected currency: ${n}`),i(`Shop currency: ${this.store.currency}`),this.store.currency&&this.store.currency!==n)?i(`Currency ${n} not supported. exiting...`):(await this.checkForCompetitorAds(),this.placements.some((e=>"geolocation"===e.locale_option))&&(this.usersCountry=await d.getUsersCountry(),i("Using geolocation, got users country:",this.usersCountry)),this.injectPlacements(),await super.init())}async checkForCompetitorAds(){this.placements.filter((e=>"below"===e.position)).length&&(await r(1e3),this.detectedAfterpayElement=m.getCompetitorElement("afterpay"),this.detectedAfterpayElement&&i("got detectedAfterpayElement",this.detectedAfterpayElement))}findCurrentPage(){let e=this.currentPageType;return"static"===e&&(e=window.location.pathname),i(`Page detected: ${e}`),e}injectPlacement(e,t,n){var a,r,o,s,c,l,d;let u=e.placement_page;if("static"===this.currentPageType&&(u=`${(null===(r=null===(a=window.Shopify)||void 0===a?void 0:a.routes)||void 0===r?void 0:r.root)||"/"}pages/${e.static_page}`),n===u){i("-----------------"),i(`Attempting to inject Ad position '${e.name?e.name:t}'.`,{install_method:e.install_method?e.install_method:"",competitor_placement:"above"!==e.position});try{const n=`margin: ${[e.padding_top,e.padding_right,e.padding_bottom,e.padding_left].map((e=>e?"1em":"0")).join(" ")}`;let a=null;"right"===e.justification?a="display: flex; justify-content: flex-end;":"center"===e.justification&&(a="display: flex; justify-content: center;");const r=document.createElement("div");r.setAttribute("style",n);let u=null;if("geolocation"===e.locale_option){if(e.countries&&!e.countries.find((e=>e===this.usersCountry))||"EUR"!==this.store.currency&&this.usersCountry!==e.country)return i(`Ad is not supported for this user's country: ${this.usersCountry}, countries for this placement: ${null!==(s=null===(o=e.countries)||void 0===o?void 0:o.join(", "))&&void 0!==s?s:e.country}`),!1;u=this.localeService.getMatchingLocale(this.usersCountry,e.honor_storefront_locale,e.countries)}else if("auto"===e.locale_option&&this.store.mid_locales){const t=null===Shopify||void 0===Shopify?void 0:Shopify.locale,{country:n,data_locale:a}=e,r=this.store.mid_locales[n];i("auto locale selection:",{locales:r,shopLocale:t,country:n,dataLocale:a,midLocales:this.store.mid_locales}),r&&(u=null!==(d=null!==(l=null!==(c=r.find((e=>e.startsWith(t))))&&void 0!==c?c:r.find((e=>a===e)))&&void 0!==l?l:r[0])&&void 0!==d?d:null)}const p=u||e.data_locale;i("Got matching locale:",u),i("Using locale:",p);const m=document.createElement("klarna-placement");"product"===this.currentPageType&&0===(this.getDataPurchaseAmount()||0)&&"dynamic"===e.type?(i("Using fallback placement",this.store.fallback_placement),m.setAttribute("data-key",this.store.fallback_placement)):m.setAttribute("data-key",e.data_key),m.setAttribute("data-purchase-amount",String(this.getDataPurchaseAmount()||0)),m.setAttribute("data-preloaded","true"),m.setAttribute("data-locale",p),"dark"===e.theme&&m.setAttribute("data-theme","dark"),r.appendChild(m);const h=document.querySelector(e.anchor_element);if("above"===e.position)i(`Ad position injected at element: ${e.anchor_element}`),h.parentNode.insertBefore(r,h);else if("below"===e.position){const t=h.nextSibling;null!==t?t.parentNode.insertBefore(r,t):h.parentNode.append(r),i(`Ad position injected at element (competitor): ${e.anchor_element}`);const n=this.detectedAfterpayElement===e.anchor_element;this.detectedAfterpayElement&&n&&(i("Observing for competitor widget changes."),A.initObserver(h.parentNode,r))}return this.watchForRemoval(m,t),a&&r.querySelector("klarna-placement")&&r.querySelector("klarna-placement").setAttribute("style",a),m}catch(t){i(`Failed to insert placement for placement id ${e.id}(${e.anchor_element})`,t)}}return!1}injectPlacements(){let e=0,t=0;const n=this.findCurrentPage();this.placements.forEach(((a,i)=>{this.injectPlacement(a,i,n)?e+=1:t+=1})),i(`Loaded: ${e}. Failed: ${t}`)}getDataPurchaseAmount(){var e,t,n,a,i,r;let o=null;const s=p.getVariantIdFromQueryString();return s&&(o=null===(e=this.productVariants)||void 0===e?void 0:e.find((e=>e.id===s))),o?o.price:null!==(r=null===(i=null===(a=null===(n=null===(t=null===window||void 0===window?void 0:window.ShopifyAnalytics)||void 0===t?void 0:t.meta)||void 0===n?void 0:n.product)||void 0===a?void 0:a.variants[0])||void 0===i?void 0:i.price)&&void 0!==r?r:0}getKlarnaPlacements(){return Array.from(document.getElementsByTagName("klarna-placement")).filter((e=>!e.id))}watchForRemoval(e,t){const n=new WeakSet;let a=e;do{n.add(a),a=a.parentElement}while(a);const r=new MutationObserver((a=>{a.forEach((a=>{a.removedNodes.forEach((a=>{n.has(a)&&!document.body.contains(e)&&(i("placement was removed, reinserting..."),r.disconnect(),this.reinsertPlacement(t))}))}))}));document.body.contains(e)?r.observe(document.body,{childList:!0,subtree:!0}):(i("Reinserting placement before observer attached"),this.reinsertPlacement(t))}reinsertPlacement(e){this.injectPlacement(this.placements[e],e,this.findCurrentPage())?(super.updatePurchaseAmount(),i("finished reinserting placement")):i("failed to reinsert placement")}}const y=new A},991:e=>{(()=>{"use strict";var t,n={};t=n,Object.defineProperty(t,"__esModule",{value:!0}),t.SHOPIFY_API_KEY=t.DEVELOPMENT_PATH_PREFIX=t.GEOSERVICE_URL=t.APP_URL=t.NODE_ENV=void 0,t.NODE_ENV="production",t.APP_URL="https://skosm.klarna.com",t.GEOSERVICE_URL=`${t.APP_URL}/geolocation/v1`,t.DEVELOPMENT_PATH_PREFIX="",t.SHOPIFY_API_KEY="4439684aa13a71f0befb66b3a308e7d4",e.exports=n})()}}]);