import { proxyCustomElement, HTMLElement, createEvent, h } from '@stencil/core/internal/client';
import { C as ComponentErrorSeverity, a as ComponentErrorCodes } from './Plaid.js';
import { m as makeGetBusiness, a as makePatchBusiness } from './payment-provisioning-actions.js';
import { B as BusinessService } from './business.service.js';
import { C as CoreBusinessInfo, a as CountryCode } from './Business.js';
import { b as businessCoreInfoSchemaCAN, a as businessCoreInfoSchemaUSA } from './business-core-info-schema.js';
import { F as FormController } from './form.js';
import { c as businessClassificationOptions } from './business-form-options.js';
import { B as BusinessFormStep } from './event-types2.js';
import { P as PHONE_MASKS } from './form-input-masks.js';
import { h as heading2, l as label, c as inputDisabled, A as buttonSecondary } from './parts.js';
import { P as PaymentProvisioningLoading } from './payment-provisioning-loading.js';
import { c as countryLabels } from './country-config.js';
import { d as defineCustomElement$6 } from './custom-popper2.js';
import { d as defineCustomElement$5 } from './form-control-date2.js';
import { d as defineCustomElement$4 } from './form-control-number-masked2.js';
import { d as defineCustomElement$3 } from './form-control-select2.js';
import { d as defineCustomElement$2 } from './form-control-text2.js';
import { d as defineCustomElement$1 } from './form-control-tooltip2.js';

