(self.webpackChunkclient=self.webpackChunkclient||[]).push([[280],{280:(t,e,a)=>{"use strict";a.d(e,{default:()=>v});const r=(...t)=>{console.log("[klarna-osm]",...t)},n=t=>new Promise((e=>setTimeout(e,t))),o=()=>{if(!(document.currentScript instanceof HTMLScriptElement))return"unknown";const t=document.currentScript.src.split("/").at(-3);return`${"0.0.0"===t?"local:":""}${t}`||"unknown"},i=()=>Array.from(document.getElementsByTagName("klarna-placement"));var c=a(573);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"},l="klarnaosm_user_locale";class u{static getCountryFromTimeZone(){var t;const{timeZone:e}=Intl.DateTimeFormat().resolvedOptions(),a=null!==(t=s[e])&&void 0!==t?t:null;return a||r("[getCountryFromTimeZone] unsupported country or time zone",{timeZone:e}),a}static async fetchUserCountry(){let t=u.getCachedUsersCountry();if(t)return r("Found users country in cache"),t;try{const e=new AbortController;setTimeout((()=>e.abort()),1500);const a=window.location.hostname,r=Shopify.shop,n=a!==r?a:"",i=new URL(c.GEOSERVICE_URL);i.searchParams.set("defaultDomain",r),i.searchParams.set("customDomain",n);const s=await fetch(i,{signal:e.signal,headers:{"x-app-blocks-version":o()}});if(!s.ok)throw new Error(s.statusText);t=(await s.json()).country}catch(t){return r("[getUsersCountry] Failed",t),r("[getUsersCountry] trying to parse from time zone"),this.getCountryFromTimeZone()}return t&&u.setCachedUsersCountry(t),t}static getCachedUsersCountry(){return localStorage.getItem(l)||null}static setCachedUsersCountry(t){r("Setting users country to cache",t),localStorage.setItem(l,t)}constructor(t){this.midLocales=null!=t?t:{}}static findLocale(t,e,a){var n,o;if(t){r("[getMatchingLocale] Valid locales for users country",t);const i=null!==(n=t[0])&&void 0!==n?n:null;let c="";if(e&&"undefined"!=typeof Shopify?(c=Shopify.locale,r("[getMatchingLocale] Using Shopify.locale",c)):navigator.language&&(c=navigator.language.slice(0,2),r("[getMatchingLocale] Using browser language",c)),c){const e=t.find((t=>t.startsWith(c)));if(e)return e}return a&&null!==(o=t.find((t=>t.startsWith("en"))))&&void 0!==o?o:i}return null}getMatchingLocale(t,e,a){if(!t||!this.midLocales)return r("[getMatchingLocale] Invalid data",t,this.midLocales),null;r("[getMatchingLocale] Available countries for merchant",a);const n=this.getFilteredLocales(a);r("[getMatchingLocale] Valid locales for merchant",n);const o=null==n?void 0:n[t];return u.findLocale(o,e,!0)}getFilteredLocales(t){if(!t)return this.midLocales;const e=new Set(t);return Object.keys(this.midLocales).reduce(((t,a)=>{var r;return e.has(a)&&(t[a]=null!==(r=this.midLocales[a])&&void 0!==r?r:[]),t}),{})}getMatchingLocaleWithMidLocales(t,e){if(!t||!this.midLocales||0===Object.keys(this.midLocales).length)return r("[getMatchingLocale] Invalid data",t,this.midLocales),null;const a=this.midLocales[t];return u.findLocale(a,e,!1)}}const d=u;class m{constructor(t){this.store=t}inject(){if(!this.isOSMScriptAlreadyInjected())try{this.injectKlarnaOSMScriptTag(),r("Klarna OSM Script Tag has been added successfully")}catch(t){r("Could not add script element",t)}}isOSMScriptAlreadyInjected(){return null!==document.getElementById("klarna-osm-script-tag")}logIfEmptyClientId(){this.store.client_id||r("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 t=this.createKlarnaOSMScriptTag(),e=document.querySelector("body");e.insertBefore(t,e.children[0])}createKlarnaOSMScriptTag(){this.logIfEmptyClientId();const t=document.createElement("script"),e=this.store.playground_active?"playground":"production";return t.id="klarna-osm-script-tag",t.async=!0,t.setAttribute("data-environment",e),t.src="https://js.klarna.com/web-sdk/v1/klarna.js",t.setAttribute("data-client-id",this.store.client_id),t}}async function h(){var t;const e=await fetch("/cart.json");if(!e.ok)throw new Error;return null!==(t=(await e.json()).total_price)&&void 0!==t?t:0}class p{static getVariantIdFromQueryString(){const t=new URLSearchParams(window.location.search).get("variant");return t?Number.parseInt(t,10):null}constructor(t,e){this.store=t,this.productVariants=e,this.localeService=new d(t.mid_locales)}async init(){var t;window.klarna_OSMP=window.klarna_OSMP||{},window.klarna_OSMP.updaterId=null!==(t=window.klarna_OSMP.updaterId)&&void 0!==t?t:0,this.injectOnSiteScript(),await this.initPurchaseAmountIfCartOrProductPage(),this.listenForInputChange()}injectOnSiteScript(){new m(this.store).inject()}async initPurchaseAmountIfCartOrProductPage(){["cart","product"].includes(this.currentPageType)&&await this.updatePurchaseAmount()}listenForInputChange(){"cart"===this.currentPageType&&this.updatePlacementsOnDomMutations(),"product"===this.currentPageType&&new MutationObserver((t=>{i().forEach((t=>{const e=String(this.getDataPurchaseAmount()||0),a=t.getAttribute("data-purchase-amount");e!==t.getAttribute("data-purchase-amount")&&(r(`amount changed to ${e} from ${a}`),t.setAttribute("data-purchase-amount",e))}))})).observe(document.body,{childList:!0,subtree:!0})}updatePlacementsOnDomMutations(){new MutationObserver(function(t,e){let a=!1;return function(){a||(a=!0,t(),setTimeout((()=>{a=!1}),1e3))}}((async()=>{window.klarna_OSMP.updaterId+=1;const t=window.klarna_OSMP.updaterId,e=[void 0,void 0,await h()];let a=5;const r=async()=>{const t=await h();return!!e.some((e=>e!==t))&&(await this.updatePurchaseAmount(t),e.shift(),e.push(t),!0)};for(;a>0&&t===window.klarna_OSMP.updaterId;)a-=1,await n(1e3),await r()}))).observe(document.body,{childList:!0,subtree:!0})}async updatePurchaseAmount(t=""){const e=i();let a=t;a||("cart"===this.currentPageType?a=await h():"product"===this.currentPageType&&(a=this.getDataPurchaseAmount())),r("Updating placements with new amount",{placements:e,purchaseAmount:a}),e.forEach((t=>{t.setAttribute("data-purchase-amount",String(a))}))}}const g=[["/products/","product"],["/collections","collections"],["/pages/","static"],["/cart","cart"],["/checkouts","checkout"]],A={product:"product",home:"home",collection:"collections",page:"static"},y=[".product-form",".price",".product__title",".shopify-payment-button",".add-to-cart",".product-form__submit",".product-form__payment-container",".product__form",".product-price",".product__price",".product-add-to-cart",".product-single__add-to-cart",".btn--shopify-payment-btn",".product-action-flex","#product-add-to-cart",".shopify-product-form",".product-single__form",".current_price",".product-details__form",".product-detail","form.price","*:not(style,script)[data-shopify]",".product-single__description",".product-title",".product-description",".product-single__desc",".product-main__information",".product-variants",".main-price",'*:not(style,script)[data-action="add-to-cart"]',".ProductMeta__Description",".ProductMeta__TaxNotice",'*:not(style,script)[itemprop="offers"]'],f=[".cart__footer",".cart__blocks",".totals",".cart__checkout-button",".cart-totals",".cart__footer__text",".cart__submit-controls",".cart__subtotal-container",".cart__subtotal",".cart-bottom",".cart_bottom",".cart__buttons",".cart-meta",".cart-total-bottom",".subtotal_amount",".subtotal__container",".cart-price",".cart__checkout-wrapper",".cart__row",".cart-subtotal__price",".cart-recap__checkout",".hulkapps-cart-original-total",".cart-total-price",".checkout-buttons",".Cart__Total",".js-cart_subtotal",".secondary_button"],_=["h1","h2","h3","h4","h5",".h1",".h2",".h3",".h4",".h5","body"];class w extends p{constructor(){var t,e,a,n;super(window.klarna_OSMP.store,null!==(n=null===(a=null===(e=null===(t=window.ShopifyAnalytics)||void 0===t?void 0:t.meta)||void 0===e?void 0:e.product)||void 0===a?void 0:a.variants)&&void 0!==n?n:[]),this.usersCountry=null,this.placements=window.klarna_OSMP.placements,window.klarna_OSMP=window.klarna_OSMP||{},this.currentPageType=(()=>{if((()=>{var t,e,a;const r=null===(t=window.Shopify)||void 0===t?void 0:t.routes;let n=null!==(a=null!==(e=null==r?void 0:r.root)&&void 0!==e?e:null==r?void 0:r.root_url)&&void 0!==a?a:"";return n.length>1&&(null==n?void 0:n.endsWith("/"))&&(n=n.slice(0,-1)),window.location.pathname===n})())return"home";const t=(()=>{for(const[t,e]of g)if(window.location.pathname.includes(t))return e;return""})(),e=(()=>{var t,e,a;const r=null===(a=null===(e=null===(t=window.ShopifyAnalytics)||void 0===t?void 0:t.meta)||void 0===e?void 0:e.page)||void 0===a?void 0:a.pageType;return(r?A[r]:"")||""})();return t||e})(),r("Current page type:",this.currentPageType)}async init(){r("Initializing Klarna On-Site Messaging"),window.Shopify&&window.ShopifyAnalytics||r("Shopify objects are missing. It may cause unwanted behavior."),this.isValidDataAndCurrency()?(this.placements.some((t=>"geolocation"===t.locale_option))&&(this.usersCountry=await d.fetchUserCountry(),r("Using geolocation, got users country:",this.usersCountry)),this.injectPlacements(),await super.init()):r("Exiting due to invalid configuration.")}isValidDataAndCurrency(){return this.placements&&this.store?!!(t=>{var e,a,n,o;if(!window.Shopify)return!0;const i=null===(a=null===(e=window.Shopify)||void 0===e?void 0:e.currency)||void 0===a?void 0:a.active,c=null===(o=null===(n=window.Shopify)||void 0===n?void 0:n.Checkout)||void 0===o?void 0:o.currency,s=i||c;return r(`Selected currency: ${s}`),r(`Shop currency: ${t}`),t===s})(this.store.currency)||(r("Selected currency not supported"),!1):(r("Insufficient data to initialize placements"),!1)}findCurrentPage(){let t=this.currentPageType;return"static"===t&&(t=window.location.pathname),r(`Page detected: ${t}`),t}injectPlacement(t,e,a){var n,o,i,c,s,l,u,d,m;let h=t.placement_page;if("static"===this.currentPageType&&(h=`${(null===(o=null===(n=window.Shopify)||void 0===n?void 0:n.routes)||void 0===o?void 0:o.root)||"/"}pages/${t.static_page}`),a===h){r("-----------------"),r(`Attempting to install placement '${t.name}' using ${t.install_method}`);try{const a=`margin: ${[t.padding_top,t.padding_right,t.padding_bottom,t.padding_left].map((t=>t?"1em":"0")).join(" ")}`;let n=null;"right"===t.justification?n="display: flex; justify-content: flex-end;":"center"===t.justification&&(n="display: flex; justify-content: center;");let o=null;if("geolocation"===t.locale_option){if(t.countries&&!t.countries.find((t=>t===this.usersCountry))||"EUR"!==this.store.currency&&this.usersCountry!==t.country)return r(`Ad is not supported for this user's country: ${this.usersCountry}, countries for this placement: ${null!==(c=null===(i=t.countries)||void 0===i?void 0:i.join(", "))&&void 0!==c?c:t.country}`),!1;o=this.localeService.getMatchingLocale(this.usersCountry,t.honor_storefront_locale,t.countries)}else if("auto"===t.locale_option&&this.store.mid_locales){const e=null===(s=window.Shopify)||void 0===s?void 0:s.locale,{country:a,data_locale:n}=t,i=this.store.mid_locales[a];r("auto locale selection:",{locales:i,shopLocale:e,country:a,dataLocale:n,midLocales:this.store.mid_locales}),i&&(o=null!==(d=null!==(u=null!==(l=i.find((t=>t.startsWith(e))))&&void 0!==l?l:i.find((t=>n===t)))&&void 0!==u?u:i[0])&&void 0!==d?d:null)}const h=o||t.data_locale;r("Got matching locale:",o),r("Using locale:",h);const p=document.createElement("klarna-placement");"product"===this.currentPageType&&0===(this.getDataPurchaseAmount()||0)&&"dynamic"===t.type?(r("Using fallback placement",this.store.fallback_placement),p.setAttribute("data-key",this.store.fallback_placement)):p.setAttribute("data-key",t.data_key),p.setAttribute("data-purchase-amount",String(this.getDataPurchaseAmount()||0)),p.setAttribute("data-preloaded","true"),p.setAttribute("data-locale",h),p.setAttribute("data-integration-style","vintage"),"dark"!==t.theme&&"custom"!==t.theme||p.setAttribute("data-theme",t.theme);const g=document.createElement("div");g.setAttribute("style",a),g.appendChild(p);const A=function(t){const e=document.querySelector(t);if(!e)throw new Error(`Anchor not found for selector: ${t}`);return e}(function(t){return"autopicker"===t.install_method?function(t){const e=[..."cart"===t?f:y,..._].find((t=>document.querySelector(t)))||"h1";return r("Picked anchor:",e),e}(t.placement_page):t.anchor_element}(t));if(null===(m=A.parentNode)||void 0===m||m.insertBefore(g,A),r("Placement injected at element",A),this.watchForRemoval(p,e),n&&g.querySelector("klarna-placement")){const t=g.querySelector("klarna-placement");if(!t)return r("Failed to find klarna-placement element"),!1;t.setAttribute("style",n)}return p}catch(e){r(`Failed to insert placement for placement id ${t.id}(${t.anchor_element})`,e)}}return!1}injectPlacements(){let t=0,e=0;const a=this.findCurrentPage();this.placements.forEach(((r,n)=>{this.injectPlacement(r,n,a)?t+=1:e+=1})),r(`Loaded: ${t}. Failed: ${e}`)}getDataPurchaseAmount(){return this.getSelectedVariantPrice()||w.getFirstVariantPrice()}getSelectedVariantPrice(){var t;const e=p.getVariantIdFromQueryString();if(e){const a=null===(t=this.productVariants)||void 0===t?void 0:t.find((t=>t.id===e));return a?Number(a.price):0}return 0}static getFirstVariantPrice(){var t,e,a;const r=null===(a=null===(e=null===(t=window.ShopifyAnalytics)||void 0===t?void 0:t.meta)||void 0===e?void 0:e.product)||void 0===a?void 0:a.variants[0];return r?Number(r.price):0}watchForRemoval(t,e){const a=new WeakSet;let n=t;do{a.add(n),n=n.parentElement}while(n);const o=new MutationObserver((n=>{n.forEach((n=>{n.removedNodes.forEach((n=>{a.has(n)&&!document.body.contains(t)&&(r("placement was removed, reinserting..."),o.disconnect(),this.reinsertPlacement(e))}))}))}));document.body.contains(t)?o.observe(document.body,{childList:!0,subtree:!0}):(r("Reinserting placement before observer attached"),this.reinsertPlacement(e))}reinsertPlacement(t){const e=this.placements[t];if(!e)throw new Error("Index out of bounds for placements array");this.injectPlacement(e,t,this.findCurrentPage())?(super.updatePurchaseAmount(),r("finished reinserting placement")):r("failed to reinsert placement")}}const v=new w},573:t=>{(()=>{"use strict";var e,a={};e=a,Object.defineProperty(e,"__esModule",{value:!0}),e.SHOPIFY_API_KEY=e.DEVELOPMENT_PATH_PREFIX=e.GEOSERVICE_URL=e.APP_URL=e.NODE_ENV=void 0,e.NODE_ENV="production",e.APP_URL="https://skosm.klarna.com",e.GEOSERVICE_URL=`${e.APP_URL}/geolocation/v1`,e.DEVELOPMENT_PATH_PREFIX="",e.SHOPIFY_API_KEY="4439684aa13a71f0befb66b3a308e7d4",t.exports=a})()}}]);