/**
 * @preserve
 * Licenses of bundled dependencies can be found in dependencies-licenses.txt
 */
/*! vehicle-context-automation 2.10.0 */
import{initializeLogger as e}from"@seamless/logger";import{getConnectionVehicleDataDispatchers as t,connectionName as n}from"@dh-io-globalelem/vehicle-data-store-connection";import{initializeStore as a}from"@seamless/store";import{subscribe as o}from"@seamless/one-context";import{formatToMarketSpecificCurrency as r}from"@workbench/core";const i="cta-automation-service",c="cta_service.is_initialized";var s,u,l,d,f,p,m;!function(e){e.Configurator="CONFIGURATOR",e.OnlineShop="ONLINE_SHOP",e.ProductPage="PRODUCT_PAGE",e.TestDrive="TEST_DRIVE",e.Enquiry="ENQUIRY"}(s||(s={})),function(e){e.Publish="PUBLISHER",e.Author="AUTHOR"}(u||(u={})),function(e){e.Primary="primary",e.Secondary="secondary",e.Shop="shop",e.Configurator="configurator",e.Info="info",e.CarDrive="cardrive",e.Enquiry="enquiry",e.TestDrive="testDrive"}(l||(l={})),function(e){e.Configurator="bds/car-config/24",e.OnlineShop="bds/shopping-cart/24",e.Enquiry="bds/pencil-document/24"}(d||(d={})),function(e){e.Default="default",e.Alternative="alternative"}(f||(f={})),function(e){e.VehicleId="vehicleId",e.ColorGroup="colorGroup"}(p||(p={})),function(e){e.Default="",e.AMG="MERCEDES_AMG",e.Maybach="MERCEDES_MAYBACH"}(m||(m={}));const g=e(i),h=[s.Configurator,s.OnlineShop],w=[s.Configurator],y=[s.OnlineShop,s.ProductPage],b=[s.ProductPage],v=[s.OnlineShop],$=[s.Enquiry,s.TestDrive],S=(e,t)=>t.every((t=>Object.keys(e).includes(t))),C=(e,t=!1,n=f.Default,a=!1)=>{switch(!0){case a:return S(e,$)?[s.TestDrive,s.Enquiry]:[s.Enquiry];case S(e,h):return t?k(n):[s.OnlineShop,s.ProductPage];case S(e,w):return t?[s.Configurator,s.Enquiry]:[s.Configurator,s.ProductPage];case S(e,y):return t?[s.OnlineShop]:[s.OnlineShop,s.ProductPage];case S(e,b):return t?[s.Enquiry]:[s.ProductPage];case S(e,v):return[s.OnlineShop,s.Enquiry];default:return g.error("No scenario detected for loaded data:",e),[s.Enquiry]}},k=e=>e===f.Default?[s.OnlineShop,s.Configurator]:[s.OnlineShop,s.Enquiry],N=e(i),A=async e=>{const t=(()=>{try{const e=localStorage.getItem("cta_service.deeplink_response_mock_data");if(e){const t=JSON.parse(e);return N.log("Skipping sending request to the deeplink service and using mock data from the local storage:",t),t}}catch(e){N.error("An error occurred during injecting deep link data from the local storage:",e.message)}})();if(t)return t;try{N.log(`Sending request to ${e}`);const t=await fetch(e),n=await t.json();if(t.ok)return n}catch(e){N.error("Error caused during processing request to deep link service")}},B=(e,{runMode:t,country:n,language:a,modelSeries:o,subBrands:r,engineConcept:i})=>{const c="AUTHOR"===t?u.Author:u.Publish;return`${e}/vehicle-deeplinks-api/v1/deeplinks/${"AQ"===n?"DE":n}/${a}/model-series/${o}?${new URLSearchParams([...(r||[]).map((e=>["subBrands",e])),["cmsInstance",c],..."PLUGIN_HYBRID"===i&&r.includes(m.AMG)?[["engineConcept",i]]:[]])}`},P=(e,t)=>{const n=(e=>{switch(e){case s.OnlineShop:return d.OnlineShop;case s.Configurator:return d.Configurator;case s.Enquiry:return d.Enquiry;default:return""}})(t);return{...e,type:t,baseUrl:e?.url,icon:n}},U=(e,...t)=>{const n=[l.Primary,l.Secondary,l.Shop,l.Configurator,l.Info,l.TestDrive,l.Enquiry];if(t.length)return t.reduce(((t,a,o)=>{const r=n[o],i=a.toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));const c=a.toLowerCase(),s=e[a]??e[i]??e[c];if(r&&s){const e=P(s,a);t[r]=e}return t}),{})},E=async e=>{const n=(e=>{const t={};for(const n in s){const a=s[n];if(e[a]){const n=P(e[a],a);t[a.toLowerCase()]=n}}return t})(e);(await t()).setCta(n)},R=(e,t)=>{const n={...e};if(!t||"object"==typeof t&&0===Object.keys(t).length)return n;const a="string"==typeof t?{[p.VehicleId]:t}:t;return Object.keys(n).forEach((e=>{const t=n[e];if(!t)return;const o={[p.VehicleId]:[s.Configurator],[p.ColorGroup]:[s.OnlineShop,s.Configurator]},r=Object.entries(a).filter((([e])=>(o[e]||[]).includes(t.type)));if(0===r.length)return;let i=t.baseUrl;for(const[e,t]of r)t&&(i=D(i,e,t));n[e]={...t,url:i}})),n},D=(e,t,n)=>{const a=new URL(e);return a.hash?_(a,t,n):a.searchParams.set(t,n),a.toString()},_=(e,t,n)=>{const a=e.hash.indexOf("?")>-1?e.hash.substring(e.hash.lastIndexOf("?")+1):"",o=new URLSearchParams(a);o.set(t,n),e.hash=`${e.hash.replace(`?${a}`,"")}?${o.toString()}`},T="globalelem",I="abtest-new_cta_print",M="target",O=async(e,t)=>new Promise((n=>{o("PageConnection",{tenant:t??T,componentName:e,callback:e=>{n(e.pageEnvironmentVariables)}})})),q=async(e,t)=>new Promise((n=>{o("PageConnection",{tenant:t??T,componentName:e,callback:e=>{n(e.environmentVariables)}})})),L=()=>new Promise((e=>{a().once(n,e)})),j=e=>{let t;a().subscribe(n,(n=>{const a=n.configurationId;a&&a!==t&&(t=a,e(n))}))},z=()=>new URLSearchParams(window.location.search).get(I)===M,x=(e,t,n)=>{const a=I;o("ABTestingConnection",{tenant:n??T,componentName:e,callback:e=>{t(e[a]===M)}})},G=e(i),H=async()=>{x(i,(async e=>{if(e){const{cta:e={},modelSeries:n}=await L(),a=e.test_drive?[s.Enquiry,s.TestDrive]:[s.Enquiry],o=U(e,...a);if("#"===e?.enquiry?.url)return void G.log(`Skipping A/B test because enquiry URL is not set for ${n}.`);if(o){(await t()).setCta(o),G.log(`A/B Testing buttons for ${n} have been added to the store:`,o)}}}))},F=e=>{sessionStorage.setItem(c,String(e))},Q="globalelem",V=async(e,t)=>new Promise((n=>{o("PageConnection",{tenant:t??Q,componentName:e,callback:e=>{n(e.environmentVariables)}})})),Y=e("cta-automation-service"),J=async()=>{const e=await(async()=>{let e;try{return e=await fetch(await async function(){const{assetUri:e}=await V("globalelem-phrase-translations"),{language:t,country:n}=await(async()=>new Promise((e=>{o("PageConnection",{tenant:Q,componentName:"globalelem-phrase-translations",callback:t=>{e(t.pageEnvironmentVariables)}})})))();return`${e}/globalelem-phrase-translations/latest/translations/${t}-${("AQ"===n?"DE":n).toUpperCase()}.all.json`}()),e.json()}catch(e){Y.error("Failed to fetch translations, trying to fetch default.",e)}try{return e=await fetch(await async function(){const{assetUri:e}=await V("globalelem-phrase-translations");return`${e}/globalelem-phrase-translations/latest/translations/en-GB.all.json`}()),e?.json()}catch(e){Y.error("Failed to fetch default translation.",e)}return null})();return e&&e.find((e=>"makeAnEnquiry"===e.id))?.translation||""};const K=async e=>{let t=e?.url;return t||(t=function(){if("undefined"==typeof window||"undefined"==typeof document)return"#";let e=document.querySelector("aemf-form-container");if(!e){e=document.querySelector('[data-component-name*="owpi-spa"]');const t=e?.getAttribute("component-id"),n=window.top?.aemNamespace?.componentData;if(t&&Boolean(n?.[t]?.payload.hideContactForm&&n?.[t]?.payload.formId))return"#contact"}if(e){let t=e.getAttribute("data-anchor-id");return t||(t=`form-anchor-${crypto.randomUUID?crypto.randomUUID():Date.now()}`,e.setAttribute("data-anchor-id",t)),`#${t}`}}()),{url:t,label:await J()}},W="generic-product-template",X=e(i),Z="https://api.oneweb.mercedes-benz.com",ee=async()=>{F(!1);const{runMode:e,country:n,language:a,templateName:o}=await O(i),{modelSeries:r,subBrands:u,cta:l={},engineConcept:d}=await L();try{const{enquiry:i}=l;let f;if(o!==W)return void X.log("Skipping CTA service initialization outside of product page.");if("true"===sessionStorage.getItem(c))return void X.log("CTA service is already initialized");te(!r,"No apiUri or modelSeries found, skipping CTA service initialization"),te(!i,`No enquiry configuration loaded for ${r}`),F(!0);const p=B(Z,{runMode:e,country:n,language:a,modelSeries:r,subBrands:u,engineConcept:d});f=await A(p),f?X.log(`Data for ${r} has been loaded:`,f):X.error(`No data loaded from deep link service for ${r}.`),f={...f,[s.Enquiry]:await K(i)},E(f);const m=z(),g=C(f,!0,l.scenario,m);X.log(`Mapping buttons for the following scenario${m?" (A/B test mapping active)":""}:`,g);const h=U(f,...g);if(h){(await t()).setCta(h),X.log(`Buttons for ${r} have been added to the store:`,h)}}catch(e){X.error(e)}},te=(e,t)=>{e&&X.error(t)},ne=async(e,t=[],n,a,o,r="")=>{const{country:c,language:u,runMode:l}=await O(i),d=B(Z,{runMode:l,country:c,language:u,modelSeries:e,subBrands:t,engineConcept:r});let f,p;try{f=await A(d),f?X.log(`Data for ${e} has been loaded:`,f):X.error(`No data loaded from deep link service for ${e}.`)}catch(e){X.error(e.message)}finally{f={...f},f[s.Enquiry]=await K(n);const t=z(),r=C(f,!1,a,t);X.log("Mapping buttons for the following scenario:",r);const i=U(f,...r);i&&(p=R(i,o),X.log(`Buttons for ${e} have been mapped:`,p))}return p},ae="price-automation-service",oe=e(ae);var re;!function(e){e.Price="PRICE"}(re||(re={}));const ie=(e,t)=>{const n=`${e.language}-${e.country}`,a=Number("min"===t?e.min:e.max);return r(a,n)},ce=e(ae),se=async(e,t,n=[])=>{const{apiUri:a,country:o,language:r,templateName:i}=await O(ae);if(i===W)if(a&&e)try{const i=((e,{country:t,language:n,modelSeries:a,engineConcept:o,subBrands:r})=>{const i=new URL(`${e}/vmds-highlights-api/v1/highlights/${t}/${n}/${a}`);for(const e of r)i.searchParams.append("subBrands",e);return o&&i.searchParams.append("engineConcept",o),i.toString()})(a,{country:o,language:r,modelSeries:e,engineConcept:t,subBrands:n}),c=await(async e=>{try{oe.log(`Sending request to ${e}`);const t=await fetch(e),n=await t.json();if(t.ok)return n}catch(e){throw Error("Error caused during processing request to VMDS service")}})(i);if(!c)return void ce.error(`No data loaded from VMDS service for ${e}.`);ce.log(`Data for ${e} has been loaded:`,c);const s=((e,t,n)=>{const a=e.i18n,o=e.highlights[re.Price],{unit:r,footnoteI18nKey:i}=o,c={min:String(o.min),max:String(o.max),unit:o.unit,language:t,country:n},s={unit:r,min:ie(c,"min"),max:ie(c,"max"),pricePrefixLabel:a.PRICE};return i&&a[i]&&(s.priceFootnoteLabel=a[i]),s})(c,r,o);return ce.log(`Formatted price for ${e} have been returned:`,s),s}catch(e){ce.error(e.message)}else ce.error("No apiUri or modelSeries found, skipping price service initialization.");else ce.log("Skipping price automation service initialization outside of product page.")},ue=()=>{"undefined"!=typeof window&&!1!==window.ctaAutomationAutoInit&&((async()=>{const{modelSeries:e,engineConcept:n,subBrands:a}=await L(),o=await se(e,n,a);o?((await t()).setPrice(o),ce.log(`Price data for ${e} have been added to the store:`,o)):ce.error(`No price data for ${e} added to the store.`)})(),ee().then((()=>{H(),(async()=>{j((async({configurationId:n})=>{const{cta:a}=await L();if(void 0!==n&&a){const o=R(a,n);(await t()).setCta(o),e(i).log(`Updated CTAs with configurationID: ${n} added`)}}))})()})))};ue();export{s as CTATypes,d as CtaIcons,W as PRODUCT_PAGE_TEMPLATE,z as doesExistABTestUrlParam,O as getPageEnvironmentState,q as getPageEnvironmentVariables,L as getVehicleDataStoreState,ue as initVCAService,ne as loadCtaConfiguration,se as loadPriceData,x as subscribeToABTestingState,j as subscribeToVehicleDataByConfigurationId};
//# sourceMappingURL=index.mjs.map