const BusinessCoreInfoFormStep = /*@__PURE__*/ proxyCustomElement(class BusinessCoreInfoFormStep extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.errorEvent = createEvent(this, "error-event", 7);
        this.stepCompleteEvent = createEvent(this, "complete-form-step-event", 7);
        this.formLoading = createEvent(this, "formLoading", 7);
        this.errors = {};
        this.coreInfo = {};
        this.isLoading = false;
        this.isEditingTaxId = false;
        this.getData = () => {
            if (!this.getBusiness)
                return;
            this.formLoading.emit(true);
            this.isLoading = true;
            this.getBusiness({
                onSuccess: (response) => {
                    this.coreInfo = new CoreBusinessInfo(response.data);
                    this.formController.setInitialValues(Object.assign({}, this.coreInfo));
                },
                onError: ({ error, code, severity }) => {
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity
                    });
                },
                final: () => {
                    this.formLoading.emit(false);
                    this.isLoading = false;
                }
            });
        };
        this.sendData = (onSuccess) => {
            let submittedData;
            this.formLoading.emit(true);
            this.patchBusiness({
                payload: this.patchPayload,
                onSuccess: (response) => {
                    submittedData = response;
                    onSuccess();
                    // after successful patch, revert back to read-only for tax id
                    this.isEditingTaxId = false;
                },
                onError: ({ error, code, severity, rawError }) => {
                    submittedData = error;
                    // Set field-specific error if param exists
                    if (rawError && typeof rawError === 'object' && rawError.param) {
                        this.formController.setFieldError(rawError.param, rawError.message);
                    }
                    // Still emit component-level error
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity
                    });
                },
                final: () => {
                    this.stepCompleteEvent.emit({ response: submittedData, formStep: BusinessFormStep.businessInfo });
                    this.formLoading.emit(false);
                }
            });
        };
        this.inputHandler = (name, value) => {
            // Clear backend error when user edits field
            if (this.errors[name]) {
                this.formController.clearFieldError(name);
            }
            this.formController.setValues(Object.assign(Object.assign({}, this.formController.values.getValue()), { [name]: value }));
        };
    }
    propChanged() {
        this.initializeApi();
    }
    async validateAndSubmit({ onSuccess }) {
        this.formController.validateAndSubmit(() => this.sendData(onSuccess));
    }
    get patchPayload() {
        const formValues = new CoreBusinessInfo(this.formController.values.getValue()).payload;
        return formValues;
    }
    componentWillLoad() {
        this.initializeApi();
        const schema = (this.country === CountryCode.CAN)
            ? businessCoreInfoSchemaCAN(this.allowOptionalFields)
            : businessCoreInfoSchemaUSA(this.allowOptionalFields);
        this.formController = new FormController(schema);
        this.getData();
    }
    componentDidLoad() {
        this.formController.errors.subscribe(errors => {
            this.errors = Object.assign({}, errors);
        });
    }
    initializeApi() {
        if (this.authToken && this.businessId) {
            this.getBusiness = makeGetBusiness({
                authToken: this.authToken,
                businessId: this.businessId,
                service: new BusinessService()
            });
            this.patchBusiness = makePatchBusiness({
                authToken: this.authToken,
                businessId: this.businessId,
                service: new BusinessService()
            });
        }
        else {
            this.errorEvent.emit({
                message: 'Missing required props',
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    render() {
        var _a, _b;
        const coreInfoDefaultValue = this.formController.getInitialValues();
        if (this.isLoading) {
            return h(PaymentProvisioningLoading, null);
        }
        return (h("form", null, h("fieldset", null, h("div", { class: "d-flex align-items-center gap-2" }, h("legend", { class: "mb-0", part: heading2 }, "Business Information")), h("hr", { class: "mt-2" }), h("div", { class: "row gy-3" }, h("div", { class: "col-12 col-md-6" }, h("form-control-text", { name: "legal_name", label: "Business Name", defaultValue: coreInfoDefaultValue.legal_name, errorText: this.errors.legal_name, inputHandler: this.inputHandler, helpText: "Enter this exactly as it appears on your tax records (don't use acronyms or abbreviations unless you registered that way)." })), h("div", { class: "col-12 col-md-6" }, h("form-control-text", { name: "doing_business_as", label: "Doing Business As (DBA)", defaultValue: coreInfoDefaultValue.doing_business_as, errorText: this.errors.doing_business_as, inputHandler: this.inputHandler, helpText: "Enter this exactly as it appears on your tax records (leave blank if you don't have a registered DBA/trade name)" })), h("div", { class: "col-12 col-md-8" }, h("form-control-select", { name: "classification", label: "Business Classification", options: businessClassificationOptions, defaultValue: coreInfoDefaultValue.classification, errorText: this.errors.classification, inputHandler: this.inputHandler })), h("div", { class: "col-12 col-md-4" }, h("form-control-date", { name: "date_of_incorporation", label: "Date of Registration", defaultValue: coreInfoDefaultValue.date_of_incorporation, errorText: this.errors.date_of_incorporation, inputHandler: this.inputHandler })), h("div", { class: "col-12 col-md-6" }, h("form-control-text", { name: "industry", label: "Industry", defaultValue: coreInfoDefaultValue.industry, errorText: this.errors.industry, inputHandler: this.inputHandler, helpText: "Describe what you sell" })), h("div", { class: "col-12 col-md-6" }, (!((_a = this.coreInfo) === null || _a === void 0 ? void 0 : _a.tax_id_last4) || this.isEditingTaxId) ? (h("form-control-number-masked", { name: "tax_id", label: countryLabels[this.country].taxIdLabelOptional || countryLabels[this.country].taxIdLabel, defaultValue: this.isEditingTaxId ? '' : coreInfoDefaultValue.tax_id, errorText: this.errors.tax_id, inputHandler: this.inputHandler, mask: '000000000', helpText: countryLabels[this.country].taxIdHelpText })) : (h("div", null, h("label", { class: "form-label", part: label }, countryLabels[this.country].taxIdLabel), h("div", { class: "input-group mb-3" }, h("input", { type: "text", class: "form-control", part: inputDisabled, value: `****${(_b = this.coreInfo) === null || _b === void 0 ? void 0 : _b.tax_id_last4}`, disabled: true }), h("button", { class: "btn btn-secondary", type: "button", part: buttonSecondary, onClick: () => {
                this.isEditingTaxId = true;
                // Clear last4-equivalent and current value if any future conditional validation depends on it
                this.formController.setValues(Object.assign(Object.assign({}, this.formController.values.getValue()), { tax_id: '', tax_id_last4: null }));
            } }, "Change"))))), h("div", { class: "col-12" }, h("form-control-text", { name: "website_url", label: "Business Website URL", defaultValue: coreInfoDefaultValue.website_url, errorText: this.errors.website_url, inputHandler: this.inputHandler, helpText: "Don't have a live website? You can use your social media business page, app store link, or staging site URL." })), h("div", { class: "col-12 col-md-6" }, h("form-control-text", { name: "email", label: "Business Email Address", defaultValue: coreInfoDefaultValue.email, errorText: this.errors.email, inputHandler: this.inputHandler })), h("div", { class: "col-12 col-md-6" }, h("form-control-number-masked", { name: "phone", label: "Business Phone Number", defaultValue: coreInfoDefaultValue.phone, errorText: this.errors.phone, inputHandler: this.inputHandler, mask: PHONE_MASKS.US }))))));
    }
    static get watchers() { return {
        "authToken": ["propChanged"],
        "businessId": ["propChanged"]
    }; }
}, [256, "business-core-info-form-step", {
        "authToken": [1, "auth-token"],
        "businessId": [1, "business-id"],
        "allowOptionalFields": [4, "allow-optional-fields"],
        "country": [1],
        "getBusiness": [32],
        "patchBusiness": [32],
        "formController": [32],
        "errors": [32],
        "coreInfo": [32],
        "isLoading": [32],
        "isEditingTaxId": [32],
        "validateAndSubmit": [64]
    }, undefined, {
        "authToken": ["propChanged"],
        "businessId": ["propChanged"]
    }]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["business-core-info-form-step", "custom-popper", "form-control-date", "form-control-number-masked", "form-control-select", "form-control-text", "form-control-tooltip"];
    components.forEach(tagName => { switch (tagName) {
        case "business-core-info-form-step":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, BusinessCoreInfoFormStep);
            }
            break;
        case "custom-popper":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "form-control-date":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "form-control-number-masked":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "form-control-select":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "form-control-text":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
        case "form-control-tooltip":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}
defineCustomElement();

export { BusinessCoreInfoFormStep as B, defineCustomElement as d };
