'use strict';

var index = require('./index-p7cvUYAE.js');
var Api = require('./Api-D9vOcUw4.js');
var Plaid = require('./Plaid-CPESyiiV.js');
require('./Pagination-Dediz133.js');
require('./Business-oBifyXkW.js');
var utils = require('./utils-BsnepLy6.js');
var Analytics = require('./Analytics-C6KBHEIP.js');
var checkPkgVersion = require('./check-pkg-version-B9EoYyZR.js');
var checkout_store = require('./checkout.store-CZHrIuaP.js');
var utils$1 = require('./utils-CYONRFR6.js');
var insuranceState = require('./insurance-state-B-XQRmMs.js');
var parts = require('./parts-BXshb_S-.js');
var styledHost = require('./styled-host-Ch0-dxF-.js');
require('./event-types-YOY5TKUN.js');
var skeleton = require('./skeleton-DvRCiQlA.js');
require('./config-state-BIgGhhe9.js');
require('./index-W-zoNiyM.js');
require('./package-YyJzVqrh.js');
require('./index-CajjbB9t.js');
require('./dinero-BwNN_k7x.js');

const api = Api.Api();
class InsuranceService {
    async fetchQuote(authToken, payload) {
        const endpoint = 'insurance/quotes';
        const body = payload;
        return api.post({ endpoint, body, authToken });
    }
    async toggleCoverage(authToken, quoteId, payload) {
        const endpoint = `insurance/quotes/${quoteId}/toggle`;
        const body = payload;
        return api.post({ endpoint, body, authToken });
    }
}

