import { proxyCustomElement, HTMLElement, createEvent, h, Host } 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 { B as Button } from './button.js';
import { h as heading2, F as alert } from './parts.js';
import './justifi-details2.js';
import './event-types.js';
import './justifi-radio-list-item2.js';
import { P as PaymentProvisioningLoading } from './payment-provisioning-loading.js';
import { B as BusinessFormStep, a as BusinessFormClickActions } from './event-types2.js';
import { R as Representative } from './Business.js';
import { d as defineCustomElement$b } from './custom-popper2.js';
import { d as defineCustomElement$a } from './form-address-fields2.js';
import { d as defineCustomElement$9 } from './form-control-date2.js';
import { d as defineCustomElement$8 } from './form-control-number2.js';
import { d as defineCustomElement$7 } from './form-control-number-masked2.js';
import { d as defineCustomElement$6 } from './form-control-select2.js';
import { d as defineCustomElement$5 } from './form-control-text2.js';
import { d as defineCustomElement$4 } from './form-control-tooltip2.js';
import { d as defineCustomElement$3 } from './identity-address-form2.js';
import { d as defineCustomElement$2 } from './owner-form2.js';
import { d as defineCustomElement$1 } from './owner-form-inputs2.js';

const BusinessOwnersFormStep = /*@__PURE__*/ proxyCustomElement(class BusinessOwnersFormStep extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.clickEvent = createEvent(this, "click-event", 7);
        this.stepCompleteEvent = createEvent(this, "complete-form-step-event", 7);
        this.errorEvent = createEvent(this, "error-event", 7);
        this.formLoading = createEvent(this, "formLoading", 7);
        this.ownersPayload = [];
        this.refs = [];
        this.isLoading = false;
        this.representativeIsOwner = null;
        this.matchRef = (ref, ownerId) => {
            if (ref === null)
                return;
            const ownerIndex = this.ownersPayload.findIndex(owner => owner.id === ownerId);
            if (ownerIndex !== -1) {
                // Ensure refs array is properly sized before setting ref
                if (this.refs.length !== this.ownersPayload.length) {
                    this.manageRefs();
                }
                this.refs[ownerIndex] = ref;
            }
        };
        this.getData = () => {
            this.formLoading.emit(true);
            this.isLoading = true;
            this.getBusiness({
                onSuccess: (response) => {
                    this.representative = new Representative(response.data.representative || {});
                    if (response.data.owners.length) {
                        this.ownersPayload = response.data.owners.map(owner => ({ id: owner.id }));
                    }
                    else {
                        this.addOwnerForm();
                    }
                },
                onError: ({ error, code, severity }) => {
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity
                    });
                },
                final: () => {
                    this.formLoading.emit(false);
                    this.isLoading = false;
                    this.manageRefs();
                }
            });
        };
        this.sendData = async (onSuccess) => {
            let submittedData;
            this.formLoading.emit(true);
            this.patchBusiness({
                payload: { owners: this.ownersPayload },
                onSuccess: (response) => {
                    submittedData = response;
                    onSuccess();
                },
                onError: ({ error, code, severity }) => {
                    submittedData = error;
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity
                    });
                },
                final: () => {
                    this.stepCompleteEvent.emit({ response: submittedData, formStep: BusinessFormStep.owners });
                    this.formLoading.emit(false);
                }
            });
        };
        this.addOwnerForm = (fireClick) => {
            this.newFormOpen = true;
            this.ownersPayload = [...this.ownersPayload, { id: '' }];
            fireClick && this.clickEvent.emit({ name: BusinessFormClickActions.addOwnerForm });
        };
        this.removeOwnerForm = (id) => {
            this.ownersPayload = this.ownersPayload.filter(owner => owner.id !== id);
            this.newFormOpen && (this.newFormOpen = false);
        };
        this.handleRepresentativeIsOwnerChange = (value) => {
            this.representativeIsOwner = value;
            if (this.representativeIsOwner) {
                this.formLoading.emit(true);
                this.isLoading = true;
                this.ownersPayload = this.ownersPayload.filter(owner => owner.id !== '');
                this.patchBusiness({
                    payload: {
                        representative: { is_owner: true },
                        owners: [{ id: this.representative.id }, ...this.ownersPayload],
                    },
                    onSuccess: () => {
                        this.getData();
                        this.newFormOpen = false;
                    },
                    finally: () => {
                        this.isLoading = false;
                        this.formLoading.emit(false);
                    }
                });
            }
        };
    }
    propChanged() {
        this.initializeApi();
    }
    get showAddOwnerButton() {
        return this.ownersPayload.length < 4 && !this.newFormOpen;
    }
    manageRefs() {
        this.refs = this.ownersPayload.map((owner) => { return owner.id; });
    }
    async validateAndSubmit({ onSuccess }) {
        const formValidations = this.refs.map(ref => ref.validate());
        const formsValid = (await Promise.all(formValidations)).every(result => result);
        if (!formsValid) {
            return;
        }
        if (!this.allowOptionalFields) {
            const percentages = await Promise.all(this.refs.map(ref => ref.getOwnershipPercentage()));
            const total = percentages.reduce((sum, p) => sum + (parseFloat(p) || 0), 0);
            if (total > 100) {
                await Promise.all(this.refs.map(ref => ref.setOwnershipPercentageError('Ownership percentages cannot exceed 100%')));
                return;
            }
        }
        const formSubmissions = this.refs.map(ref => ref.submit());
        const submissionsValid = (await Promise.all(formSubmissions)).every(result => result);
        if (!submissionsValid) {
            return;
        }
        this.sendData(onSuccess);
    }
    componentWillLoad() {
        this.initializeApi();
        if (this.getBusiness) {
            this.getData();
        }
    }
    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,
            });
        }
    }
    ownersWatcher() {
        this.manageRefs();
    }
    handleOwnerSubmit(event) {
        const submittedOwner = event.detail;
        const updatedOwners = this.ownersPayload.map(owner => owner.id === submittedOwner.id ? submittedOwner : owner);
        if (!updatedOwners.includes(submittedOwner)) {
            const newOwnerIndex = this.ownersPayload.findIndex(owner => !owner.id);
            updatedOwners[newOwnerIndex] = submittedOwner;
            this.newFormOpen && (this.newFormOpen = false);
        }
        this.ownersPayload = updatedOwners;
    }
    render() {
        if (this.isLoading) {
            return (h(Host, null, h(PaymentProvisioningLoading, null)));
        }
        const isRepresentativeOwner = this.ownersPayload.some(owner => owner.id === this.representative.id);
        const shouldShowRepresentativeIsOwner = this.representativeIsOwner === null && !isRepresentativeOwner;
        return (h(Host, null, h("div", null, h("div", { class: "d-flex align-items-center gap-2" }, h("legend", { class: "mb-0", part: heading2 }, "Owners"), h("form-control-tooltip", { helpText: "For partnerships, LLCs or privately held corporations, the business is required to apply with all individuals with 25% or more ownership to the application. For charities and registered non-profits, the business is required to apply with 1 individual with substantial control over the entity, such as a board member or director." })), h("hr", { class: "mt-2" }), shouldShowRepresentativeIsOwner && (h("div", { class: `alert alert-warning mb-3`, part: alert }, h("div", { class: "card-body" }, h("div", { class: "d-flex align-items-center mb-3" }, h("strong", null, "Is the representative of this business also an owner?")), h("div", { class: "d-flex gap-2" }, h(Button, { variant: 'primary', onClick: () => this.handleRepresentativeIsOwnerChange(true) }, "Yes"), h(Button, { variant: 'secondary', onClick: () => this.handleRepresentativeIsOwnerChange(false) }, "No"))))), h("div", { class: 'row gy-3' }, this.ownersPayload.map((owner) => {
            return (h("owner-form", { key: owner.id, authToken: this.authToken, businessId: this.businessId, ownerId: owner.id, removeOwner: this.removeOwnerForm, newFormOpen: this.newFormOpen, ownersLength: this.ownersPayload.length, country: this.country, allowOptionalFields: this.allowOptionalFields, ref: (ref) => this.matchRef(ref, owner.id) }));
        })), h("div", { class: 'd-flex justify-content-start' }, h("div", { class: 'gap-2' }, h(Button, { variant: 'primary', onClick: () => this.addOwnerForm(true), hidden: !this.showAddOwnerButton }, "Add Owner"))))));
    }
    static get watchers() { return {
        "authToken": ["propChanged"],
        "businessId": ["propChanged"],
        "ownersPayload": ["ownersWatcher"]
    }; }
}, [256, "business-owners-form-step", {
        "authToken": [1, "auth-token"],
        "businessId": [1, "business-id"],
        "allowOptionalFields": [4, "allow-optional-fields"],
        "country": [1],
        "getBusiness": [32],
        "patchBusiness": [32],
        "ownersPayload": [32],
        "refs": [32],
        "newFormOpen": [32],
        "isLoading": [32],
        "representativeIsOwner": [32],
        "representative": [32],
        "validateAndSubmit": [64]
    }, [[0, "ownerSubmitted", "handleOwnerSubmit"]], {
        "authToken": ["propChanged"],
        "businessId": ["propChanged"],
        "ownersPayload": ["ownersWatcher"]
    }]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["business-owners-form-step", "custom-popper", "form-address-fields", "form-control-date", "form-control-number", "form-control-number-masked", "form-control-select", "form-control-text", "form-control-tooltip", "identity-address-form", "owner-form", "owner-form-inputs"];
    components.forEach(tagName => { switch (tagName) {
        case "business-owners-form-step":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, BusinessOwnersFormStep);
            }
            break;
        case "custom-popper":
            if (!customElements.get(tagName)) {
                defineCustomElement$b();
            }
            break;
        case "form-address-fields":
            if (!customElements.get(tagName)) {
                defineCustomElement$a();
            }
            break;
        case "form-control-date":
            if (!customElements.get(tagName)) {
                defineCustomElement$9();
            }
            break;
        case "form-control-number":
            if (!customElements.get(tagName)) {
                defineCustomElement$8();
            }
            break;
        case "form-control-number-masked":
            if (!customElements.get(tagName)) {
                defineCustomElement$7();
            }
            break;
        case "form-control-select":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "form-control-text":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "form-control-tooltip":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "identity-address-form":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "owner-form":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
        case "owner-form-inputs":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}
defineCustomElement();

export { BusinessOwnersFormStep as B, defineCustomElement as d };
