1if(!customElements.get("popup-lead-form")){class PopupLeadForm extends HTMLElement{static selectors=Object.freeze({form:".popup-lead-form__form",modeSwitch:"[data-lead-mode-switch]",offerStateDescription:"[data-offer-state-description]",offerStateHeading:"[data-popup-heading-state]",successMessage:"[data-success-message]",termsLabel:".popup-lead-form__terms-label",errorOutput:".popup-lead-form__output",submitButton:".popup-lead-form__button--submit"});static controls=Object.freeze({languageIso:"language_iso",languageRootUrl:"language_root_url",channel:"channel",phone:"phone",email:"email",terms:"agree-to-terms",trackingConsent:"agree-to-tracking"});static buttonVariants=Object.freeze({default:"default",success:"success",error:"error"});static modes=Object.freeze({emailWhatsapp:"email_whatsapp",emailOnly:"email_only"});static offerStates=Object.freeze({emailWhatsapp:"email_whatsapp",emailOnlyWithPhoneAvailable:"email_only_with_phone_available",emailOnlyWhenPhoneHidden:"email_only_when_phone_hidden"});static events=Object.freeze({leadSubmitSuccess:"lead-submit-success",leadSubmitError:"lead-submit-error"});static timeouts=Object.freeze({buttonMessageDuration:3e3,buttonMessageDurationExtended:5e3});static klaviyo=Object.freeze({companyId:"RH49u6",listId:"S7jh9K",revision:"2026-01-15",source:"Popup Form",signupSource:"popup",consentVersion:"popup-bottom-sheet-v1-2026-08-14"});static consentLog=Object.freeze({endpoint:"https://erebor.beglarianfabrics.com/webhook/bf/email-consent"});static errorTypes=Object.freeze({validation:"validation",network:"network",server:"server",client:"client"});#isInitialized=!1;#isSending=!1;#isCopyMode=!1;#buttonMessageTimeout=null;connectedCallback(){if(this.#isInitialized)return;this.popup=this.closest("subscription-popup");const form=this.querySelector(PopupLeadForm.selectors.form),submitButton=form?.querySelector(PopupLeadForm.selectors.submitButton);this.elements={form,languageIsoInput:form?.elements[PopupLeadForm.controls.languageIso],languageRootUrlInput:form?.elements[PopupLeadForm.controls.languageRootUrl],channelInput:form?.elements[PopupLeadForm.controls.channel],phoneInput:form?.elements[PopupLeadForm.controls.phone],emailInput:form?.elements[PopupLeadForm.controls.email],termsInput:form?.elements[PopupLeadForm.controls.terms],termsLabel:form?.querySelector(PopupLeadForm.selectors.termsLabel),trackingConsentInput:form?.elements[PopupLeadForm.controls.trackingConsent],submitButton,submitButtonText:submitButton?.querySelector(".btn__text")||submitButton?.firstElementChild||submitButton,output:form?.querySelector(PopupLeadForm.selectors.errorOutput),successMessageElement:this.querySelector(PopupLeadForm.selectors.successMessage),modeSwitchButtons:Array.from(this.querySelectorAll(PopupLeadForm.selectors.modeSwitch)),offerStateDescriptionElements:Array.from(this.querySelectorAll(PopupLeadForm.selectors.offerStateDescription)),offerStateHeadingElements:Array.from(this.popup?.querySelectorAll(PopupLeadForm.selectors.offerStateHeading)||[])},this.hidePhone=this.dataset.hidePhone==="true";const requiredElements=[this.elements.form,this.elements.languageIsoInput,this.elements.languageRootUrlInput,this.elements.channelInput,this.elements.emailInput,this.elements.termsInput,this.elements.termsLabel,this.elements.submitButton,this.elements.submitButtonText,this.elements.output];this.hidePhone||requiredElements.push(this.elements.phoneInput),requiredElements.every(element=>element!==null)&&(this.supportedPhoneCodes=(this.dataset.supportedPhoneCodes||"").split(",").map(code=>code.trim()).filter(Boolean),this.offerConfig={[PopupLeadForm.offerStates.emailWhatsapp]:{submitLabel:this.dataset.submitLabelDual||"",successMessage:this.dataset.successMessageDual||""},[PopupLeadForm.offerStates.emailOnlyWithPhoneAvailable]:{submitLabel:this.dataset.submitLabelEmailOnlyWithPhoneAvailable||"",successMessage:this.dataset.successMessageEmailOnlyWithPhoneAvailable||""},[PopupLeadForm.offerStates.emailOnlyWhenPhoneHidden]:{submitLabel:this.dataset.submitLabelEmailOnlyWhenPhoneHidden||"",successMessage:this.dataset.successMessageEmailOnlyWhenPhoneHidden||""}},this.messages={errorPhone:this.dataset.formErrorPhone,errorEmail:this.dataset.formErrorEmail,errorTerms:this.dataset.formErrorTerms,errorGeneric:this.dataset.formError,errorCountryNotSupported:this.dataset.countryNotSupported},this.initialMode=this.resolveMode(this.dataset.modeDefault||this.elements.channelInput.value),this.onModeSwitchClick=this.onModeSwitchClick.bind(this),this.onSubmit=this.onSubmit.bind(this),this.onPopupAfterShow=this.onPopupAfterShow.bind(this),this.onPopupToggle=this.onPopupToggle.bind(this),this.elements.form.addEventListener("click",this.onModeSwitchClick),this.elements.form.addEventListener("submit",this.onSubmit),this.popup&&(this.popup.addEventListener("drawer:handleAfterShow",this.onPopupAfterShow),this.popup.addEventListener("toggle",this.onPopupToggle)),this.setMode(this.initialMode,{resetCopyMode:!1}),this.#isInitialized=!0)}disconnectedCallback(){!this.#isInitialized||!this.elements?.form||(this.elements.form.removeEventListener("click",this.onModeSwitchClick),this.elements.form.removeEventListener("submit",this.onSubmit),this.popup&&(this.popup.removeEventListener("drawer:handleAfterShow",this.onPopupAfterShow),this.popup.removeEventListener("toggle",this.onPopupToggle)),this.resetButtons(),this.#isInitialized=!1)}onPopupAfterShow(){this.resetToInitialState()}
1onPopupToggle(){this.resetToInitialState()}resolveMode(mode){const normalized=String(mode||"").toLowerCase();return normalized==="whatsapp"?PopupLeadForm.modes.emailWhatsapp:normalized==="email"?PopupLeadForm.modes.emailOnly:normalized!==PopupLeadForm.modes.emailWhatsapp&&normalized!==PopupLeadForm.modes.emailOnly?this.hidePhone?PopupLeadForm.modes.emailOnly:PopupLeadForm.modes.emailWhatsapp:this.hidePhone&&normalized===PopupLeadForm.modes.emailWhatsapp?PopupLeadForm.modes.emailOnly:normalized}resolveOfferState(mode=this.currentMode){return mode===PopupLeadForm.modes.emailWhatsapp?PopupLeadForm.offerStates.emailWhatsapp:this.hidePhone?PopupLeadForm.offerStates.emailOnlyWhenPhoneHidden:PopupLeadForm.offerStates.emailOnlyWithPhoneAvailable}normalizeOfferState(value){const normalized=String(value||"").toLowerCase();return normalized===PopupLeadForm.offerStates.emailWhatsapp||normalized===PopupLeadForm.offerStates.emailOnlyWithPhoneAvailable||normalized===PopupLeadForm.offerStates.emailOnlyWhenPhoneHidden?normalized:normalized===PopupLeadForm.modes.emailWhatsapp||normalized==="whatsapp"?PopupLeadForm.offerStates.emailWhatsapp:normalized===PopupLeadForm.modes.emailOnly||normalized==="email"?this.hidePhone?PopupLeadForm.offerStates.emailOnlyWhenPhoneHidden:PopupLeadForm.offerStates.emailOnlyWithPhoneAvailable:this.resolveOfferState()}setMode(nextMode,{resetCopyMode=!0}={}){const previousMode=this.currentMode,mode=this.resolveMode(nextMode),isDualMode=mode===PopupLeadForm.modes.emailWhatsapp,offerState=this.resolveOfferState(mode);this.currentMode=mode,this.currentOfferState=offerState,this.elements.form.dataset.channel=mode,this.elements.form.dataset.leadState=offerState,this.elements.form.dataset.hidePhone=String(this.hidePhone),this.elements.channelInput.value=mode,this.elements.phoneInput&&(this.elements.phoneInput.disabled=this.hidePhone||!isDualMode,this.elements.phoneInput.required=!this.hidePhone&&isDualMode,this.elements.phoneInput.setCustomValidity("")),this.elements.emailInput.setCustomValidity(""),this.elements.termsInput.setCustomValidity(""),this.errorMessage="",this.updateOfferText(offerState),this.updateOfferDescriptions(offerState),this.updateOfferHeadings(offerState),this.updateModeSwitches(mode),previousMode===PopupLeadForm.modes.emailWhatsapp&&mode===PopupLeadForm.modes.emailOnly&&!this.isSending&&!this.isCopyMode&&(this.elements.phoneInput&&this.elements.phoneInput.setCustomValidity(""),this.errorMessage="",this.setButtonMessage(this.elements.submitButton.dataset.defaultText,PopupLeadForm.buttonVariants.default,0)),resetCopyMode&&(this.isCopyMode=!1)}updateOfferText(offerState){const config=this.offerConfig[offerState]||{},submitLabel=config.submitLabel||this.elements.submitButton.dataset.defaultText||"";this.elements.submitButton.dataset.defaultText=submitLabel,!this.isSending&&!this.isCopyMode&&(this.elements.submitButtonText.textContent=submitLabel),this.elements.successMessageElement&&(this.elements.successMessageElement.textContent=config.successMessage||"")}updateOfferDescriptions(offerState){this.elements.offerStateDescriptionElements.forEach(element=>{const elementOfferState=this.normalizeOfferState(element.dataset.offerStateDescription);element.hidden=elementOfferState!==offerState})}updateOfferHeadings(offerState){this.elements.offerStateHeadingElements.forEach(element=>{const shouldShow=this.normalizeOfferState(element.dataset.popupHeadingState)===offerState;element.hidden=!shouldShow,element.classList.toggle("hidden",!shouldShow)})}updateModeSwitches(mode){this.elements.modeSwitchButtons.forEach(button=>{if(this.hidePhone){button.hidden=!0;return}const visibleForMode=this.resolveMode(button.dataset.visibleWhen);button.hidden=visibleForMode!==mode})}onModeSwitchClick(event){const switchButton=event.target.closest(PopupLeadForm.selectors.modeSwitch);if(!switchButton||this.isSending)return;const modeTarget=this.resolveMode(switchButton.dataset.modeTarget);modeTarget!==this.currentMode&&this.setMode(modeTarget,{resetCopyMode:!0})}async onSubmit(event){if(event.preventDefault(),this.isSending)return;if(this.setButtonMessage(this.elements.submitButton.dataset.defaultText,PopupLeadForm.buttonVariants.default,0),!this.validate()){this.setButtonMessage("",PopupLeadForm.buttonVariants.error,PopupLeadForm.timeouts.buttonMessageDuration),this.emit
1(PopupLeadForm.events.leadSubmitError,{channel:this.currentOfferState,error_type:PopupLeadForm.errorTypes.validation});return}this.errorMessage="",this.isSending=!0;const mode=this.currentMode,offerState=this.currentOfferState||this.resolveOfferState(mode),normalizedPhone=this.elements.phoneInput?this.normalizePhone(this.elements.phoneInput.value):"",email=this.elements.emailInput.value.trim(),basePayload={language_iso:this.elements.languageIsoInput.value,language_root_url:this.elements.languageRootUrlInput.value,channel:offerState,phone:normalizedPhone,email,trackingConsent:this.elements.trackingConsentInput?.checked||!1};let submitError=null;try{mode===PopupLeadForm.modes.emailWhatsapp?await Promise.all([this.sendEmailToKlaviyo({...basePayload,phone:""}),this.sendWhatsappToWebhook({...basePayload,channel:"whatsapp"})]):await Promise.all([this.sendEmailToKlaviyo({...basePayload,phone:""}),this.sendConsentLog(basePayload)])}catch(err){submitError=err}if(submitError){let errorType=submitError?.errorType||PopupLeadForm.errorTypes.server;"cause"in submitError&&submitError?.cause?.errors?.[0]?.code==="invalid"?(errorType=PopupLeadForm.errorTypes.validation,this.errorMessage=this.messages.errorPhone,this.setButtonMessage("",PopupLeadForm.buttonVariants.error,PopupLeadForm.timeouts.buttonMessageDurationExtended)):errorType===PopupLeadForm.errorTypes.validation?(this.errorMessage=submitError.userMessage||submitError.message||this.messages.errorGeneric,this.setButtonMessage("",PopupLeadForm.buttonVariants.error,PopupLeadForm.timeouts.buttonMessageDurationExtended)):(this.errorMessage="",this.setButtonMessage(submitError.userMessage||this.messages.errorGeneric,PopupLeadForm.buttonVariants.error,PopupLeadForm.timeouts.buttonMessageDurationExtended));const emittedErrorType=mode===PopupLeadForm.modes.emailWhatsapp&&errorType===PopupLeadForm.errorTypes.network?PopupLeadForm.errorTypes.server:errorType;this.emit(PopupLeadForm.events.leadSubmitError,{channel:offerState,error_type:emittedErrorType}),this.isSending=!1;return}try{this.resetForm(),this.setMode(mode,{resetCopyMode:!1}),this.isCopyMode=!0,this.emit(PopupLeadForm.events.leadSubmitSuccess,{channel:offerState})}catch(uiErr){console.error("[popup-lead-form] success UI transition failed",{branch:"ui",error:uiErr?.message||String(uiErr)}),this.errorMessage="",this.setButtonMessage(this.elements.submitButton.dataset.defaultText,PopupLeadForm.buttonVariants.default,0),this.isSending=!1}}resetToInitialState(){this.resetForm(),this.setMode(this.initialMode,{resetCopyMode:!1}),this.isCopyMode=!1,this.setButtonMessage(this.elements.submitButton.dataset.defaultText,PopupLeadForm.buttonVariants.default,0)}resetButtons({resetSubmit=!0}={}){clearTimeout(this.#buttonMessageTimeout),resetSubmit&&this.setButtonMessage(this.elements.submitButton.dataset.defaultText,PopupLeadForm.buttonVariants.default,0)}isSupportedPhoneCountry(phone){return this.supportedPhoneCodes.length===0?!0:this.supportedPhoneCodes.some(code=>phone.startsWith(code))}set isSending(value){this.#isSending=!!value,this.elements.submitButton.classList.toggle("is-loading",this.#isSending),this.#isSending?this.elements.submitButton.setAttribute("aria-busy","true"):this.elements.submitButton.removeAttribute("aria-busy")}get isSending(){return this.#isSending}set isCopyMode(value){this.#isCopyMode=!!value,this.elements.form.dataset.copyMode=String(this.#isCopyMode),this.resetButtons({resetSubmit:!this.#isCopyMode})}get isCopyMode(){return this.#isCopyMode}set errorMessage(message){this.elements.output.hidden=message==="",setTimeout(()=>{this.elements.output.textContent=message},0)}get errorMessage(){return this.elements.output.textContent||""}setButtonMessage(message,variant=PopupLeadForm.buttonVariants.default,duration=PopupLeadForm.timeouts.buttonMessageDuration){clearTimeout(this.#buttonMessageTimeout),message&&(this.elements.submitButtonText.textContent=message),this.elements.submitButton.dataset.variant=variant,!(duration<=0)&&(this.#buttonMessageTimeout=setTimeout(()=>{message&&(this.elements.submitButtonText.textContent=this.elements.submitButton.dataset.defaultText),this.elements.submitButton.dataset.variant=PopupLeadForm.buttonVariants.default},duration))}
1clearFormValues(){this.elements.phoneInput&&(this.elements.phoneInput.value="",this.elements.phoneInput.setCustomValidity("")),this.elements.emailInput.value="",this.elements.termsInput.checked=!1,this.elements.emailInput.setCustomValidity(""),this.elements.termsInput.setCustomValidity("")}resetForm(){this.clearFormValues(),this.errorMessage="",this.isCopyMode=!1,this.isSending=!1}validate(){const isDualMode=this.currentMode===PopupLeadForm.modes.emailWhatsapp&&!!this.elements.phoneInput&&!this.elements.phoneInput.disabled;if(this.elements.phoneInput&&this.elements.phoneInput.setCustomValidity(""),this.elements.emailInput.setCustomValidity(""),this.elements.termsInput.setCustomValidity(""),isDualMode){const normalizedPhone=this.normalizePhone(this.elements.phoneInput.value),phoneValidation=globalThis.LeadFormPhoneValidation?.validateInternationalPhone(normalizedPhone);if(!(phoneValidation?!!phoneValidation.isValid:/^\+[1-9]\d{1,14}$/.test(normalizedPhone)))return this.errorMessage=this.messages.errorPhone,this.elements.phoneInput.setCustomValidity(this.messages.errorPhone),this.elements.phoneInput.focus(),!1;if(!this.isSupportedPhoneCountry(normalizedPhone)){const countryNotSupportedMessage=this.messages.errorCountryNotSupported||this.messages.errorPhone||this.messages.errorGeneric;return this.errorMessage=countryNotSupportedMessage,this.elements.phoneInput.setCustomValidity(countryNotSupportedMessage),this.elements.phoneInput.focus(),!1}}return this.elements.emailInput.checkValidity()?this.elements.termsInput.checkValidity()?(this.errorMessage="",!0):(this.errorMessage=this.messages.errorTerms,this.elements.termsInput.setCustomValidity(this.messages.errorTerms),this.elements.termsInput.focus(),!1):(this.errorMessage=this.messages.errorEmail,this.elements.emailInput.setCustomValidity(this.messages.errorEmail),this.elements.emailInput.focus(),!1)}normalizePhone(phone){return globalThis.LeadFormPhoneValidation?.normalizePhone?globalThis.LeadFormPhoneValidation.normalizePhone(phone):phone.trim().replace(/[^0-9+]/g,"")}async sendEmailToKlaviyo(payload){const headers={accept:"application/vnd.api+json","content-type":"application/vnd.api+json",revision:PopupLeadForm.klaviyo.revision};let body=null;try{body=JSON.stringify({data:{type:"subscription",attributes:{profile:{data:{type:"profile",attributes:{...payload.email?{email:payload.email}:{},...payload.phone?{phone_number:payload.phone}:{},subscriptions:{...payload.email?{email:{marketing:{consent:"SUBSCRIBED"}}}:{}},properties:{source:PopupLeadForm.klaviyo.source,signup_source:PopupLeadForm.klaviyo.signupSource,channel:payload.channel,language_iso:payload.language_iso,language_root_url:payload.language_root_url,email_tracking_consent:payload.trackingConsent||!1,consent_version:PopupLeadForm.klaviyo.consentVersion}}}},custom_source:PopupLeadForm.klaviyo.source},relationships:{list:{data:{type:"list",id:PopupLeadForm.klaviyo.listId}}}}})}catch(err){throw new Error(this.messages.errorGeneric,{cause:err})}const subscribeUrl=new URL("https://a.klaviyo.com/client/subscriptions/");subscribeUrl.searchParams.set("company_id",PopupLeadForm.klaviyo.companyId);let response=null;try{response=await fetch(subscribeUrl,{method:"POST",headers,body})}catch(err){throw console.error("[popup-lead-form] submit failed",{branch:"email",status:null,error:err?.message||String(err)}),err}if(response.status!==202&&!response.ok){const responsePreview=await response.clone().text().then(value=>value.trim().slice(0,200)).catch(()=>""),responseError=await response.json();throw console.error("[popup-lead-form] submit failed",{branch:"email",status:response.status,response:responsePreview||responseError?.title||""}),new Error(responseError.title,{cause:responseError})}}async sendWhatsappToWebhook(payload){const webhookUrlRaw=this.dataset.whatsappWebhook?.trim()||"";let webhookUrl=null;try{webhookUrl=new URL(webhookUrlRaw)}catch{throw console.error("[popup-lead-form] submit failed",{branch:"whatsapp",status:null,response:"Invalid webhook URL"}),this.createSubmitError(PopupLeadForm.errorTypes.server,this.messages.errorGeneric)}let response=null;const controller=new AbortController,timeoutId=setTimeout(()=>controller.abort(),8e3);try{response=await fetch(webhookUrl.toString(),{method:"POST",signal:controller.signal,headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({channel:payload.channel||"whatsapp",phone:payload.phone,email:payload.email||"",consent:!0,language_iso:payload.language_iso,language_root_url:payload.language_root_url,source:"shopify_popup"})})}catch(err){throw console.error("[popup-lead-form] submit failed",{branch:"whatsapp",status:null,error:err?.message||String(err)}),this.createSubmitError(PopupLeadForm.errorTypes.network,this.messages.errorGeneric,err,this.messages.errorGeneric)}finally{clearTimeout(timeoutId)}if(response.ok)return;let responseBody=null,rawResponse="";try{rawResponse=await response.text()}catch{rawResponse=""}if(rawResponse.trim()!=="")try{responseBody=JSON.parse(rawResponse)}catch{responseBody=null}const responseMessage=typeof responseBody?.message=="string"?responseBody.message.trim():"";throw response.status===422?(console.error("[popup-lead-form] submit failed",{branch:"whatsapp",status:response.status,response:responseMessage||rawResponse.trim().slice(0,200)}),this.createSubmitError(PopupLeadForm.errorTypes.validation,responseMessage||this.messages.errorPhone||this.messages.errorGeneric)):response.status===429?(console.error("[popup-lead-form] submit failed",{branch:"whatsapp",status:response.status,response:responseMessage||rawResponse.trim().slice(0,200)}),this.createSubmitError(PopupLeadForm.errorTypes.server,responseMessage||this.messages.errorGeneric)):(console.error("[popup-lead-form] submit failed",{branch:"whatsapp",status:response.status,response:responseMessage||rawResponse.trim().slice(0,200)}),this.createSubmitError(PopupLeadForm.errorTypes.server,responseMessage||this.messages.errorGeneric))}async sendConsentLog(payload){const controller=new AbortController,timeoutId=setTimeout(()=>controller.abort(),8e3);try{await fetch(PopupLeadForm.consentLog.endpoint,{method:"POST",signal:controller.signal,headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({email:payload.email,consent_version:PopupLeadForm.klaviyo.consentVersion,email_tracking_consent:payload.trackingConsent||!1,source:"shopify_popup",channel:payload.channel})})}catch(err){console.error("[popup-lead-form] consent log failed",{branch:"consent-log",error:err?.message||String(err)})}finally{clearTimeout(timeoutId)}}createSubmitError(errorType,message,cause=null,userMessage=null){const error=cause?new Error(message,{cause}):new Error(message);return error.errorType=errorType,error.userMessage=userMessage||message,error}emit(name,detail){window.dispatchEvent(new CustomEvent(name,{detail}))}}customElements.define("popup-lead-form",PopupLeadForm)} 2//# sourceMappingURL=/cdn/shop/t/99/assets/popup-lead-form.js.map?v=183905538877751110461787060537
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.