import { r as registerInstance, c as createEvent, h } from './index-77a9c9e7.js';
import { c as $$, q as y$, r as cA, u as dA, x as pA, A as gA, B as fA } from './index.esm.min-cd800f97.js';
import { aE as KR, c as cR, u as up, aF as JR, aG as zR, aH as UR, aI as FR, aJ as bL, aK as YR, j as eM, aL as XR, M as Mh, ag as Nh, aM as n6, aN as HW, aO as ws, aP as Rh, m as m8, aQ as ee, aR as rn, _ as _8 } from './index.esm.min-db2d29e8.js';
import { s as se, d, h as he, n as ne, y, i as f, j as de } from './index.esm.min-9889e78b.js';
import { s as store } from './redux-store.service-dc54f48e.js';

const bpSdkAddressGroupCss = "";
const BpSdkAddressGroupStyle0 = bpSdkAddressGroupCss;

const BpSdkAddressGroup = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.saveAnswer = createEvent(this, "saveAnswer", 7);
        this.addressMissingComponents = createEvent(this, "addressMissingComponents", 7);
        this.stageAddressValidationAnswerForUpdate = createEvent(this, "stageAddressValidationAnswerForUpdate", 7);
        this.updateInputs = (address) => () => {
            this.updateStreet(address);
            this.updateCity(address);
            this.updateState(address);
            this.updateZip(address);
        };
        /**
         * Emits addressMissingComponents event if any required
         * address components are missing
         *
         * @param addressComponents The array of address components from Google
         */
        this.handleMissingAddressComponents = (addressComponents) => {
            const missingComponents = this.getMissingAddressComponents(addressComponents);
            if (missingComponents.length) {
                this.addressMissingComponents.emit({
                    missing_components: missingComponents,
                });
            }
        };
        /**
         * Finds the address components that are missing in the Google data
         *
         * @param addressComponents The array of address components from Google
         * @returns Returns an array of missing address component types
         */
        this.getMissingAddressComponents = (addressComponents) => {
            const requiredAddressComponentTypes = ['street_number', 'route', 'locality', 'administrative_area_level_1', 'postal_code'];
            return requiredAddressComponentTypes.filter((requiredAddressComponentType) => {
                return !addressComponents.some((addressComponent) => addressComponent.types[0] === requiredAddressComponentType);
            });
        };
        this.answers = [];
        this.label = undefined;
        this.labelledBy = undefined;
        this.disableAutoSave = false;
        this.useAddressValidation = false;
        this.addressValidationId = undefined;
        this.answerMap = {};
        this.useExternal = false;
    }
    onAnswersChange(newAnswers) {
        const map = {};
        newAnswers.forEach((answer) => {
            var _a;
            if ((_a = answer === null || answer === void 0 ? void 0 : answer.question) === null || _a === void 0 ? void 0 : _a.reference_type) {
                map[answer.question.reference_type] = answer;
            }
        });
        this.answerMap = map;
    }
    resetState() { }
    connectedCallback() {
        this.resetState();
    }
    componentWillLoad() {
        this.useExternal = !!customElements.get('bp-sdk-external-address-group');
        customElements.whenDefined('bp-sdk-external-address-group').then(() => {
            this.useExternal = true;
        });
        this.onAnswersChange(this.answers);
    }
    emitSaveAnswer(answer, newValue) {
        if ($$(answer, newValue)) {
            this.saveAnswer.emit({
                answer,
                new_value: newValue,
            });
        }
    }
    onSaveAnswer(event) {
        if (this.disableAutoSave) {
            this.stageAddressValidationAnswerForUpdate.emit(event.detail);
            event.preventDefault();
            event.stopImmediatePropagation();
        }
    }
    onPlacesUpdate({ detail }) {
        if (this.useExternal) {
            return;
        }
        const address = {};
        if (detail.address_components) {
            detail.address_components.forEach((addressComponent) => {
                address[addressComponent.types[0]] = {
                    short: addressComponent.short_name,
                    long: addressComponent.long_name,
                };
            });
            setTimeout(this.updateInputs(address), 0);
            this.handleMissingAddressComponents(detail.address_components);
        }
        this.updateJson(detail);
    }
    updateStreet(address) {
        if (address['street_number'] && address['route']) {
            const street_answer = this.answerMap['street_1'];
            if (street_answer) {
                this.emitSaveAnswer(Object.assign({}, street_answer), `${address['street_number'].long} ${address['route'].long}`);
            }
        }
    }
    updateCity(address) {
        if (address['locality']) {
            const city_answer = this.answerMap['city'];
            if (city_answer) {
                this.emitSaveAnswer(Object.assign({}, city_answer), address['locality'].long);
            }
        }
    }
    updateState(address) {
        if (address['administrative_area_level_1']) {
            const state_answer = this.answerMap['state'];
            if (state_answer) {
                const state = address['administrative_area_level_1'].short;
                const state_choice = state_answer.question.choices.find((choice) => choice.alias === state);
                if (state_choice) {
                    this.emitSaveAnswer(Object.assign({}, state_answer), [state_choice.id]);
                }
            }
        }
    }
    updateZip(address) {
        if (address['postal_code']) {
            const zip_answer = this.answerMap['zipcode'];
            if (zip_answer) {
                this.emitSaveAnswer(Object.assign({}, zip_answer), address['postal_code'].long);
            }
        }
    }
    updateJson(place) {
        const json_answer = this.answerMap['address_json'];
        if (json_answer) {
            this.emitSaveAnswer(Object.assign({}, json_answer), JSON.stringify(place));
        }
    }
    render() {
        return [this.useExternal && this.renderExternal(), !this.useExternal && this.renderInternal()];
    }
    renderExternal() {
        return h("bp-sdk-external-address-group", { answers: this.answers, label: this.label, labelledBy: this.labelledBy });
    }
    renderInternal() {
        return (h("div", { class: "bp-sdk-address-group__container" }, h("div", { class: "bp-sdk-address-group__streets" }, h("div", { class: "bp-sdk-row" }, this.answerMap['street_1'] && (h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group-street-primary", labelledBy: this.labelledBy, shouldHideLabel: y$(this.label, this.answerMap['street_1']), answer: this.answerMap['street_1'], disableAddressAutocomplete: this.disableAutoSave })), this.answerMap['street_2'] && (h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group-street-secondary", labelledBy: this.labelledBy, shouldHideLabel: y$(this.label, this.answerMap['street_2']), answer: this.answerMap['street_2'] })))), (this.answerMap['city'] || this.answerMap['state'] || this.answerMap['zipcode']) && (h("div", { class: "bp-sdk-address-group__locality" }, h("div", { class: "bp-sdk-row" }, this.answerMap['city'] && (h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group__city", labelledBy: this.labelledBy, shouldHideLabel: y$(this.label, this.answerMap['city']), answer: this.answerMap['city'] })), this.answerMap['state'] && (h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group__state", labelledBy: this.labelledBy, shouldHideLabel: y$(this.label, this.answerMap['state']), answer: this.answerMap['state'], useSelectAlias: true })), this.answerMap['zipcode'] && (h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group__zipcode", labelledBy: this.labelledBy, shouldHideLabel: y$(this.label, this.answerMap['zipcode']), answer: this.answerMap['zipcode'] }))))), this.answerMap['address_json'] && (h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group-address__json", labelledBy: this.labelledBy, shouldHideLabel: y$(this.label, this.answerMap['address_json']), answer: this.answerMap['address_json'], hidden: true })), this.useAddressValidation && (h("bp-sdk-google-address-validation", { answerMap: this.answerMap, addressValidationId: this.addressValidationId }))));
    }
    static get watchers() { return {
        "answers": ["onAnswersChange"]
    }; }
};
BpSdkAddressGroup.style = BpSdkAddressGroupStyle0;

