import{t as e,v as t,G as s,T as n,h as o}from"./2c1ab0fe.Dbn2KvkT.js";import{d as r,dl as d,E as i,a,dm as c,ag as u,aM as p,k as f,w as l,dn as m,dp as g}from"./4b4bc88f.z1yoAwwH.js";import{p as y,s as h,a as b,b as v}from"./f58f39d8.CX1OVCRt.js";import{s as A}from"./74835653.BLveyRHP.js";import{u as $}from"./a9fa9fda.CPgABguf.js";import{cP as w,h as I,eA as C,p as k,df as S}from"./164ad2e3.FTBuhkTQ.js";import{A as x}from"./60a453ce.B80X1bY8.js";function T(e){return new Promise((t,s)=>{I(e.approvalScopes,x.CustomerPersonalData)||s(new d(`Extension ${e.id} at target \`${e.extensionPoint.target}\` is missing required access to read customer personal data.`)),t()})}function q(e,t,s){switch(!0){case e instanceof d:j(e,t);break;case e instanceof i:if("persisted"===t.type)j(e,t);else{const{extensionPoint:{target:n}}=t;s(new i(`[${n}] ${e.message}`))}break;default:s(e)}}function j(e,t){const s=`[${t.extensionPoint.target}] ${e.name}: ${e.message}`;console.error(s)}function E(e,t){const s={...e};var n;return h(t)?"object"!=typeof(n=s.addressLineComponents)||null===n||Array.isArray(n)||(s.addressLineComponents=function(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>null!==e&&!("string"==typeof e&&""===e.trim())))}(s.addressLineComponents)):delete s.addressLineComponents,b(t)||delete s.addressCode,s}function P(e,t){return e&&y(t)?{acceptedAddressInputFields:e}:{}}function L(e){return e?.length?e.sort(z):[{offset:0,length:0}]}function z(e,t){return e.offset-t.offset}function M(e,t){if("object"!=typeof e)throw new i("formattedAddress must be an object: received type "+typeof e);const s=E(e,t),n=N(s);if(n.length)throw new i(n.join("; "));return s}function N(e){const t=[],{address1:s,address2:n,city:o,company:r,provinceCode:d,zip:i,countryCode:c,latitude:u,longitude:p,addressLineComponents:f,addressCode:l}=e;if(s&&!O(s)&&t.push(`address1 must be a non-empty string: received type ${typeof s} in formattedAddress`),n&&!O(n)&&t.push(`address2 must be a non-empty string: received type ${typeof n} in formattedAddress`),o&&!O(o)&&t.push(`city must be a non-empty string: received type ${typeof o} in formattedAddress`),r&&!O(r)&&t.push(`company must be a non-empty string: received type ${typeof r} in formattedAddress`),d&&!O(d)&&t.push(`provinceCode must be a non-empty string: received type ${typeof d} in formattedAddress`),i&&!O(i)&&t.push(`zip must be a non-empty string: received type ${typeof i} in formattedAddress`),c&&!a(c)&&t.push(`countryCode must be a valid alpha-2 country code: received "${c}" in formattedAddress`),u&&("number"!=typeof u?t.push(`latitude must be a number: received type ${typeof u} in formattedAddress`):(u<-90||u>90)&&t.push(`latitude must be between -90 and 90: received ${u} in formattedAddress`)),f)if("object"!=typeof f||Array.isArray(f))t.push(`addressLineComponents must be an object: received type ${typeof f} in formattedAddress`);else for(const[a,m]of Object.entries(f))void 0===m||O(m)||t.push(`${a} must be a non-empty string: received type ${typeof m} in addressLineComponents`);return l&&!O(l)&&t.push(`addressCode must be a non-empty string: received type ${typeof l} in formattedAddress`),p&&("number"!=typeof p?t.push(`longitude must be a number: received type ${typeof p} in formattedAddress`):(p<-180||p>180)&&t.push(`longitude must be between -180 and 180: received ${p} in formattedAddress`)),t}function O(e){return("string"==typeof e||e instanceof String)&&e.trim().length>0}function V({addressType:d,countryCode:a,field:y,initialAddressQuery:h="",provider:b="autocomplete-service",allowAllCountries:I}){const{i18n:{locale:x},observability:j,userEvents:z,shop:V,source:B,checkout:{address:D}}=r(),{id:F}=V,[X,G]=s(h),[Q,H]=s(X),[J,K]=s(!1),[R,W]=s([]),[Y,Z]=s([]),ee=n(!1),[te,se]=s(_(B.sourceId)),{geolocation:ne}=w(),{search:oe,fetchAddress:re}=$(),de=S(),{details:ie}=u(a),ae=p(),ce=null!==D.extendedAddressMode.get(a),ue=e(()=>v({country:ie,extendedAddressMode:D.extendedAddressMode}),[D.extendedAddressMode,ie]),pe="pickup"===d?"google":void 0,fe=k("purchase.address-autocomplete.suggest"),le=t(()=>fe.map(f),[fe]),me=function(s){const n=C(s),o=t(()=>s[0],[s]);return e((e,t,s)=>o?new Promise((r,d)=>{t.aborted&&d(new c(t.reason)),T(o).then(()=>n({signal:t,target:{...e,...P(s,o.apiVersion)}})).then(e=>e?.suggestions||[]).then(e=>function(e,t){const s=[];if(!Array.isArray(e))throw new i("An array of address suggestions must be defined");const n=e.slice(0,5);for(const[o,{id:r,label:d,matchedSubstrings:a,formattedAddress:c}]of n.entries()){if(O(d)||s.push(`label is required and must be a non-empty string: received ${typeof d} in suggestions[${o}]`),r&&!O(r)&&s.push(`id must be a non-empty string: received ${typeof r} in suggestions[${o}]`),a)if(Array.isArray(a))for(const[e,{offset:t,length:n}]of a.entries())"number"!=typeof t&&s.push(`offset must be a number: received type ${typeof t} in matchedSubstrings[${e}] for suggestions[${o}]`),"number"!=typeof n&&s.push(`length must be a number: received type ${typeof n} in matchedSubstrings[${e}] for suggestions[${o}]`);else s.push(`matchedSubstrings must be an array: received type ${typeof a} in suggestions[${o}]`);if(c)if("object"==typeof c){const e=N(E(c,t));for(const t of e)s.push(`${t} for suggestions[${o}]`)}else s.push(`formattedAddress must be an object: received type ${typeof c} in suggestions[${o}]`);if(s.length)throw new i(s.join("; "))}return n}(e,o.apiVersion)).then(e=>function(e,t){return e.map((e,s)=>{const{id:n,label:o,matchedSubstrings:r,formattedAddress:d}=e;return{internalId:`extension-suggestion-${s}`,matchedSubstrings:L(r),label:o,...n&&{id:n},...d&&{formattedAddress:E(d,t)}}})}(e,o.apiVersion)).then(e=>r(e)).catch(e=>{q(e,o,d),r([])}),t.addEventListener("abort",()=>{d(new c(t.reason))})}):Promise.resolve([]),[n,o])}(le),ge=t(()=>le.length>0,[le]),ye=k("purchase.address-autocomplete.format-suggestion"),he=t(()=>ye.map(f),[ye]),be=function(s){const n=C(s),o=t(()=>s[0],[s]),r=k("purchase.address-autocomplete.suggest"),d=t(()=>r.length>0,[r]);return e((e,t)=>o?new Promise((s,r)=>{(function(e){return new Promise((t,s)=>{e?t():s(new i("A purchase.address-autocomplete.suggest extension is required for a purchase.address-autocomplete.format-suggestion extension"))})})(d).then(()=>T(o)).then(()=>{const{internalId:s,...r}=e,d={target:{selectedSuggestion:r,...P(t,o.apiVersion)}};return n(d)}).then(e=>{s({formattedAddress:M(e?.formattedAddress||{},o.apiVersion)})}).catch(e=>{q(e,o,r),s({formattedAddress:{}})})}):Promise.resolve({formattedAddress:{}}),[n,o,d])}(he),ve=t(()=>he.length>0,[he]),Ae=e((e,t,s,n)=>{const o=ae.value.defaultAttributes?.uniqToken||"";z.monorailEvent({schemaId:"checkout_autocomplete_suggestion/5.1",payload:{shopId:parseInt(l(F),10),checkoutToken:B.checkoutSessionIdentifier||"",uniqueToken:o,provider:t[0]?.completionService??"",context:"shipping"===e?"Shipping address":"Billing address",territoryCode:a??ne.country.code,locale:x,query:s,sessionToken:te,requestProvider:n,requestLatitude:ne.coordinates?.latitude,requestLongitude:ne.coordinates?.longitude,addressIds:t.map(e=>e.addressId)}})},[a,ne.country.code,x,te,F,B.checkoutSessionIdentifier,ae.value.defaultAttributes?.uniqToken,z,ne.coordinates]),$e=t(()=>ge&&y&&U(d),[y,d,ge]),we=t(()=>$e||I||A(a||ne.country.code),[I,a,ne.country.code,$e]);o(()=>{const e=setTimeout(()=>{de&&H(X)},300);return()=>{clearTimeout(e)}},[de,X]),o(()=>{G(h)},[h]),o(()=>{we||W([])},[we]);const Ie=n(a);o(()=>{Ie.current!==a&&void 0!==Ie.current&&(W([]),Z([]),ee.current=!1),Ie.current=a},[a]);const Ce=function(t){const{observability:s}=r(),{geolocation:n}=w();return e(async(e,o,r)=>{const d=await t(e,o,r);return s.histogram({name:"prediction_duration",value:d.duration.end-d.duration.start,attributes:{buyerCountry:n.country.code}}),d.data},[t,s,n.country.code])}(oe);o(()=>{let e=!1;if(we&&J){const[t]=le;if(t&&y&&U(d)){const s=new AbortController;return async function({activeExtension:t,query:s,field:n,signal:o}){if(!s||"string"!=typeof s||s.length<=1)return Z([]),void W([]);try{const t=await me({value:s,field:function(e){switch(e){case"address1":case"streetName":return"address1";case"postalCode":return"zip";default:throw new m(`Unknown Address Autocomplete field: ${e}`)}}(n),selectedCountryCode:a},o,ue());de.current&&!e&&(Z(t),W(function(e){return e.map(({label:e,matchedSubstrings:t,internalId:s})=>({addressId:s,completionService:"AUTOCOMPLETE_EXTENSION",description:e,matchedSubstrings:t}))}(t)))}catch(r){if(r instanceof m&&j.error(r),"local"===t.type){if(!(r instanceof c))throw r;console.warn("AddressAutocompleteSignalAbortedError: ",r.message)}}}({activeExtension:t,query:Q,field:y,signal:s.signal}),()=>{e=!0,s.abort("The query was debounced")}}!async function(t){try{if(!t||"string"!=typeof t||t.length<=1)return void W([]);const s=await Ce(t,{locale:x,countryCode:a??ne.country.code,location:ne.coordinates,requestToken:te,shopId:l(F),sourceId:B.sourceId||"",checkoutSessionIdentifier:B.checkoutSessionIdentifier||""},pe);de.current&&!e&&(W(s),!ee.current&&U(d)&&(Ae(d,s,t,pe),ee.current=!0))}catch(s){console.warn(`Unable to fetch predictions: ${s}`),de.current&&!e&&W([])}}(Q)}return()=>{e=!0}},[a,Q,x,te,Ae]);const ke=e((e,t,s,n,o)=>{const r=ie?.zones.find(e=>e.code===t.zoneCode)?.name||void 0,d=ae.value.defaultAttributes?.uniqToken,i=s.findIndex(t=>t.addressId===e)+1;z.monorailEvent({schemaId:"checkout_autocomplete_selection/6.2",payload:{shopId:parseInt(l(F),10),checkoutToken:B.checkoutSessionIdentifier||"",uniqueToken:d,address1:t.address1,address2:t.address2,city:t.city,zone:r,latitude:t.coordinates?.latitude,longitude:t.coordinates?.longitude,zip:t.postalCode,territoryCode:a??ne.country.code,position:i,query:Q,context:"shipping"===n?"Shipping address":"Billing address",locale:x,sessionToken:o,requestLatitude:ne.coordinates?.latitude,requestLongitude:ne.coordinates?.longitude}})},[ie,ae.value.defaultAttributes?.uniqToken,F,B.checkoutSessionIdentifier,a,ne.country.code,ne.coordinates,Q,x,z]),Se=e(async(e,t,s,n)=>{try{let o,r;if("AUTOCOMPLETE_EXTENSION"===t)o=await async function(e){const t=function(e){const t=Y.find(t=>t.internalId===e);return t||j.error(new g("Could not find selected suggestion in extension suggestions.")),t}(e),s=ue();return function(e,t,s){const n=e?.addressLineComponents,o=e=>t?.includes(e)?n?.[e]:void 0;return{address1:e?.address1,address2:e?.address2,city:e?.city,company:e?.company,zoneCode:e?.provinceCode,postalCode:e?.zip,coordinates:e?.latitude&&e?.longitude?{latitude:e.latitude,longitude:e.longitude}:void 0,streetName:n?.streetName,streetNumber:n?.streetNumber,line2:n?.additionalInformation,..."dedicated"===s?{district:o("district")}:{neighborhood:o("district")},subdistrict:o("subdistrict")}}(t?.formattedAddress||await async function(e,t){if(ve&&e)return(await be(e,t)).formattedAddress;const s=new i("The address fields could not be auto-populated. Please provide a `formattedAddress` for the selected suggestion or implement the `purchase.address-autocomplete.format-suggestion` extension.");console.error(`${s.name}: ${s.message}`)}(t,s),s,D.extendedAddressMode.get(a))}(e);else{const n=te;o=await re(e,{locale:x,requestToken:te,completionService:t,shopId:l(F),sourceId:B.sourceId||"",checkoutSessionIdentifier:B.checkoutSessionIdentifier||"",extendedFields:!s&&ce}),r=n,de.current&&(se(_(B.sourceId)),U(d)&&ke(e,o,R,d,n))}de.current&&n(o,r)}catch(o){if(o instanceof i)throw o;console.warn(`Unable to select prediction: ${o}`)}},[x,te,F,B.sourceId,B.checkoutSessionIdentifier,re,de,d,ke,R,ve,Y,be,j,ce,ue,D.extendedAddressMode,a]),xe=e((e,t=!0)=>{G(e),K(t)},[]);return{value:X,debouncedValue:Q,setValue:xe,predictions:R,selectPrediction:Se,provider:b}}function _(e){return`${e}-${Date.now()}`}function U(e){return"billing"===e||"shipping"===e}export{V as u};