/**
 * @preserve
 * Licenses of bundled dependencies can be found in dependencies-licenses.txt
 */
/*! vehicle-context-automation 2.13.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,l,u,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"}(l||(l={})),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"}(u||(u={})),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),B=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")}},P=(e,{runMode:t,country:n,language:a,modelSeries:o,subBrands:r,engineConcept:i})=>{const c="AUTHOR"===t?l.Author:l.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]]:[]])}`},U=(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}},A=(e,...t)=>{const n=[u.Primary,u.Secondary,u.Shop,u.Configurator,u.Info,u.TestDrive,u.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=U(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=U(e[a],a);t[a.toLowerCase()]=n}}return t})(e);(await t()).setCta(n)},R={[s.Configurator]:[[p.VehicleId,"vehicleId"]],[s.OnlineShop]:[[p.ColorGroup,"emhcolor"]]},D=(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=R[t.type];if(!o)return;let r=t.baseUrl;for(const[e,t]of o)a[e]&&(r=I(r,t,a[e]));n[e]={...t,url:r}}),n},I=(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",M="abtest-new_cta_print",L="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)}})}),z=()=>new Promise(e=>{a().subscribe(n,e)}),j=e=>{let t;a().subscribe(n,n=>{const a=n.configurationId;a&&a!==t&&(t=a,e(n))})},H=()=>new URLSearchParams(window.location.search).get(M)===L,x=(e,t,n)=>{const a=M;o("ABTestingConnection",{tenant:n??T,componentName:e,callback:e=>{t(e[a]===L)}})},G=e(i),F=async()=>{x(i,async e=>{if(e){const{cta:e={},modelSeries:n}=await z(),a=e.test_drive?[s.Enquiry,s.TestDrive]:[s.Enquiry],o=A(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)}}})},Q=e=>{sessionStorage.setItem(c,String(e))},V="globalelem",Y=async(e,t)=>new Promise(n=>{o("PageConnection",{tenant:t??V,componentName:e,callback:e=>{n(e.environmentVariables)}})}),J=e("cta-automation-service"),K=async()=>{const e=await(async()=>{let e;try{return e=await fetch(await async function(){const{assetUri:e}=await Y("globalelem-phrase-translations"),{language:t,country:n}=await(async()=>new Promise(e=>{o("PageConnection",{tenant:V,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){J.error("Failed to fetch translations, trying to fetch default.",e)}try{return e=await fetch(await async function(){const{assetUri:e}=await Y("globalelem-phrase-translations");return`${e}/globalelem-phrase-translations/latest/translations/en-GB.all.json`}()),e?.json()}catch(e){J.error("Failed to fetch default translation.",e)}return null})();return e&&e.find(e=>"makeAnEnquiry"===e.id)?.translation||""};const W=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 K()}},X="generic-product-template",Z=e(i),ee="https://api.oneweb.mercedes-benz.com",te=async()=>{Q(!1);const{country:e,language:n,templateName:a}=await O(i),{modelSeries:o,subBrands:r,cta:l={},engineConcept:u}=await z();try{const{enquiry:i}=l;let d;if(a!==X)return void Z.log("Skipping CTA service initialization outside of product page.");if("true"===sessionStorage.getItem(c))return void Z.log("CTA service is already initialized");ne(!o,"No apiUri or modelSeries found, skipping CTA service initialization"),ne(!i,`No enquiry configuration loaded for ${o}`),Q(!0);const f=P(ee,{runMode:"PUBLISH",country:e,language:n,modelSeries:o,subBrands:r,engineConcept:u});d=await B(f),d?Z.log(`Data for ${o} has been loaded:`,d):Z.error(`No data loaded from deep link service for ${o}.`),d={...d,[s.Enquiry]:await W(i)},E(d);const p=H(),m=C(d,!0,l.scenario,p);Z.log(`Mapping buttons for the following scenario${p?" (A/B test mapping active)":""}:`,m);const g=A(d,...m);if(g){(await t()).setCta(g),Z.log(`Buttons for ${o} have been added to the store:`,g)}}catch(e){Z.error(e)}},ne=(e,t)=>{e&&Z.error(t)},ae=async(e,t=[],n,a,o,r="")=>{const{country:c,language:l,runMode:u}=await O(i),d=P(ee,{runMode:u,country:c,language:l,modelSeries:e,subBrands:t,engineConcept:r});let f,p;try{f=await B(d),f?Z.log(`Data for ${e} has been loaded:`,f):Z.error(`No data loaded from deep link service for ${e}.`)}catch(e){Z.error(e.message)}finally{f={...f},f[s.Enquiry]=await W(n);const t=H(),r=C(f,!1,a,t);Z.log("Mapping buttons for the following scenario:",r);const i=A(f,...r);i&&(p=D(i,o),Z.log(`Buttons for ${e} have been mapped:`,p))}return p},oe="price-automation-service",re=e(oe);var ie;!function(e){e.Price="PRICE"}(ie||(ie={}));const ce=(e,t)=>{const n=`${e.language}-${e.country}`,a=Number("min"===t?e.min:e.max);return r(a,n)},se=e(oe),le=async(e,t,n=[])=>{const{apiUri:a,country:o,language:r,templateName:i}=await O(oe);if(i===X)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{re.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 se.error(`No data loaded from VMDS service for ${e}.`);se.log(`Data for ${e} has been loaded:`,c);const s=((e,t,n)=>{const a=e.i18n,o=e.highlights[ie.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:ce(c,"min"),max:ce(c,"max"),pricePrefixLabel:a.PRICE};return i&&a[i]&&(s.priceFootnoteLabel=a[i]),s})(c,r,o);return se.log(`Formatted price for ${e} have been returned:`,s),s}catch(e){se.error(e.message)}else se.error("No apiUri or modelSeries found, skipping price service initialization.");else se.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 z(),o=await le(e,n,a);o?((await t()).setPrice(o),se.log(`Price data for ${e} have been added to the store:`,o)):se.error(`No price data for ${e} added to the store.`)})(),te().then(()=>{F(),(async()=>{j(async({configurationId:n})=>{const{cta:a}=await z();if(void 0!==n&&a){const o=D(a,n);(await t()).setCta(o),e(i).log(`Updated CTAs with configurationID: ${n} added`)}})})()}))};ue();export{s as CTATypes,d as CtaIcons,X as PRODUCT_PAGE_TEMPLATE,H as doesExistABTestUrlParam,O as getPageEnvironmentState,q as getPageEnvironmentVariables,z as getVehicleDataStoreState,ue as initVCAService,ae as loadCtaConfiguration,le as loadPriceData,x as subscribeToABTestingState,j as subscribeToVehicleDataByConfigurationId};
//# sourceMappingURL=index.mjs.map
