import { h, proxyCustomElement, HTMLElement, createEvent } from '@stencil/core/internal/client';
import { L as heading4, a2 as heading5, z as buttonPrimary, j as text } from './parts.js';
import { S as StyledHost } from './styled-host.js';
import './justifi-details2.js';
import './event-types.js';
import './justifi-radio-list-item2.js';
import { c as checkPkgVersion } from './check-pkg-version.js';
import { J as JustifiAnalytics } from './Analytics.js';
import { s as TerminalModel, C as ComponentErrorSeverity, t as TerminalOrder, j as TerminalOrderType, a as ComponentErrorCodes } from './Plaid.js';
import { B as BusinessService } from './business.service.js';
import { b as Business } from './Business.js';
import { m as makeGetBusiness } from './get-business.js';
import { S as Skeleton } from './skeleton.js';
import './config-state.js';
import './dinero.js';
import './Pagination.js';
import './ApplePay.js';
import { g as getErrorCode, a as getErrorMessage } from './utils3.js';
import { T as TerminalService } from './terminal.service.js';
import { m as formatPhoneNumber } from './utils2.js';
import { d as defineCustomElement$4 } from './custom-popper2.js';
import { d as defineCustomElement$3 } from './form-control-tooltip2.js';
import { d as defineCustomElement$2 } from './terminal-quantity-selector2.js';

const FormBlock = () => (h("div", { class: "row gap-3" }, h("div", { class: "col-12" }, h(Skeleton, { width: "25%" })), h("div", { class: "col-12" }, h(Skeleton, { width: "100%" })), h("div", { class: "col-12 d-flex gap-3" }, h(Skeleton, { width: "50%" }), h(Skeleton, { width: "50%" })), h("div", { class: "col-12 d-flex gap-3" }, h(Skeleton, { width: "65%" }), h(Skeleton, { width: "35%" }))));
const OrderTerminalsLoading = () => {
    return (h("div", { class: "row gap-5" }, h("div", { class: "col-12" }, h(Skeleton, { width: "40%", height: "40px" })), h(FormBlock, null)));
};

const TerminalSelectorLoading = () => {
    return (h("div", { class: "terminal-selector-skeleton mt-4 rounded shadow-sm" }, h("div", { class: "d-flex align-items-center gap-3" }, h(Skeleton, { width: "125px", height: "125px", styles: { borderRadius: '8px' } }), h("div", { class: "flex-grow-1" }, h("div", { class: "d-flex row flex-row" }, h("div", { class: "col-6 flex-column" }, h(Skeleton, null), h(Skeleton, { width: "60%" })), h("div", { class: "d-flex justify-content-end align-items-center gap-2 col-6" }, h(Skeleton, { width: "32px", height: "32px", styles: { borderRadius: '50%' } }), h(Skeleton, { width: "80px", height: "32px" }), h(Skeleton, { width: "32px", height: "32px", styles: { borderRadius: '50%' } }))), h("div", { class: "mt-4" }, h("div", { class: "d-flex flex-column gap-2" }, h(Skeleton, null), h(Skeleton, null)))))));
};

