import { h, r as registerInstance, c as createEvent } from './index-CV0Pyo1O.js';
import { A as Api } from './Api-BulOmiMS.js';
import { C as ComponentErrorSeverity, b as ComponentErrorCodes } from './Plaid-DxSkT8pY.js';
import './Pagination-CLHwhyvu.js';
import './Business-BcNb9bVO.js';
import { g as getErrorCode, a as getErrorMessage } from './utils-CVYvs2hZ.js';
import { J as JustifiAnalytics } from './Analytics-C76Y5Pqf.js';
import { c as checkPkgVersion } from './check-pkg-version-D5BxTNyL.js';
import { c as checkoutStore } from './checkout.store-DibfdUMm.js';
import { p as processHTML, f as formatCurrency, r as removeAttribute, i as addAttribute } from './utils-C25uIOK0.js';
import { v as validateInsuranceValues, i as insuranceValues, a as insuranceErrors, H as Header2 } from './insurance-state-C5OZqDCT.js';
import { t as text, z as textDanger } from './parts-CPKMvyV_.js';
import { S as StyledHost } from './styled-host-D84RBv1W.js';
import './event-types-CZfYo5-1.js';
import { S as Skeleton } from './skeleton-BEHo2ypu.js';
import './config-state-kKn89dp1.js';
import './index-cDVGjRkU.js';
import './package-CqcLgdsl.js';
import './index-DkoufM1t.js';
import './dinero-HXpYMWUU.js';

const 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 = getErrorMessage(response.error);
            const code = getErrorCode((_a = response.error) === null || _a === void 0 ? void 0 : _a.code);
            return onError({
                error: responseError,
                code,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: 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 = getErrorMessage(response.error);
            const code = getErrorCode((_a = response.error) === null || _a === void 0 ? void 0 : _a.code);
            return onError({
                error: responseError,
                code,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: ComponentErrorSeverity.ERROR,
        });
    }
};

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

const JustifiSeasonInterruptionInsurance = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.insuranceUpdated = createEvent(this, "insurance-updated", 7);
        this.errorEvent = createEvent(this, "error-event", 7);
        this.isLoading = true;
    }
    async validate() {
        return validateInsuranceValues();
    }
    processHTMLContent(html) {
        return processHTML(html, [
            (html) => removeAttribute(html, 'style'),
            (html) => addAttribute(html, 'a', 'part', text),
            (html) => addAttribute(html, 'p', 'part', text),
        ]);
    }
    componentWillLoad() {
        checkPkgVersion();
        this.analytics = new 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 || checkoutStore.authToken;
        if (!authToken) {
            this.errorEvent.emit({
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                message: 'Missing authToken',
                severity: 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 || 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);
                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;
        insuranceErrors[this.quote.policy_type] = false;
        this.toggleCoverage({
            quoteId: this.quote.id,
            payload: { accepted: this.accepted },
            onSuccess: () => {
                this.insuranceUpdated.emit();
                insuranceValues[this.quote.policy_type] = this.accepted;
            },
            onError: ({ error, code, severity }) => {
                this.errorEvent.emit({
                    errorCode: code,
                    message: error,
                    severity,
                });
            }
        });
    }
    get error() {
        var _a;
        return insuranceErrors[(_a = this.quote) === null || _a === void 0 ? void 0 : _a.policy_type];
    }
    render() {
        var _a, _b, _c, _d;
        if (checkoutStore && 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 (h(StyledHost, null, h(SeasonInterruptionInsuranceLoading, null)));
        return (h(StyledHost, null, h("div", null, h(Header2, { text: (_a = this.quote) === null || _a === void 0 ? void 0 : _a.product.title, class: "fs-5 fw-bold pb-3" }), h("small", { part: text, innerHTML: (_b = this.quote) === null || _b === void 0 ? void 0 : _b.product.description }), h("form-control-radio", { label: `Accept coverage for ${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 }), 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 }), h("div", { class: "invalid-feedback", style: { display: this.error ? 'block' : 'none' }, part: textDanger }, "Please select an option"), h("small", { part: text, innerHTML: (_d = this.quote) === null || _d === void 0 ? void 0 : _d.product.legal_disclaimer }))));
    }
};

export { JustifiSeasonInterruptionInsurance as justifi_season_interruption_insurance };
