import { proxyCustomElement, HTMLElement, createEvent, h } from '@stencil/core/internal/client';
import { c as create$3, b as create$7, F as FormController } from './form.js';
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 { h as heading2 } from './parts.js';
import { B as BusinessFormStep } from './event-types2.js';
import { d as defineCustomElement$1 } from './form-control-checkbox2.js';

const businessTermsConditionsSchema = (allowOptionalFields) => {
    const schema = create$3({
        accepted: create$7()
            .oneOf([true], 'You must agree to the terms and conditions to continue')
            .required('You must agree to the terms and conditions to continue')
    });
    const easySchema = create$3({
        accepted: create$7().nullable()
    });
    return allowOptionalFields ? easySchema : schema;
};

const BusinessTermsConditionsFormStep = /*@__PURE__*/ proxyCustomElement(class BusinessTermsConditionsFormStep extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.stepCompleteEvent = createEvent(this, "complete-form-step-event", 7);
        this.errorEvent = createEvent(this, "error-event", 7);
        this.formLoading = createEvent(this, "formLoading", 7);
        this.formCompleted = createEvent(this, "formCompleted", 7);
        this.errors = {};
        this.fetchData = async () => {
            this.formLoading.emit(true);
            try {
                const response = await this.api.get({ endpoint: this.businessEndpoint, authToken: this.authToken });
                this.acceptedTermsBefore = response.data.terms_conditions_accepted;
            }
            catch (error) {
                this.errorEvent.emit({
                    errorCode: ComponentErrorCodes.FETCH_ERROR,
                    message: error.message,
                    severity: ComponentErrorSeverity.ERROR,
                    data: error,
                });
            }
            finally {
                this.formLoading.emit(false);
            }
        };
        this.sendData = async (onSuccess) => {
            this.formLoading.emit(true);
            try {
                const payload = this.termsPayload;
                const response = await this.api.post({ endpoint: this.termsConditionsEndpoint, body: payload, authToken: this.authToken });
                this.handleResponse(response, onSuccess);
            }
            catch (error) {
                this.errorEvent.emit({
                    errorCode: ComponentErrorCodes.POST_ERROR,
                    message: error.message,
                    severity: ComponentErrorSeverity.ERROR,
                    data: error,
                });
            }
            finally {
                this.formLoading.emit(false);
            }
        };
        this.inputHandler = (name, value) => {
            this.acceptedTerms = value;
            this.formController.setValues(Object.assign(Object.assign({}, this.formController.values.getValue()), { [name]: value }));
        };
    }
    get businessEndpoint() {
        return `entities/business/${this.businessId}`;
    }
    get termsConditionsEndpoint() {
        return 'entities/terms_and_conditions';
    }
    get formHelperText() {
        return this.acceptedTermsBefore ? 'You have already accepted the terms and conditions.' : null;
    }
    get termsPayload() {
        return {
            business_id: this.businessId,
            accepted: this.formController.values.getValue().accepted,
            user_agent: window.navigator.userAgent
        };
    }
    async componentWillLoad() {
        this.api = Api();
        this.formController = new FormController(businessTermsConditionsSchema(this.allowOptionalFields));
        if (this.businessId && this.authToken) {
            this.fetchData();
        }
    }
    handleResponse(response, onSuccess) {
        if (response.error) {
            this.errorEvent.emit({
                errorCode: ComponentErrorCodes.POST_ERROR,
                message: response.error.message,
                severity: ComponentErrorSeverity.ERROR,
                data: response.error,
            });
        }
        else {
            onSuccess();
        }
        this.stepCompleteEvent.emit({ response: response, formStep: BusinessFormStep.termsAndConditions });
        this.formCompleted.emit();
    }
    async validateAndSubmit({ onSuccess }) {
        if (this.acceptedTermsBefore) {
            this.stepCompleteEvent.emit({ response: null, formStep: BusinessFormStep.termsAndConditions, metadata: 'no data submitted' });
            this.formCompleted.emit();
            onSuccess();
        }
        else {
            this.formController.validateAndSubmit(() => this.sendData(onSuccess));
        }
    }
    ;
    componentDidLoad() {
        this.formController.errors.subscribe(errors => {
            this.errors = Object.assign({}, errors);
        });
    }
    get merchantAgreementLink() {
        return (h("a", { href: "https://justifi.tech/merchant-agreement/", target: "_blank", rel: "noopener noreferrer" }, "merchant agreement"));
    }
    render() {
        return (h("form", { key: '24b0a8ff0187894cf5e0f56e9e4b28c378e720cb' }, h("fieldset", { key: '26fa9159dd6d61edd28b9443a10eeb981f150308' }, h("legend", { key: '103bdecbc51f2cccd9105e2f9b271b60760618ec', part: heading2 }, "Terms and Conditions"), h("hr", { key: 'dfd29fbe609a57d8160df7980ed0e63e75934a86' }), h("div", { key: '61e06597ec652c1d7c6e7e2bd8c9b653d061d076' }, h("p", { key: 'cd4def71580cd14d6edb5887221ebf6aa80cc2ea' }, "Please read and accept the ", this.merchantAgreementLink, " to submit your provisioning request.")), h("br", { key: 'e3c64733f11a4f702e686e6c5ae7acd7e6bd1c34' }), h("div", { key: '71bd74de3aee69805a2aa1297356ff8b8db3c76c', class: "row-gy-3" }, h("div", { key: '94a28c13e3bbc1c89cd1b5ebde2e1732b48f99ea', class: "col-12" }, h("form-control-checkbox", { key: 'fee95fa42192fee1bbfd544307b4e1c11c0d97f4', name: "accepted", label: "I agree to the terms and conditions", inputHandler: this.inputHandler, errorText: this.errors.accepted, disabled: this.acceptedTermsBefore, helpText: this.formHelperText, checked: this.acceptedTerms }))))));
    }
}, [256, "business-terms-conditions-form-step", {
        "authToken": [1, "auth-token"],
        "businessId": [1, "business-id"],
        "allowOptionalFields": [4, "allow-optional-fields"],
        "formController": [32],
        "errors": [32],
        "acceptedTermsBefore": [32],
        "acceptedTerms": [32],
        "validateAndSubmit": [64]
    }]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["business-terms-conditions-form-step", "form-control-checkbox"];
    components.forEach(tagName => { switch (tagName) {
        case "business-terms-conditions-form-step":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, BusinessTermsConditionsFormStep);
            }
            break;
        case "form-control-checkbox":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}
defineCustomElement();

export { BusinessTermsConditionsFormStep as B, defineCustomElement as d };
