import { r as registerInstance, c as createEvent, h, F as Fragment, g as getElement } from './index-77a9c9e7.js';
import { s as sn, U as Uc, L as Lo, A as AH, z as OH, l as lR, u as up, B as Te, X as Xt, K as KL, C as mR } from './index.esm.min-db2d29e8.js';
import { p as pt } from './index.esm.min-f72e1bc6.js';
import { P, d, b as s, q } from './index.esm.min-9889e78b.js';
import { i as isEqual_1 } from './isEqual-064ed72d.js';
import { s as store } from './redux-store.service-dc54f48e.js';
import './_commonjsHelpers-1789f0cf.js';

const BpSdkQuoteRequestContainer = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.bpAnalyticsTrack = createEvent(this, "bpAnalyticsTrack", 7);
        this.handleSubscriptions = () => {
            this.storeUnsubscribe && this.storeUnsubscribe();
            store.mapDispatchToProps(this, {
                bindQuoteRequest: sn,
                timeoutQuoteState: Uc,
                quoteActionBind: Lo,
                setFilteredOfflineQuotes: AH,
                setFilteredOnlineQuotes: OH,
            });
            this.storeUnsubscribe = store.mapStateToProps(this, this.mapStateToProps);
        };
        this.mapStateToProps = (state) => {
            return {
                appFormState: state.application.form.state,
                applicationFormResourceState: lR(state),
                config: up(state),
                configOptions: Te(state),
                carriersProducts: Xt(state) || [],
                carriersProductsResourceState: KL(state),
                quotes: state.application.quotes || [],
                quotesResourceState: mR(state),
            };
        };
        this.handleQuoteTimeout = () => {
            this.timeoutQuoteState();
        };
        this.handleBind = (quoteId, appFormId, afterResponse) => {
            this.bindQuoteRequest({
                quoteId,
                appFormId,
                afterResponse,
                config: this.config,
            });
        };
        this.handleQuoteActionBind = (action, quote) => {
            // Pay actions have no API to hit and only update internal state logic
            if (action.value === 'pay') {
                this.showQuotePayment = true;
                return;
            }
            this.quoteActionBind({
                action,
                quote,
                config: this.config,
            });
        };
        this.handleDownload = (id, filename) => {
            pt.getAttachment(id, this.config).then((data) => {
                const a = document.createElement('a');
                a.href = window.URL.createObjectURL(data.parsedBody);
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                a.remove();
            });
        };
        this.renderQuotes = () => {
            var _a;
            return [
                !this.filteredOnlineQuotes.length && !this.filteredOfflineQuotes.length && [],
                this.filteredOnlineQuotes.map((quote) => {
                    const quoteInfo = {
                        annual_price: quote.annual_price,
                        monthly_price: quote.monthly_price,
                        number_of_installments: quote.number_of_installments,
                        downpayment: quote.downpayment,
                        semiannual_price: quote.semiannual_price,
                        price_details: quote.price_details,
                        quote_number: quote.quote_number,
                    };
                    const quoteStatus = {
                        recommended: quote.recommended,
                        selected: quote.selected,
                        consumer_selected: quote.consumer_selected,
                        focused: quote.focused,
                        expired: quote.expired,
                    };
                    return (h(Fragment, null, h("bp-sdk-quote-request", { actions: quote.actions, appFormId: quote.application_form_id, attachments: quote.attachments, bindable: quote.bindable, carrier: quote.carrier, customLogoBaseUrl: this.customLogoBaseUrl, handleAction: this.handleQuoteActionBind, handleBind: this.handleBind, handleDownload: this.handleDownload, permittedToBind: quote.permitted_to_bind, products: quote.products, quoteId: quote.id, quoteInfo: quoteInfo, quoteStatus: quoteStatus, requestStatus: quote.request_status, satisfiesApplicationFormProductRequest: quote.satisfies_application_form_product_request, showCustomLogo: this.showCustomLogo, showLogo: this.showLogo, translatedMessages: quote.translated_messages, supplierName: quote.supplier_name, supplierLogoUrl: quote.supplier_logo_url, supplierLogoUrlFull: quote.supplier_logo_url_full, supplierCode: quote.supplier_code, parentQuoteRequestId: quote.parentQuoteRequestId }), this.renderQuotePayment(quote)));
                }),
                ((_a = this.configOptions) === null || _a === void 0 ? void 0 : _a.renderOfflineQuotes) &&
                    this.filteredOfflineQuotes.map((offlineQuote) => {
                        return (h("bp-sdk-offline-quote", { carrier: offlineQuote.carrier, product: offlineQuote.product, showLogo: this.showLogo, showCustomLogo: this.showCustomLogo, customLogoBaseUrl: this.customLogoBaseUrl }));
                    }),
                !this.disableSendToExchange && h("bp-sdk-send-to-exchange-container", null),
            ];
        };
        this.showLogo = true;
        this.showCustomLogo = false;
        this.customLogoBaseUrl = '';
        this.disableSendToExchange = false;
        this.quotes = [];
        this.carriersProducts = undefined;
        this.applicationFormResourceState = undefined;
        this.quotesResourceState = undefined;
        this.appFormState = undefined;
        this.config = undefined;
        this.carriersProductsResourceState = undefined;
        this.configOptions = undefined;
        this.quoteTimeout = 90;
        this.showAllQuotes = false;
        this.quotesSortFn = (a, b) => {
            return a.order - b.order;
        };
        this.offlineQuotesSortFn = undefined;
        this.filteredCarrierCodes = [];
        this.useExternal = false;
        this.isReady = true;
        this.showQuotePayment = false;
        this.filteredOnlineQuotes = [];
        this.filteredOfflineQuotes = [];
    }
    resetState() {
        this.showQuotePayment = false;
    }
    connectedCallback() {
        this.resetState();
        this.handleSubscriptions();
    }
    componentWillLoad() {
        this.useExternal = !!customElements.get('bp-sdk-external-quote-request-container');
        customElements.whenDefined('bp-sdk-external-quote-request-container').then(() => {
            this.useExternal = true;
        });
        this.handleSubscriptions();
        this.onApplicationResourceStateChange(this.applicationFormResourceState);
        this.onQuotesResourceStateChange(this.quotesResourceState);
    }
    disconnectedCallback() {
        this.storeUnsubscribe && this.storeUnsubscribe();
    }
    onCarriersProductsChange(carriersProducts) {
        if (this.useExternal) {
            return;
        }
        const onlineCarrierIds = this.quotes.map((quote) => quote.carrier.id);
        const filteredOfflineQuotes = carriersProducts.filter((offlineQuote) => {
            // TODO(hybrid_appetite): keep market, remove legacy check of `carrier.online`
            // legacy: online vs offline carrier products
            const shouldRenderLegacyOfflineQuote = !onlineCarrierIds.includes(offlineQuote.carrier.id) && !offlineQuote.carrier.online;
            // next gen: market to indicate where carrier can quote
            const shouldRenderNextGenOfflineQuote = offlineQuote.market && offlineQuote.market === q.OFFLINE;
            const shouldQuoteCarrierRender = this.filteredCarrierCodes.length > 0 ? this.filteredCarrierCodes.includes(offlineQuote.carrier.code) : true;
            return shouldQuoteCarrierRender && (shouldRenderLegacyOfflineQuote || shouldRenderNextGenOfflineQuote);
        });
        if (this.offlineQuotesSortFn) {
            filteredOfflineQuotes.sort(this.offlineQuotesSortFn);
        }
        this.filteredOfflineQuotes = filteredOfflineQuotes;
        this.setFilteredOfflineQuotes(filteredOfflineQuotes);
    }
    onQuotesChange(quotes, oldQuotes) {
        if (this.useExternal) {
            return;
        }
        const filteredOnlineQuotes = this.quotes.filter((quote) => {
            var _a, _b;
            const shouldQuoteCarrierRender = this.filteredCarrierCodes.length > 0 ? this.filteredCarrierCodes.includes(quote.carrier.code) : true;
            const shouldQuoteStatusRender = ((_b = (_a = this.configOptions) === null || _a === void 0 ? void 0 : _a.quoteStatusFilter) !== null && _b !== void 0 ? _b : []).includes(quote.request_status);
            return (shouldQuoteStatusRender && shouldQuoteCarrierRender) || this.showAllQuotes;
        });
        if (this.quotesSortFn) {
            filteredOnlineQuotes.sort(this.quotesSortFn);
        }
        this.filteredOnlineQuotes = filteredOnlineQuotes;
        this.setFilteredOnlineQuotes(filteredOnlineQuotes);
        if (!isEqual_1(quotes, oldQuotes)) {
            const label = quotes
                .map((q) => `${q.carrier.name}_${q.annual_price}_${q.bindable ? P.additionalQuoteOnline : P.additionalQuoteOffline}`)
                .join('; ');
            this.bpAnalyticsTrack.emit({
                eventName: 'Display_Additional',
                eventPayload: {
                    label,
                    value: 0,
                },
            });
        }
    }
    onApplicationResourceStateChange(newState) {
        this.updateResource(newState, this.quotesResourceState);
    }
    onQuotesResourceStateChange(newState, oldState) {
        this.updateResource(this.applicationFormResourceState, newState);
        if (!!oldState && oldState !== d.Loading && newState === d.Loading) {
            // Kick off timer to automatically set to quoted after timeout expires
            setTimeout(this.handleQuoteTimeout, this.quoteTimeout * 1000);
        }
    }
    updateResource(applicationForm, quotes) {
        this.isReady = applicationForm === d.Loading || quotes !== d.Loading || this.configOptions.renderQuotesAsync;
    }
    isAppFormReadyToShowQuotes() {
        var _a;
        return ((_a = this.configOptions) === null || _a === void 0 ? void 0 : _a.renderQuotesWithAppState)
            ? this.configOptions.renderQuotesWithAppState.includes(this.appFormState)
            : [s.Completed, s.Quoted].includes(this.appFormState);
    }
    componentWillUpdate() {
        this.handleSubscriptions();
    }
    render() {
        return [this.useExternal && this.renderExternal(), !this.useExternal && this.renderInternal()];
    }
    renderExternal() {
        return (h("bp-sdk-external-quote-request-container", { appFormState: this.appFormState, applicationFormResourceState: this.applicationFormResourceState, config: this.config, configOptions: this.configOptions, customLogoBaseUrl: this.customLogoBaseUrl, disableSendToExchange: this.disableSendToExchange, eligibilityCarrierProducts: this.carriersProducts, carriersProductsResourceState: this.carriersProductsResourceState, quoteTimeout: this.quoteTimeout, quotes: this.quotes, quotesResourceState: this.quotesResourceState, showCustomLogo: this.showCustomLogo, showLogo: this.showLogo, showAllQuotes: this.showAllQuotes, quotesSortFn: this.quotesSortFn, offlineQuotesSortFn: this.offlineQuotesSortFn, filteredCarrierCodes: this.filteredCarrierCodes }));
    }
    renderQuotePayment(quote) {
        var _a;
        if (this.showQuotePayment && ((_a = quote === null || quote === void 0 ? void 0 : quote.actions) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            return h("bp-sdk-quote-payment", { quoteRequest: quote });
        }
    }
    renderInternal() {
        return [!this.isReady && h("bp-sdk-quote-load", null), this.isReady && this.isAppFormReadyToShowQuotes() && this.renderQuotes(), h("slot", null)];
    }
    get el() { return getElement(this); }
    static get watchers() { return {
        "carriersProducts": ["onCarriersProductsChange"],
        "quotes": ["onQuotesChange"],
        "applicationFormResourceState": ["onApplicationResourceStateChange"],
        "quotesResourceState": ["onQuotesResourceStateChange"]
    }; }
};

export { BpSdkQuoteRequestContainer as bp_sdk_quote_request_container };
