'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-ceff47a0.js');
const index_esm_min = require('./index.esm.min-2e158fd8.js');
const index_esm_min$1 = require('./index.esm.min-f57d151c.js');
const index_esm_min$2 = require('./index.esm.min-1101deb1.js');
const reduxStore_service = require('./redux-store.service-10b7725a.js');

const bpSdkAddressGroupCss = "";
const BpSdkAddressGroupStyle0 = bpSdkAddressGroupCss;

const BpSdkAddressGroup = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.saveAnswer = index.createEvent(this, "saveAnswer", 7);
        this.addressMissingComponents = index.createEvent(this, "addressMissingComponents", 7);
        this.stageAddressValidationAnswerForUpdate = index.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 (index_esm_min.$$(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 index.h("bp-sdk-external-address-group", { answers: this.answers, label: this.label, labelledBy: this.labelledBy });
    }
    renderInternal() {
        return (index.h("div", { class: "bp-sdk-address-group__container" }, index.h("div", { class: "bp-sdk-address-group__streets" }, index.h("div", { class: "bp-sdk-row" }, this.answerMap['street_1'] && (index.h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group-street-primary", labelledBy: this.labelledBy, shouldHideLabel: index_esm_min.y$(this.label, this.answerMap['street_1']), answer: this.answerMap['street_1'], disableAddressAutocomplete: this.disableAutoSave })), this.answerMap['street_2'] && (index.h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group-street-secondary", labelledBy: this.labelledBy, shouldHideLabel: index_esm_min.y$(this.label, this.answerMap['street_2']), answer: this.answerMap['street_2'] })))), (this.answerMap['city'] || this.answerMap['state'] || this.answerMap['zipcode']) && (index.h("div", { class: "bp-sdk-address-group__locality" }, index.h("div", { class: "bp-sdk-row" }, this.answerMap['city'] && (index.h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group__city", labelledBy: this.labelledBy, shouldHideLabel: index_esm_min.y$(this.label, this.answerMap['city']), answer: this.answerMap['city'] })), this.answerMap['state'] && (index.h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group__state", labelledBy: this.labelledBy, shouldHideLabel: index_esm_min.y$(this.label, this.answerMap['state']), answer: this.answerMap['state'], useSelectAlias: true })), this.answerMap['zipcode'] && (index.h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group__zipcode", labelledBy: this.labelledBy, shouldHideLabel: index_esm_min.y$(this.label, this.answerMap['zipcode']), answer: this.answerMap['zipcode'] }))))), this.answerMap['address_json'] && (index.h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group-address__json", labelledBy: this.labelledBy, shouldHideLabel: index_esm_min.y$(this.label, this.answerMap['address_json']), answer: this.answerMap['address_json'], hidden: true })), this.useAddressValidation && (index.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) {
        index.registerInstance(this, hostRef);
        this.bpAnalyticsTrack = index.createEvent(this, "bpAnalyticsTrack", 7);
        this.isContinueDisabled = true;
        this.isLatest = { verdict: false, validationAttempt: false };
        this.mapStateToProps = (state) => {
            return {
                address: index_esm_min$1.KR(state, this.addressValidationId),
                answersResourceState: index_esm_min$1.cR(state),
                config: index_esm_min$1.up(state),
                googleApiToken: state.config.googleApiToken,
                stagedAnswers: index_esm_min$1.JR(state, this.addressValidationId),
                triggerValidation: index_esm_min$1.zR(state, this.addressValidationId),
                hasValidationError: index_esm_min$1.UR(state, this.addressValidationId),
                verdict: index_esm_min$1.FR(state, this.addressValidationId),
                latestAddress: index_esm_min$1.bL(state, this.answerMap),
                validationAttempt: index_esm_min$1.YR(state, this.addressValidationId),
                isValidationTriggerOverridden: index_esm_min$1.eM(state),
                originalAddress: index_esm_min$1.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: index_esm_min$2.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 !== index_esm_min$2.d.Loading) {
            !this.hasValidationError &&
                this.setAddressValidationStatus({
                    validationStatus: this.isValidationTriggerOverridden ? index_esm_min$2.se.COMPLETED : index_esm_min$2.se.PROCEED_NEXT,
                    addressValidationId: this.addressValidationId,
                });
            this.resetAddressValidation(this.addressValidationId);
            this.shouldProceedNext = false;
        }
    }
    onValidationError() {
        if (this.hasValidationError) {
            this.bpAnalyticsTrack.emit({
                eventName: index_esm_min$2.he.AddressValidation_ValidationError,
            });
        }
    }
    onTriggerValidation() {
        var _a;
        if (this.triggerValidation) {
            if (this.validationAttempt < 2) {
                this.validateAddress(Object.assign({ googleApiKey: this.googleApiToken, addressValidationId: this.addressValidationId }, index_esm_min.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: index_esm_min$2.he.AddressValidation_ValidatedOnFirstAttempt,
                    eventPayload: { isValidated: this.verdict === index_esm_min$2.ne.ACCEPT },
                });
            }
            this.bpAnalyticsTrack.emit({
                eventName: index_esm_min$2.he.AddressValidation_Verdict,
                eventPayload: { verdict: this.verdict, attempt: this.validationAttempt },
            });
            this.resetIsLatest();
        }
    }
    onAddressValidation() {
        if (this.address) {
            this.validatedAddressView = {
                address: this.address,
                displayAddress: index_esm_min.dA(this.address.formattedAddress),
                answersWithMissingPieces: this.address.missingComponentTypes
                    ? this.address.missingComponentTypes
                        .filter((type) => type !== index_esm_min$2.y.ROUTE)
                        .map((type) => this.latestAddress
                        ? this.latestAddress[index_esm_min.pA(type)]
                        : this.answerMap[index_esm_min.pA(type)])
                    : null,
                unconfirmedAddressComponents: this.address.addressComponents.filter((component) => component.confirmationLevel !== index_esm_min$2.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();
        reduxStore_service.store.mapDispatchToProps(this, {
            setAddressValidationStatus: index_esm_min$1.Mh,
            resetAddressValidation: index_esm_min$1.Nh,
            resetAddressValidationAttempt: index_esm_min$1.n6,
            saveValidatedAddressAnswers: index_esm_min$1.HW,
            saveAddressValidationMissingAnswers: index_esm_min$1.ws,
            stageAddressValidationAnswer: index_esm_min$1.Rh,
            switchActiveQuestionSet: index_esm_min$1.m8,
            updateAnswer: index_esm_min$1.ee,
            validateAddress: index_esm_min$1.rn,
            removeActiveAnswerId: index_esm_min$1._8,
        });
        this.storeUnsubscribe = reduxStore_service.store.mapStateToProps(this, this.mapStateToProps);
    }
    onCTAClick(action) {
        this.bpAnalyticsTrack.emit({
            eventName: index_esm_min$2.he.AddressValidation_CTAClicked,
            eventPayload: { ctaType: action, verdict: this.verdict, attempt: this.validationAttempt },
        });
        switch (action) {
            case index_esm_min$2.de.EDIT:
                return this.editAddress();
            case index_esm_min$2.de.AS_ENTERED:
                return this.continueAsEntered();
            case index_esm_min$2.de.MISSING_FIX:
                return this.continueWithMissingInputFix();
            case index_esm_min$2.de.CONFIRM:
                return this.continueWithConfirm();
        }
    }
    render() {
        return [this.useExternal && this.renderExternal(), !this.useExternal && this.renderInternal()];
    }
    renderExternal() {
        return (index.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 (index.h("div", { class: "bp-sdk-google-address-validation__container" }, this.verdict == index_esm_min$2.ne.CONFIRM && this.renderConfirm(), this.verdict == index_esm_min$2.ne.TYPO && this.renderTypo(), this.verdict == index_esm_min$2.ne.FIX && this.renderFix()));
    }
    renderConfirm() {
        return (index.h("div", { class: "bp-sdk-google-address-validation__confirm" }, index.h("h2", null, "Address confirmation"), index.h("h3", null, "Suggested address:"), index.h("p", null, this.validatedAddressView.displayAddress), index.h("h3", null, "Original address:"), index.h("p", null, this.originalAddress), index.h("bp-sdk-button", { text: "Continue with suggested address", onClick: () => this.onCTAClick(index_esm_min$2.de.CONFIRM) }), index.h("bp-sdk-button", { text: "Use original address", onClick: () => this.onCTAClick(index_esm_min$2.de.AS_ENTERED) }), index.h("p", null, "Address confirmation helps ensure quoting accuracy.")));
    }
    renderTypo() {
        return (index.h("div", { class: "bp-sdk-google-address-validation__spelling-suggestion" }, index.h("h2", null, "Address confirmation"), index.h("h3", null, "Did you mean?"), index.h("p", null, this.validatedAddressView.displayAddress), index.h("h3", null, "Address entered:"), index.h("p", null, this.originalAddress), index.h("bp-sdk-button", { text: "Yes, continue with suggested address", onClick: () => this.onCTAClick(index_esm_min$2.de.CONFIRM) }), index.h("bp-sdk-button", { text: "No, continue with address entered", onClick: () => this.onCTAClick(index_esm_min$2.de.AS_ENTERED) }), index.h("p", null, "Address confirmation helps ensure quoting accuracy.")));
    }
    renderFix() {
        return (index.h("div", { class: "bp-sdk-google-address-validation__fix" }, index.h("h2", null, "Address not verified"), index.h("h3", null, "Original address:"), index.h("p", null, this.originalAddress), (this.validatedAddressView.answersWithMissingPieces && (index.h("div", null, index.h("h3", null, "Missing information"), index.h("bp-sdk-address-group", { answers: this.validatedAddressView.answersWithMissingPieces, useAddressValidation: false, disableAutoSave: true })))) ||
            this.validatedAddressView.unconfirmedAddressComponents.map((component) => (index.h("div", null, index.h("h3", null, index_esm_min.fA(component.componentType), " not confirmed:"), index.h("p", null, component.componentName.text)))), (this.validatedAddressView.answersWithMissingPieces && (index.h("bp-sdk-button", { text: "Continue", onClick: () => this.onCTAClick(index_esm_min$2.de.MISSING_FIX), buttonDisabled: index_esm_min.gA(this.stagedAnswers) }))) || index.h("bp-sdk-button", { text: "Edit address", onClick: () => this.onCTAClick(index_esm_min$2.de.EDIT) }), index.h("bp-sdk-button", { text: "Continue with original address", onClick: () => this.onCTAClick(index_esm_min$2.de.AS_ENTERED) }), index.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;

exports.bp_sdk_address_group = BpSdkAddressGroup;
exports.bp_sdk_google_address_validation = BpSdkGoogleAddressValidation;