const makeGetQuote = ({ authToken, service }) => async ({ payload, onSuccess, onError }) => {
    var _a;
    try {
        const response = await service.fetchQuote(authToken, payload);
        if (!response.error) {
            const quote = response.data;
            onSuccess({ quote });
        }
        else {
            const responseError = utils.getErrorMessage(response.error);
            const code = utils.getErrorCode((_a = response.error) === null || _a === void 0 ? void 0 : _a.code);
            return onError({
                error: responseError,
                code,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = utils.getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: Plaid.ComponentErrorSeverity.ERROR,
        });
    }
};
const makeToggleCoverage = ({ authToken, service }) => async ({ quoteId, payload, onSuccess, onError }) => {
    var _a;
    try {
        const response = await service.toggleCoverage(authToken, quoteId, payload);
        if (!response.error) {
            const quote = response.data;
            onSuccess({ quote });
        }
        else {
            const responseError = utils.getErrorMessage(response.error);
            const code = utils.getErrorCode((_a = response.error) === null || _a === void 0 ? void 0 : _a.code);
            return onError({
                error: responseError,
                code,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = utils.getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: Plaid.ComponentErrorSeverity.ERROR,
        });
    }
};

const SeasonInterruptionInsuranceLoading = () => (index.h("div", { class: "row gap-3" }, index.h("div", { class: "col-12" }, index.h(skeleton.Skeleton, { width: "35%", height: "30px" })), index.h("div", { class: "col-12" }, index.h(skeleton.Skeleton, { width: "70%" })), index.h("div", { class: "col-12" }, index.h(skeleton.Skeleton, { width: "40%" })), index.h("div", { class: "col-12" }, index.h(skeleton.Skeleton, { width: "40%" })), index.h("div", { class: "col-12" }, index.h(skeleton.Skeleton, { width: "100%" })), index.h("div", { class: "col-12" }, index.h(skeleton.Skeleton, { width: "80%" }))));

const JustifiSeasonInterruptionInsurance = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.insuranceUpdated = index.createEvent(this, "insurance-updated", 7);
        this.errorEvent = index.createEvent(this, "error-event", 7);
        this.isLoading = true;
    }
    async validate() {
        return insuranceState.validateInsuranceValues();
    }
    processHTMLContent(html) {
        return utils$1.processHTML(html, [
            (html) => utils$1.removeAttribute(html, 'style'),
            (html) => utils$1.addAttribute(html, 'a', 'part', parts.text),
            (html) => utils$1.addAttribute(html, 'p', 'part', parts.text),
        ]);
    }
    componentWillLoad() {
        checkPkgVersion.checkPkgVersion();
        this.analytics = new Analytics.JustifiAnalytics(this);
        this.initializeServiceMethods();
        if (this.getQuote) {
            this.fetchData();
        }
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    initializeServiceMethods() {
        const authToken = this.authToken || checkout_store.checkoutStore.authToken;
        if (!authToken) {
            this.errorEvent.emit({
                errorCode: Plaid.ComponentErrorCodes.MISSING_PROPS,
                message: 'Missing authToken',
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
            return;
        }
        const service = new InsuranceService();
        const config = { authToken, service };
        this.getQuote = makeGetQuote(config);
        this.toggleCoverage = makeToggleCoverage(config);
    }
    fetchData() {
        this.isLoading = true;
        this.getQuote({
            payload: {
                checkout_id: this.checkoutId || checkout_store.checkoutStore.checkoutId,
                policy_type: "season_interruption",
                primary_identity: {
                    state: this.primaryIdentityState,
                    email: this.primaryIdentityEmailAddress,
                    first_name: this.primaryIdentityFirstName,
                    last_name: this.primaryIdentityLastName,
                    postal_code: this.primaryIdentityPostalCode,
                    country: this.primaryIdentityCountry
                },
                policy_attributes: {
                    insurable_amount: this.policyAttributesInsurableAmount,
                    start_date: this.policyAttributesStartDate,
                    end_date: this.policyAttributesEndDate,
                    covered_identity: {
                        first_name: this.coveredIdentityFirstName,
                        last_name: this.coveredIdentityLastName
                    }
                }
            },
            onSuccess: ({ quote }) => {
                this.quote = quote;
                this.quote.product.description = this.processHTMLContent(this.quote.product.description);
                this.quote.product.legal_disclaimer = this.processHTMLContent(this.quote.product.legal_disclaimer);
                insuranceState.insuranceValues[quote.policy_type] = quote.accepted;
                this.isLoading = false;
            },
            onError: ({ error, code, severity }) => {
                this.isLoading = false;
                this.errorEvent.emit({
                    errorCode: code,
                    message: error,
                    severity,
                });
            }
        });
    }
    onChangeHandler(_name, value) {
        this.accepted = value;
        insuranceState.insuranceErrors[this.quote.policy_type] = false;
        this.toggleCoverage({
            quoteId: this.quote.id,
            payload: { accepted: this.accepted },
            onSuccess: () => {
                this.insuranceUpdated.emit();
                insuranceState.insuranceValues[this.quote.policy_type] = this.accepted;
            },
            onError: ({ error, code, severity }) => {
                this.errorEvent.emit({
                    errorCode: code,
                    message: error,
                    severity,
                });
            }
        });
    }
    get error() {
        var _a;
        return insuranceState.insuranceErrors[(_a = this.quote) === null || _a === void 0 ? void 0 : _a.policy_type];
    }
    render() {
        var _a, _b, _c, _d;
        if (checkout_store.checkoutStore && checkout_store.checkoutStore.insuranceEnabled === false) {
            console.warn('[justifi-season-interruption-insurance] Insurance is disabled for this checkout (payment_settings.insurance_payments=false).');
            return null;
        }
        if (this.isLoading)
            return (index.h(styledHost.StyledHost, null, index.h(SeasonInterruptionInsuranceLoading, null)));
        return (index.h(styledHost.StyledHost, null, index.h("div", null, index.h(insuranceState.Header2, { text: (_a = this.quote) === null || _a === void 0 ? void 0 : _a.product.title, class: "fs-5 fw-bold pb-3" }), index.h("small", { part: parts.text, innerHTML: (_b = this.quote) === null || _b === void 0 ? void 0 : _b.product.description }), index.h("form-control-radio", { label: `Accept coverage for ${utils$1.formatCurrency((_c = this.quote) === null || _c === void 0 ? void 0 : _c.total_cents)}`, name: "opt-in", value: 'true', checked: this.accepted === 'true', inputHandler: this.onChangeHandler.bind(this),
            // don't wanna show error message, but need to show the red border
            errorText: this.error ? ' ' : undefined }), index.h("form-control-radio", { label: "Decline coverage", name: "opt-in", value: 'false', checked: this.accepted === 'false', inputHandler: this.onChangeHandler.bind(this), errorText: this.error ? ' ' : undefined }), index.h("div", { class: "invalid-feedback", style: { display: this.error ? 'block' : 'none' }, part: parts.textDanger }, "Please select an option"), index.h("small", { part: parts.text, innerHTML: (_d = this.quote) === null || _d === void 0 ? void 0 : _d.product.legal_disclaimer }))));
    }
};

exports.justifi_season_interruption_insurance = JustifiSeasonInterruptionInsurance;