const bpSdkGoogleAddressValidationCss = "";
const BpSdkGoogleAddressValidationStyle0 = bpSdkGoogleAddressValidationCss;

const BpSdkGoogleAddressValidation = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.bpAnalyticsTrack = createEvent(this, "bpAnalyticsTrack", 7);
        this.isContinueDisabled = true;
        this.isLatest = { verdict: false, validationAttempt: false };
        this.mapStateToProps = (state) => {
            return {
                address: KR(state, this.addressValidationId),
                answersResourceState: cR(state),
                config: up(state),
                googleApiToken: state.config.googleApiToken,
                stagedAnswers: JR(state, this.addressValidationId),
                triggerValidation: zR(state, this.addressValidationId),
                hasValidationError: UR(state, this.addressValidationId),
                verdict: FR(state, this.addressValidationId),
                latestAddress: bL(state, this.answerMap),
                validationAttempt: YR(state, this.addressValidationId),
                isValidationTriggerOverridden: eM(state),
                originalAddress: XR(state, this.addressValidationId),
            };
        };
        this.continueWithConfirm = () => {
            this.removeActiveAnswerId();
            this.saveValidatedAddressAnswers({
                addressComponents: this.address.addressComponents,
                answerMap: this.answerMap,
                config: this.config,
            });
            this.resetAddressValidation(this.addressValidationId);
            this.shouldProceedNext = true;
        };
        this.continueWithMissingInputFix = () => {
            const answersToSave = this.stagedAnswers.map((answerDetails) => (Object.assign(Object.assign({}, answerDetails.answer), { value: answerDetails.new_value })));
            this.removeActiveAnswerId();
            this.saveAddressValidationMissingAnswers({
                answersToSave,
                addressValidationId: this.addressValidationId,
                config: this.config,
            });
        };
        this.editAddress = () => {
            this.resetAddressValidation(this.addressValidationId);
            this.resetAddressValidationAttempt(this.addressValidationId);
            this.setAddressValidationStatus({
                validationStatus: se.REQUIRED,
                addressValidationId: this.addressValidationId,
            });
        };
        this.continueAsEntered = () => {
            this.resetAddressValidation(this.addressValidationId);
            this.shouldProceedNext = true;
        };
        this.resetIsLatest = () => {
            this.isLatest.validationAttempt = false;
            this.isLatest.verdict = false;
        };
        this.address = undefined;
        this.addressValidationId = undefined;
        this.answerMap = undefined;
        this.answersResourceState = undefined;
        this.config = undefined;
        this.googleApiToken = undefined;
        this.stagedAnswers = [];
        this.triggerValidation = undefined;
        this.hasValidationError = undefined;
        this.verdict = undefined;
        this.latestAddress = undefined;
        this.validationAttempt = undefined;
        this.isValidationTriggerOverridden = undefined;
        this.originalAddress = undefined;
        this.useExternal = false;
        this.shouldProceedNext = false;
    }
    onStageAddressValidationAnswerForUpdate(event) {
        this.stageAddressValidationAnswer({ answerToStage: event.detail, addressValidationId: this.addressValidationId });
    }
    onIsReadyToProceedNext() {
        if (this.shouldProceedNext && this.answersResourceState !== d.Loading) {
            !this.hasValidationError &&
                this.setAddressValidationStatus({
                    validationStatus: this.isValidationTriggerOverridden ? se.COMPLETED : se.PROCEED_NEXT,
                    addressValidationId: this.addressValidationId,
                });
            this.resetAddressValidation(this.addressValidationId);
            this.shouldProceedNext = false;
        }
    }
    onValidationError() {
        if (this.hasValidationError) {
            this.bpAnalyticsTrack.emit({
                eventName: he.AddressValidation_ValidationError,
            });
        }
    }
    onTriggerValidation() {
        var _a;
        if (this.triggerValidation) {
            if (this.validationAttempt < 2) {
                this.validateAddress(Object.assign({ googleApiKey: this.googleApiToken, addressValidationId: this.addressValidationId }, cA((_a = this.latestAddress) !== null && _a !== void 0 ? _a : this.answerMap)));
            }
            else {
                this.shouldProceedNext = true;
            }
        }
    }
    onValidationAttempt() {
        if (this.validationAttempt) {
            this.isLatest.validationAttempt = true;
        }
    }
    onVerdict() {
        if (this.verdict) {
            this.isLatest.verdict = true;
        }
    }
    onValidation() {
        if (this.isLatest.verdict && this.isLatest.validationAttempt) {
            if (this.validationAttempt === 1) {
                this.bpAnalyticsTrack.emit({
                    eventName: he.AddressValidation_ValidatedOnFirstAttempt,
                    eventPayload: { isValidated: this.verdict === ne.ACCEPT },
                });
            }
            this.bpAnalyticsTrack.emit({
                eventName: he.AddressValidation_Verdict,
                eventPayload: { verdict: this.verdict, attempt: this.validationAttempt },
            });
            this.resetIsLatest();
        }
    }
    onAddressValidation() {
        if (this.address) {
            this.validatedAddressView = {
                address: this.address,
                displayAddress: dA(this.address.formattedAddress),
                answersWithMissingPieces: this.address.missingComponentTypes
                    ? this.address.missingComponentTypes
                        .filter((type) => type !== y.ROUTE)
                        .map((type) => this.latestAddress
                        ? this.latestAddress[pA(type)]
                        : this.answerMap[pA(type)])
                    : null,
                unconfirmedAddressComponents: this.address.addressComponents.filter((component) => component.confirmationLevel !== f.CONFIRMED),
            };
        }
    }
    onValidationCallToAction(event) {
        this.onCTAClick(event.detail);
    }
    resetState() {
        this.shouldProceedNext = false;
    }
    connectedCallback() {
        this.resetState();
        this.handleSubscriptions();
    }
    componentWillLoad() {
        this.useExternal = !!customElements.get('bp-sdk-external-google-address-validation');
        customElements.whenDefined('bp-sdk-external-google-address-validation').then(() => {
            this.useExternal = true;
        });
        this.onIsReadyToProceedNext();
    }
    disconnectedCallback() {
        this.storeUnsubscribe && this.storeUnsubscribe();
    }
    handleSubscriptions() {
        this.storeUnsubscribe && this.storeUnsubscribe();
        store.mapDispatchToProps(this, {
            setAddressValidationStatus: Mh,
            resetAddressValidation: Nh,
            resetAddressValidationAttempt: n6,
            saveValidatedAddressAnswers: HW,
            saveAddressValidationMissingAnswers: ws,
            stageAddressValidationAnswer: Rh,
            switchActiveQuestionSet: m8,
            updateAnswer: ee,
            validateAddress: rn,
            removeActiveAnswerId: _8,
        });
        this.storeUnsubscribe = store.mapStateToProps(this, this.mapStateToProps);
    }
    onCTAClick(action) {
        this.bpAnalyticsTrack.emit({
            eventName: he.AddressValidation_CTAClicked,
            eventPayload: { ctaType: action, verdict: this.verdict, attempt: this.validationAttempt },
        });
        switch (action) {
            case de.EDIT:
                return this.editAddress();
            case de.AS_ENTERED:
                return this.continueAsEntered();
            case de.MISSING_FIX:
                return this.continueWithMissingInputFix();
            case de.CONFIRM:
                return this.continueWithConfirm();
        }
    }
    render() {
        return [this.useExternal && this.renderExternal(), !this.useExternal && this.renderInternal()];
    }
    renderExternal() {
        return (h("bp-sdk-external-google-address-validation", { answerMap: this.answerMap, addressValidationId: this.addressValidationId, config: this.config, googleApiToken: this.googleApiToken, originalAddress: this.originalAddress, stagedAnswers: this.stagedAnswers, validatedAddressView: this.validatedAddressView, verdict: this.verdict }));
    }
    renderInternal() {
        return (h("div", { class: "bp-sdk-google-address-validation__container" }, this.verdict == ne.CONFIRM && this.renderConfirm(), this.verdict == ne.TYPO && this.renderTypo(), this.verdict == ne.FIX && this.renderFix()));
    }
    renderConfirm() {
        return (h("div", { class: "bp-sdk-google-address-validation__confirm" }, h("h2", null, "Address confirmation"), h("h3", null, "Suggested address:"), h("p", null, this.validatedAddressView.displayAddress), h("h3", null, "Original address:"), h("p", null, this.originalAddress), h("bp-sdk-button", { text: "Continue with suggested address", onClick: () => this.onCTAClick(de.CONFIRM) }), h("bp-sdk-button", { text: "Use original address", onClick: () => this.onCTAClick(de.AS_ENTERED) }), h("p", null, "Address confirmation helps ensure quoting accuracy.")));
    }
    renderTypo() {
        return (h("div", { class: "bp-sdk-google-address-validation__spelling-suggestion" }, h("h2", null, "Address confirmation"), h("h3", null, "Did you mean?"), h("p", null, this.validatedAddressView.displayAddress), h("h3", null, "Address entered:"), h("p", null, this.originalAddress), h("bp-sdk-button", { text: "Yes, continue with suggested address", onClick: () => this.onCTAClick(de.CONFIRM) }), h("bp-sdk-button", { text: "No, continue with address entered", onClick: () => this.onCTAClick(de.AS_ENTERED) }), h("p", null, "Address confirmation helps ensure quoting accuracy.")));
    }
    renderFix() {
        return (h("div", { class: "bp-sdk-google-address-validation__fix" }, h("h2", null, "Address not verified"), h("h3", null, "Original address:"), h("p", null, this.originalAddress), (this.validatedAddressView.answersWithMissingPieces && (h("div", null, h("h3", null, "Missing information"), h("bp-sdk-address-group", { answers: this.validatedAddressView.answersWithMissingPieces, useAddressValidation: false, disableAutoSave: true })))) ||
            this.validatedAddressView.unconfirmedAddressComponents.map((component) => (h("div", null, h("h3", null, fA(component.componentType), " not confirmed:"), h("p", null, component.componentName.text)))), (this.validatedAddressView.answersWithMissingPieces && (h("bp-sdk-button", { text: "Continue", onClick: () => this.onCTAClick(de.MISSING_FIX), buttonDisabled: gA(this.stagedAnswers) }))) || h("bp-sdk-button", { text: "Edit address", onClick: () => this.onCTAClick(de.EDIT) }), h("bp-sdk-button", { text: "Continue with original address", onClick: () => this.onCTAClick(de.AS_ENTERED) }), h("p", null, "Note: By using a non-verified address, you may not receive an accurate quote.")));
    }
    static get watchers() { return {
        "answersResourceState": ["onIsReadyToProceedNext"],
        "shouldProceedNext": ["onIsReadyToProceedNext"],
        "hasValidationError": ["onValidationError"],
        "triggerValidation": ["onTriggerValidation"],
        "validationAttempt": ["onValidationAttempt", "onValidation"],
        "verdict": ["onVerdict", "onValidation"],
        "address": ["onAddressValidation"]
    }; }
};
BpSdkGoogleAddressValidation.style = BpSdkGoogleAddressValidationStyle0;

export { BpSdkAddressGroup as bp_sdk_address_group, BpSdkGoogleAddressValidation as bp_sdk_google_address_validation };
