import { r as registerInstance, c as createEvent, h } from './index-77a9c9e7.js';
import { a as an, S as S5, _ as _8, m as m8, w as wa, t as tf, M as Mh, o as o6, O as Oe, h as SL, u as up, c as cR, l as lR, d as dR, f as fR, W as We, x as xN, i as MN, V as VN, Z as ZR, G as GR, j as eM, H as HR } from './index.esm.min-db2d29e8.js';
import { T, O, d, s as se, h as he } from './index.esm.min-9889e78b.js';
import { $ as $i, a as et, h as hi, J as Jr, s as s$, w as ww, S as Sw, b as Sa } from './index.esm.min-cd800f97.js';
import { s as store } from './redux-store.service-dc54f48e.js';

const bpSdkNextButtonContainerCss = "";
const BpSdkNextButtonContainerStyle0 = bpSdkNextButtonContainerCss;

const BpSdkNextButtonContainer = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.bpAnalyticsTrack = createEvent(this, "bpAnalyticsTrack", 7);
        this.handleSubscriptions = () => {
            if (this.storeUnsubscribe) {
                this.storeUnsubscribe();
            }
            store.mapDispatchToProps(this, {
                saveQuestionSet: an,
                updateErrors: S5,
                removeActiveAnswerId: _8,
                switchActiveQuestionSet: m8,
                pushAnswer: wa,
                getEligibilityResults: tf,
                setAddressValidationStatus: Mh,
                setAddressValidationTriggerOverridden: o6,
            });
            this.storeUnsubscribe = store.mapStateToProps(this, this.mapStateToProps);
        };
        this.mapStateToProps = (state) => ({
            activeQuestionSet: Oe(state),
            applicationId: SL(state),
            config: up(state),
            answersResourceState: cR(state),
            applicationFormResourceState: lR(state),
            pendingProcesses: state.application.pendingProcesses,
            questionPoolResourceState: dR(state),
            questionSetResourceState: fR(state),
            questionSetState: We(state),
            queue: state.queues.answers.queue,
            enableUserApplicationGuard: !!state.config.options.enableUserApplicationGuard,
            locked: state.application.form.locked,
            isActiveQuestionSetPendingProcess: xN(state),
            isOwner: MN(state),
            hasPermissionToEdit: VN(state, {
                permission: T.ApplicationForms,
                action: O.Update,
            }),
            addressValidationStatuses: ZR(state),
            addressIdsToBeValidated: GR(state),
            isValidationTriggerOverridden: eM(state),
            isActiveQuestionSetBeingValidated: HR(state, this.activeQuestionSet),
        });
        this.activeQuestionSet = undefined;
        this.buttonDisabled = false;
        this.config = undefined;
        this.queue = undefined;
        this.shouldDisableIfIncomplete = false;
        this.answersResourceState = undefined;
        this.applicationFormResourceState = undefined;
        this.questionPoolResourceState = undefined;
        this.questionSetResourceState = undefined;
        this.questionSetState = undefined;
        this.locked = undefined;
        this.pendingProcesses = undefined;
        this.isOwner = undefined;
        this.hasPermissionToEdit = undefined;
        this.isActiveQuestionSetPendingProcess = undefined;
        this.enableUserApplicationGuard = undefined;
        this.applicationId = undefined;
        this.addressValidationStatuses = undefined;
        this.addressIdsToBeValidated = undefined;
        this.isValidationTriggerOverridden = undefined;
        this.useExternal = false;
        this.canSave = true;
        this.areResourcesReady = true;
        this.isDisabled = false;
        this.caDisabled = false;
        this.isReady = true;
        this.isLocked = false;
        this.isFirstRun = true;
        this.classes = '';
        this.isActiveQuestionSetBeingValidated = undefined;
    }
    resetState() {
        this.isReady = true;
        this.isFirstRun = true;
    }
    connectedCallback() {
        this.resetState();
        this.handleSubscriptions();
    }
    componentWillLoad() {
        this.useExternal = !!customElements.get('bp-sdk-external-next-button-container');
        customElements.whenDefined('bp-sdk-external-next-button-container').then(() => {
            this.useExternal = true;
        });
        this.handleSubscriptions();
        this.onShouldDisableIfIncompleteChange(this.shouldDisableIfIncomplete);
        this.onAnswersResourcesStateChange(this.answersResourceState);
        this.onApplicationFormResourceStateChange(this.applicationFormResourceState);
        this.onHasPermissionToEdit(this.hasPermissionToEdit);
        this.onEnableUserApplicationGuard(this.enableUserApplicationGuard);
        this.onIsFirstRun(this.isFirstRun);
        this.onIsOwner(this.isOwner);
        this.onIsReady(this.isReady);
        this.onLocked(this.locked);
        this.onQuestionPoolResourcesStateChange(this.questionPoolResourceState);
        this.onQuestionSetResourcesStateChange(this.questionSetResourceState);
        this.onQueueChange(this.queue);
        this.onIsActiveQuestionSetPendingProcess(this.isActiveQuestionSetPendingProcess);
        this.onAddressValidationStatusChange(this.addressValidationStatuses);
    }
    onEnableUserApplicationGuard(enableUserApplicationGuard) {
        this.updateIsLocked(this.locked, this.isOwner, this.hasPermissionToEdit, enableUserApplicationGuard);
    }
    onHasPermissionToEdit(hasPermission) {
        this.updateIsLocked(this.locked, this.isOwner, hasPermission, this.enableUserApplicationGuard);
    }
    onIsOwner(isOwner) {
        this.updateIsLocked(this.locked, isOwner, this.hasPermissionToEdit, this.enableUserApplicationGuard);
    }
    onLocked(locked) {
        this.updateIsLocked(locked, this.isOwner, this.hasPermissionToEdit, this.enableUserApplicationGuard);
    }
    updateIsLocked(locked, isOwner, hasPermission, enableUserApplicationGuard) {
        this.isLocked = locked || (enableUserApplicationGuard && (!isOwner || !hasPermission));
    }
    onIsFirstRun(isFirstRun) {
        this.updateAreResourcesReady(isFirstRun, this.isReady);
    }
    onIsReady(isReady) {
        this.updateAreResourcesReady(this.isFirstRun, isReady);
    }
    updateAreResourcesReady(isFirstRun, isReady) {
        this.areResourcesReady = isFirstRun || isReady;
    }
    onAnswersResourcesStateChange(state) {
        this.isReady = this.calculateResourcesReady({
            answers: state,
            applicationForm: this.applicationFormResourceState,
            questionPools: this.questionPoolResourceState,
            questionSets: this.questionSetResourceState,
        });
    }
    onApplicationFormResourceStateChange(state) {
        if (this.isFirstRun && state === d.Loaded) {
            this.isFirstRun = false;
        }
        this.isReady = this.calculateResourcesReady({
            answers: this.answersResourceState,
            applicationForm: state,
            questionPools: this.questionPoolResourceState,
            questionSets: this.questionSetResourceState,
        });
    }
    onQuestionPoolResourcesStateChange(state) {
        this.isReady = this.calculateResourcesReady({
            answers: this.answersResourceState,
            applicationForm: this.applicationFormResourceState,
            questionPools: state,
            questionSets: this.questionSetResourceState,
        });
    }
    onQuestionSetResourcesStateChange(state) {
        this.isReady = this.calculateResourcesReady({
            answers: this.answersResourceState,
            applicationForm: this.applicationFormResourceState,
            questionPools: this.questionPoolResourceState,
            questionSets: state,
        });
    }
    calculateResourcesReady(resources = {}) {
        if (!resources ||
            resources.applicationForm !== d.Loaded ||
            resources.answers === d.Loading ||
            resources.questionPools === d.Loading ||
            resources.questionSets === d.Loading) {
            return false;
        }
        return true;
    }
    onShouldDisableIfIncompleteChange(shouldDisableIfIncomplete) {
        this.updateOnDisableIfIncomplete(shouldDisableIfIncomplete, this.activeQuestionSet);
    }
    onActiveQuestionSetChange(activeQuestionSet) {
        this.updateOnDisableIfIncomplete(this.shouldDisableIfIncomplete, activeQuestionSet);
        this.disableIfCAQuestionSet(this.shouldDisableIfIncomplete, activeQuestionSet);
    }
    onQueueChange(queue) {
        this.canSave = !(queue === null || queue === void 0 ? void 0 : queue.length) && !this.isActiveQuestionSetPendingProcess;
    }
    onAddressValidationStatusChange(statuses) {
        if (statuses &&
            this.activeQuestionSet &&
            Object.values(statuses).some((status) => status === se.PROCEED_NEXT || status === se.VALIDATION_ERROR) &&
            !this.isValidationTriggerOverridden) {
            const filteredIds = Object.keys(statuses).filter((id) => this.activeQuestionSet.answers.map((answer) => answer.answer_pool_id).includes(id) ||
                this.activeQuestionSet.question_set.question_groups.map((group) => group.id).includes(id));
            if (filteredIds.every((id) => statuses[id] === se.PROCEED_NEXT ||
                statuses[id] === se.COMPLETED ||
                statuses[id] === se.VALIDATION_ERROR)) {
                this.saveQuestionSetAndProceed();
                filteredIds
                    .filter((id) => statuses[id] === se.PROCEED_NEXT)
                    .forEach((addressValidationId) => this.setAddressValidationStatus({ validationStatus: se.COMPLETED, addressValidationId }));
                filteredIds
                    .filter((id) => statuses[id] === se.VALIDATION_ERROR)
                    .forEach((addressValidationId) => this.setAddressValidationStatus({ validationStatus: se.REQUIRED, addressValidationId }));
            }
        }
    }
    onIsActiveQuestionSetPendingProcess(isQSPending) {
        this.canSave = !isQSPending;
    }
    disableIfCAQuestionSet(shouldDisableIfIncomplete, activeQuestionSet) {
        let shouldDisable = false;
        if (shouldDisableIfIncomplete && activeQuestionSet) {
            shouldDisable = $i(activeQuestionSet);
        }
        if (this.caDisabled !== shouldDisable) {
            this.caDisabled = shouldDisable;
        }
    }
    updateOnDisableIfIncomplete(shouldDisableIfIncomplete, activeQuestionSet) {
        this.isDisabled = shouldDisableIfIncomplete && this.isDisabledStatusByActiveQuestionSet(activeQuestionSet);
    }
    render() {
        return [this.useExternal && this.renderExternal(), !this.useExternal && this.renderInternal()];
    }
    renderExternal() {
        return (h("bp-sdk-external-next-button-container", { activeQuestionSet: this.activeQuestionSet, answersResourceState: this.answersResourceState, applicationFormResourceState: this.applicationFormResourceState, applicationId: this.applicationId, buttonDisabled: this.buttonDisabled, config: this.config, enableUserApplicationGuard: this.enableUserApplicationGuard, hasPermissionToEdit: this.hasPermissionToEdit, isOwner: this.isOwner, locked: this.locked, pendingProcesses: this.pendingProcesses, questionPoolResourceState: this.questionPoolResourceState, questionSetResourceState: this.questionSetResourceState, questionSetState: this.questionSetState, queue: this.queue, shouldDisableIfIncomplete: this.shouldDisableIfIncomplete, isActiveQuestionSetPendingProcess: this.isActiveQuestionSetPendingProcess }));
    }
    handleNavigateNext() {
        if (this.isAddressValidationRequired()) {
            this.handleValidation();
        }
        else {
            this.saveQuestionSetAndProceed();
        }
    }
    renderInternal() {
        return (h("bp-sdk-next-button", { buttonDisabled: !this.isNextButtonClickable() || this.isActiveQuestionSetBeingValidated, cssClasses: !this.areResourcesReady || !this.canSave ? 'loading' : 'not-loading' }));
    }
    parentQuestionSetCanSave() {
        const parentQuestionSet = this.questionSetState.parentQuestionSets.find((pqs) => pqs.id === this.activeQuestionSet.parentQuestionSetId);
        if (parentQuestionSet) {
            return this.questionSetState.list
                .filter((qs) => qs.parentQuestionSetId === parentQuestionSet.id)
                .every((qs) => et(qs.answers));
        }
    }
    saveQuestionSetAndProceed() {
        if (this.shouldCallSaveQuestionSet()) {
            const invalidAnswers = this.activeQuestionSet.answers.filter((answer) => !hi(answer));
            if (!invalidAnswers.length && this.isNextButtonClickable()) {
                this.removeActiveAnswerId();
                if (!this.activeQuestionSet.parentQuestionSetId) {
                    this.callSaveQuestionSet();
                }
                else {
                    if (this.parentQuestionSetCanSave()) {
                        this.callSaveQuestionSet(true);
                    }
                    else {
                        this.handleStep();
                    }
                }
            }
            else {
                invalidAnswers.forEach((answer) => {
                    this.updateErrors({ answer, errors: Jr(answer) });
                });
                s$();
            }
        }
        else if (this.isNextButtonClickable()) {
            this.switchActiveQuestionSet('forward');
        }
    }
    callSaveQuestionSet(useParent = false) {
        this.saveQuestionSet({
            config: this.config,
            appFormQuestionSet: this.activeQuestionSet,
            navigationDirection: 'forward',
            parentQuestionSet: useParent
                ? this.questionSetState.parentQuestionSets.find((pqs) => pqs.id === this.activeQuestionSet.parentQuestionSetId)
                : undefined,
        });
        this.bpAnalyticsTrack.emit({
            eventName: he.QuestionSetSaved,
            eventPayload: {
                applicationFormQuestionSetId: this.activeQuestionSet.id,
                questionSetId: this.activeQuestionSet.question_set_id,
                questionSetCode: this.activeQuestionSet.question_set.code,
            },
        });
    }
    handleStep() {
        const parent = ww(this.activeQuestionSet, this.questionSetState);
        const newValue = Sw(this.activeQuestionSet);
        if (parent.value !== newValue) {
            this.pushAnswer(Sa(parent, newValue));
        }
        this.getEligibilityResults({ appId: this.applicationId, config: this.config });
        this.switchActiveQuestionSet('forward');
    }
    isDisabledStatusByActiveQuestionSet(activeQuestionSet) {
        var _a;
        // If missing active question set then default to disable.
        if (!activeQuestionSet) {
            return true;
        }
        // If missing answers then default to enabled
        if (!activeQuestionSet.answers || ((_a = activeQuestionSet.answers) === null || _a === void 0 ? void 0 : _a.length) === 0) {
            return false;
        }
        // Else state determined by if all required answers are completed
        return activeQuestionSet.answers.some((answer) => !answer.is_completed && answer.required);
    }
    shouldCallSaveQuestionSet() {
        if (this.isLocked) {
            return false;
        }
        return !this.activeQuestionSet.is_completed || !!this.activeQuestionSet.parentQuestionSetId;
    }
    isNextButtonClickable() {
        return !this.buttonDisabled && this.areResourcesReady && this.canSave && !this.isDisabled && !this.caDisabled;
    }
    isAddressValidationRequired() {
        return Object.keys(this.addressValidationStatuses).some((id) => this.activeQuestionSet.answers.map((answer) => answer.answer_pool_id).includes(id) ||
            this.activeQuestionSet.question_set.question_groups.map((group) => group.id).includes(id));
    }
    handleValidation() {
        if (this.isValidationTriggerOverridden) {
            this.setAddressValidationTriggerOverridden(false);
        }
        const presentRequiredIds = this.addressIdsToBeValidated.filter((id) => this.activeQuestionSet.answers.map((answer) => answer.answer_pool_id).includes(id) ||
            this.activeQuestionSet.question_set.question_groups.map((group) => group.id).includes(id));
        if (!!presentRequiredIds.length) {
            presentRequiredIds.forEach((addressValidationId) => {
                this.setAddressValidationStatus({ validationStatus: se.READY_TO_VALIDATE, addressValidationId });
            });
        }
        else {
            const filteredIds = Object.keys(this.addressValidationStatuses).filter((id) => this.activeQuestionSet.answers.map((answer) => answer.answer_pool_id).includes(id) ||
                this.activeQuestionSet.question_set.question_groups.map((group) => group.id).includes(id));
            if (filteredIds.every((id) => this.addressValidationStatuses[id] === se.COMPLETED ||
                this.addressValidationStatuses[id] === se.VALIDATION_ERROR)) {
                this.saveQuestionSetAndProceed();
            }
        }
    }
    static get watchers() { return {
        "enableUserApplicationGuard": ["onEnableUserApplicationGuard"],
        "hasPermissionToEdit": ["onHasPermissionToEdit"],
        "isOwner": ["onIsOwner"],
        "locked": ["onLocked"],
        "isFirstRun": ["onIsFirstRun"],
        "isReady": ["onIsReady"],
        "answersResourceState": ["onAnswersResourcesStateChange"],
        "applicationFormResourceState": ["onApplicationFormResourceStateChange"],
        "questionPoolResourceState": ["onQuestionPoolResourcesStateChange"],
        "questionSetResourceState": ["onQuestionSetResourcesStateChange"],
        "shouldDisableIfIncomplete": ["onShouldDisableIfIncompleteChange"],
        "activeQuestionSet": ["onActiveQuestionSetChange"],
        "queue": ["onQueueChange"],
        "addressValidationStatuses": ["onAddressValidationStatusChange"],
        "isActiveQuestionSetPendingProcess": ["onIsActiveQuestionSetPendingProcess"]
    }; }
};
BpSdkNextButtonContainer.style = BpSdkNextButtonContainerStyle0;

export { BpSdkNextButtonContainer as bp_sdk_next_button_container };
