'use strict';

var index = require('./index-p7cvUYAE.js');
var parts = require('./parts-BXshb_S-.js');
var styledHost = require('./styled-host-Ch0-dxF-.js');
require('./event-types-YOY5TKUN.js');
var checkPkgVersion = require('./check-pkg-version-B9EoYyZR.js');
var Analytics = require('./Analytics-C6KBHEIP.js');
var Plaid = require('./Plaid-CPESyiiV.js');
var business_service = require('./business.service-BIHpEqmf.js');
var Business = require('./Business-oBifyXkW.js');
var getBusiness = require('./get-business-DaaeRffw.js');
var skeleton = require('./skeleton-DvRCiQlA.js');
require('./config-state-BIgGhhe9.js');
require('./dinero-BwNN_k7x.js');
require('./Pagination-Dediz133.js');
var utils = require('./utils-BsnepLy6.js');
var terminal_service = require('./terminal.service-9hEtgijd.js');
var utils$1 = require('./utils-CYONRFR6.js');
require('./package-YyJzVqrh.js');
require('./Api-D9vOcUw4.js');
require('./index-W-zoNiyM.js');

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

const TerminalSelectorLoading = () => {
    return (index.h("div", { class: "terminal-selector-skeleton mt-4 rounded shadow-sm" }, index.h("div", { class: "d-flex align-items-center gap-3" }, index.h(skeleton.Skeleton, { width: "125px", height: "125px", styles: { borderRadius: '8px' } }), index.h("div", { class: "flex-grow-1" }, index.h("div", { class: "d-flex row flex-row" }, index.h("div", { class: "col-6 flex-column" }, index.h(skeleton.Skeleton, null), index.h(skeleton.Skeleton, { width: "60%" })), index.h("div", { class: "d-flex justify-content-end align-items-center gap-2 col-6" }, index.h(skeleton.Skeleton, { width: "32px", height: "32px", styles: { borderRadius: '50%' } }), index.h(skeleton.Skeleton, { width: "80px", height: "32px" }), index.h(skeleton.Skeleton, { width: "32px", height: "32px", styles: { borderRadius: '50%' } }))), index.h("div", { class: "mt-4" }, index.h("div", { class: "d-flex flex-column gap-2" }, index.h(skeleton.Skeleton, null), index.h(skeleton.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 Plaid.TerminalModel(dataItem))) || [];
            const orderLimit = (_c = response.data) === null || _c === void 0 ? void 0 : _c.order_limit;
            onSuccess({ terminals, orderLimit });
        }
        else {
            const responseError = utils.getErrorMessage(response.error);
            const code = utils.getErrorCode((_d = response.error) === null || _d === void 0 ? void 0 : _d.code);
            return onError({
                error: responseError,
                code,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = utils.getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: Plaid.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 = utils.getErrorMessage(response.error);
            const code = utils.getErrorCode((_a = response.error) === null || _a === void 0 ? void 0 : _a.code);
            return onError({
                error: responseError,
                code,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = utils.getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: Plaid.ComponentErrorSeverity.ERROR,
        });
    }
};

const JustifiOrderTerminals = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.errorEvent = index.createEvent(this, "error-event", 7);
        this.submitted = index.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 Plaid.TerminalOrder({
            business_id: this.businessId,
            sub_account_id: this.accountId,
            order_type: this.shipping ? Plaid.TerminalOrderType.boardingShipping : Plaid.TerminalOrderType.boardingOnly,
        });
        checkPkgVersion.checkPkgVersion();
        this.analytics = new Analytics.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", Plaid.ComponentErrorCodes.MISSING_PROPS, Plaid.ComponentErrorSeverity.ERROR);
            return;
        }
        this.initializeGetBusiness();
        this.initializeGetTerminalModels();
    }
    initializeGetBusiness() {
        getBusiness.makeGetBusiness({
            id: this.businessId,
            authToken: this.authToken,
            service: new business_service.BusinessService()
        })({
            onSuccess: ({ business }) => {
                this.business = new Business.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 terminal_service.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 terminal_service.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 (index.h("div", null, this.loading.business && index.h(OrderTerminalsLoading, null), this.loading.terminals && (index.h("div", { class: "mt-5" }, index.h(TerminalSelectorLoading, null), index.h(TerminalSelectorLoading, null), index.h(TerminalSelectorLoading, null)))));
    }
    renderBusinessDetails() {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        if (!this.loading.business && this.business) {
            return (index.h("div", { class: "d-flex flex-column gap-4 mb-5 pt-5" }, index.h("div", { class: "row" }, index.h("div", { class: "col-12" }, index.h("h2", { part: parts.heading4 }, this.business.legal_name))), index.h("div", { class: "row" }, index.h("div", { class: "col-6" }, index.h("h5", { part: parts.heading5 }, "Representative:"), index.h("div", null, index.h("div", null, (_b = (_a = this.business) === null || _a === void 0 ? void 0 : _a.representative) === null || _b === void 0 ? void 0 : _b.name), index.h("div", null, (_d = (_c = this.business) === null || _c === void 0 ? void 0 : _c.representative) === null || _d === void 0 ? void 0 : _d.title), index.h("div", null, (_f = (_e = this.business) === null || _e === void 0 ? void 0 : _e.representative) === null || _f === void 0 ? void 0 : _f.email), index.h("div", null, utils$1.formatPhoneNumber((_h = (_g = this.business) === null || _g === void 0 ? void 0 : _g.representative) === null || _h === void 0 ? void 0 : _h.phone)))), index.h("div", { class: "col-6" }, index.h("h5", { part: parts.heading5 }, this.shipping ? "Shipping Address:" : "Business Address:"), index.h("div", null, this.business.legal_address.line1, this.business.legal_address.line2 ? `, ${this.business.legal_address.line2}` : "", index.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 (index.h("div", { class: "d-flex flex-column gap-2 mt-5" }, this.terminalModels.map((terminal) => (index.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 (index.h("div", { class: "mt-3" }, index.h("div", { class: "text-end" }, "Order limit: ", this.orderLimit), index.h("div", { class: "d-flex justify-content-end mt-3" }, index.h("button", { class: "btn btn-primary submit-btn", onClick: this.submitOrder.bind(this), disabled: this.order.totalQuantity === 0 || this.submitting, part: parts.buttonPrimary }, this.submitting ? 'Submitting...' : this.submitButtonText))));
    }
    render() {
        return (index.h(styledHost.StyledHost, { key: '1fd8c50ac4e22bb2aac46ed0379f4740737e9760' }, index.h("div", { key: 'caed839c05af25c7bcd6599c45cd5058491a1ba9', part: parts.text }, this.renderLoading(), this.renderBusinessDetails(), this.renderTerminals(), this.renderOrderSection())));
    }
};

exports.justifi_order_terminals = JustifiOrderTerminals;
