import { h, proxyCustomElement, HTMLElement, createEvent } from '@stencil/core/internal/client';
import { A as Api } from './Api.js';
import { C as ComponentErrorSeverity, a as ComponentErrorCodes } from './Plaid.js';
import './Pagination.js';
import './Business.js';
import './ApplePay.js';
import { g as getErrorCode, a as getErrorMessage } from './utils3.js';
import { J as JustifiAnalytics } from './Analytics.js';
import { c as checkPkgVersion } from './check-pkg-version.js';
import { c as checkoutStore } from './checkout.store.js';
import { p as processHTML, b as formatCurrency, r as removeAttribute, k as addAttribute } from './utils2.js';
import { v as validateInsuranceValues, a as insuranceValues, b as insuranceErrors } from './insurance-state.js';
import { j as text, k as textDanger } from './parts.js';
import { S as StyledHost } from './styled-host.js';
import { H as Header2 } from './header-2.js';
import './justifi-details2.js';
import './event-types.js';
import './justifi-radio-list-item2.js';
import { S as Skeleton } from './skeleton.js';
import { d as defineCustomElement$3 } from './form-control-help-text3.js';
import { d as defineCustomElement$2 } from './form-control-radio2.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$1 = /*@__PURE__*/ proxyCustomElement(class JustifiSeasonInterruptionInsurance extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.__attachShadow();
        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 }))));
    }
}, [257, "justifi-season-interruption-insurance", {
        "authToken": [1, "auth-token"],
        "checkoutId": [1, "checkout-id"],
        "primaryIdentityFirstName": [1, "primary-identity-first-name"],
        "primaryIdentityLastName": [1, "primary-identity-last-name"],
        "primaryIdentityState": [1, "primary-identity-state"],
        "primaryIdentityPostalCode": [1, "primary-identity-postal-code"],
        "primaryIdentityCountry": [1, "primary-identity-country"],
        "primaryIdentityEmailAddress": [1, "primary-identity-email-address"],
        "policyAttributesInsurableAmount": [2, "policy-attributes-insurable-amount"],
        "policyAttributesStartDate": [1, "policy-attributes-start-date"],
        "policyAttributesEndDate": [1, "policy-attributes-end-date"],
        "coveredIdentityFirstName": [1, "covered-identity-first-name"],
        "coveredIdentityLastName": [1, "covered-identity-last-name"],
        "getQuote": [32],
        "toggleCoverage": [32],
        "quote": [32],
        "isLoading": [32],
        "accepted": [32],
        "validate": [64]
    }]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["justifi-season-interruption-insurance", "form-control-help-text", "form-control-radio"];
    components.forEach(tagName => { switch (tagName) {
        case "justifi-season-interruption-insurance":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, JustifiSeasonInterruptionInsurance$1);
            }
            break;
        case "form-control-help-text":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "form-control-radio":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}
defineCustomElement$1();

const JustifiSeasonInterruptionInsurance = JustifiSeasonInterruptionInsurance$1;
const defineCustomElement = defineCustomElement$1;

export { JustifiSeasonInterruptionInsurance, defineCustomElement };