const makeGetTerminalModels = ({ id, authToken, service }) => async ({ onSuccess, onError }) => {
    var _a, _b, _c, _d;
    try {
        const response = await service.fetchTerminalModels(id, authToken);
        if (!response.error) {
            const terminals = ((_b = (_a = response.data) === null || _a === void 0 ? void 0 : _a.terminal_order_models) === null || _b === void 0 ? void 0 : _b.map((dataItem) => new TerminalModel(dataItem))) || [];
            const orderLimit = (_c = response.data) === null || _c === void 0 ? void 0 : _c.order_limit;
            onSuccess({ terminals, orderLimit });
        }
        else {
            const responseError = getErrorMessage(response.error);
            const code = getErrorCode((_d = response.error) === null || _d === void 0 ? void 0 : _d.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 makeOrderTerminals = ({ authToken, service, apiOrigin = "https://wc-proxy.justifi.ai" }) => async ({ terminalOrder, onSuccess, onError }) => {
    var _a;
    try {
        const response = await service.orderTerminals(authToken, terminalOrder, apiOrigin);
        if (!response.error) {
            const { data } = response;
            onSuccess({ data });
        }
        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 JustifiOrderTerminals$1 = /*@__PURE__*/ proxyCustomElement(class JustifiOrderTerminals extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.__attachShadow();
        this.errorEvent = createEvent(this, "error-event", 7);
        this.submitted = createEvent(this, "submit-event", 7);
        this.shipping = false;
        this.submitButtonText = 'Submit Order';
        this.loading = {
            business: true,
            terminals: true,
        };
        this.submitting = false;
        this.error = null;
        this.totalQuantity = 0;
    }
    componentWillLoad() {
        this.order = new TerminalOrder({
            business_id: this.businessId,
            sub_account_id: this.accountId,
            order_type: this.shipping ? TerminalOrderType.boardingShipping : TerminalOrderType.boardingOnly,
        });
        checkPkgVersion();
        this.analytics = new JustifiAnalytics(this);
        this.loadData();
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    ;
    handleError(errorMessage, code, severity) {
        this.error = { message: errorMessage, code, severity };
        this.errorEvent.emit({ errorCode: code, message: errorMessage, severity });
    }
    loadData() {
        if (!this.businessId || !this.authToken) {
            this.handleError("Invalid business id or auth token", ComponentErrorCodes.MISSING_PROPS, ComponentErrorSeverity.ERROR);
            return;
        }
        this.initializeGetBusiness();
        this.initializeGetTerminalModels();
    }
    initializeGetBusiness() {
        makeGetBusiness({
            id: this.businessId,
            authToken: this.authToken,
            service: new BusinessService()
        })({
            onSuccess: ({ business }) => {
                this.business = new Business(business);
            },
            onError: ({ error, code, severity }) => {
                this.handleError(error, code, severity);
            },
            final: () => {
                this.loading.business = false;
            },
        });
    }
    initializeGetTerminalModels() {
        makeGetTerminalModels({
            id: this.accountId,
            authToken: this.authToken,
            service: new TerminalService()
        })({
            onSuccess: ({ terminals, orderLimit }) => {
                this.terminalModels = terminals;
                this.orderLimit = orderLimit;
                this.loading.terminals = false;
            },
            onError: ({ error, code, severity }) => {
                this.handleError(error, code, severity);
                this.loading.terminals = false;
            }
        });
    }
    submitOrder() {
        const orderTerminals = makeOrderTerminals({
            authToken: this.authToken,
            service: new TerminalService()
        });
        this.submitting = true;
        orderTerminals({
            terminalOrder: this.order.payload,
            onSuccess: ({ data }) => {
                this.submitted.emit(data);
                this.submitting = false;
            },
            onError: ({ error, code, severity }) => {
                this.handleError(error, code, severity);
                this.submitting = false;
            }
        });
    }
    onSelectedQuantityChange(event) {
        this.order.updateTerminal(event.detail.modelName, event.detail.quantity);
        this.totalQuantity = this.order.totalQuantity;
    }
    renderLoading() {
        return (h("div", null, this.loading.business && h(OrderTerminalsLoading, null), this.loading.terminals && (h("div", { class: "mt-5" }, h(TerminalSelectorLoading, null), h(TerminalSelectorLoading, null), h(TerminalSelectorLoading, null)))));
    }
    renderBusinessDetails() {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        if (!this.loading.business && this.business) {
            return (h("div", { class: "d-flex flex-column gap-4 mb-5 pt-5" }, h("div", { class: "row" }, h("div", { class: "col-12" }, h("h2", { part: heading4 }, this.business.legal_name))), h("div", { class: "row" }, h("div", { class: "col-6" }, h("h5", { part: heading5 }, "Representative:"), h("div", null, h("div", null, (_b = (_a = this.business) === null || _a === void 0 ? void 0 : _a.representative) === null || _b === void 0 ? void 0 : _b.name), h("div", null, (_d = (_c = this.business) === null || _c === void 0 ? void 0 : _c.representative) === null || _d === void 0 ? void 0 : _d.title), h("div", null, (_f = (_e = this.business) === null || _e === void 0 ? void 0 : _e.representative) === null || _f === void 0 ? void 0 : _f.email), h("div", null, formatPhoneNumber((_h = (_g = this.business) === null || _g === void 0 ? void 0 : _g.representative) === null || _h === void 0 ? void 0 : _h.phone)))), h("div", { class: "col-6" }, h("h5", { part: heading5 }, this.shipping ? "Shipping Address:" : "Business Address:"), h("div", null, this.business.legal_address.line1, this.business.legal_address.line2 ? `, ${this.business.legal_address.line2}` : "", h("br", null), this.business.legal_address.city, ", ", this.business.legal_address.state, " ", this.business.legal_address.postal_code)))));
        }
    }
    renderTerminals() {
        if (!this.loading.terminals && this.terminalModels) {
            return (h("div", { class: "d-flex flex-column gap-2 mt-5" }, this.terminalModels.map((terminal) => (h("terminal-quantity-selector", { modelName: terminal.model_name, description: terminal.description, imageUrl: terminal.image_url, helpUrl: terminal.help_url, limit: this.orderLimit - this.order.totalQuantity, onSelectedQuantityChange: this.onSelectedQuantityChange.bind(this) })))));
        }
    }
    renderOrderSection() {
        return (h("div", { class: "mt-3" }, h("div", { class: "text-end" }, "Order limit: ", this.orderLimit), h("div", { class: "d-flex justify-content-end mt-3" }, h("button", { class: "btn btn-primary submit-btn", onClick: this.submitOrder.bind(this), disabled: this.order.totalQuantity === 0 || this.submitting, part: buttonPrimary }, this.submitting ? 'Submitting...' : this.submitButtonText))));
    }
    render() {
        return (h(StyledHost, { key: '1fd8c50ac4e22bb2aac46ed0379f4740737e9760' }, h("div", { key: 'caed839c05af25c7bcd6599c45cd5058491a1ba9', part: text }, this.renderLoading(), this.renderBusinessDetails(), this.renderTerminals(), this.renderOrderSection())));
    }
}, [257, "justifi-order-terminals", {
        "businessId": [1, "business-id"],
        "authToken": [1, "auth-token"],
        "accountId": [1, "account-id"],
        "shipping": [4],
        "submitButtonText": [1, "submit-button-text"],
        "loading": [32],
        "submitting": [32],
        "error": [32],
        "business": [32],
        "terminalModels": [32],
        "orderLimit": [32],
        "order": [32],
        "totalQuantity": [32]
    }]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["justifi-order-terminals", "custom-popper", "form-control-tooltip", "terminal-quantity-selector"];
    components.forEach(tagName => { switch (tagName) {
        case "justifi-order-terminals":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, JustifiOrderTerminals$1);
            }
            break;
        case "custom-popper":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "form-control-tooltip":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "terminal-quantity-selector":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}
defineCustomElement$1();

const JustifiOrderTerminals = JustifiOrderTerminals$1;
const defineCustomElement = defineCustomElement$1;

export { JustifiOrderTerminals, defineCustomElement };
