'use strict';

var index = require('./index-p7cvUYAE.js');
var checkoutActions = require('./checkout-actions-D1untOUp.js');
var checkout_service = require('./checkout.service-Bc6RAR8j.js');
var Plaid = require('./Plaid-CPESyiiV.js');
var Analytics = require('./Analytics-C6KBHEIP.js');
var checkPkgVersion = require('./check-pkg-version-B9EoYyZR.js');
require('./utils-BsnepLy6.js');
require('./Api-D9vOcUw4.js');
require('./config-state-BIgGhhe9.js');
require('./index-W-zoNiyM.js');
require('./utils-CYONRFR6.js');
require('./dinero-BwNN_k7x.js');
require('./Pagination-Dediz133.js');
require('./Business-oBifyXkW.js');
require('./package-YyJzVqrh.js');

const JustifiQrTerminal = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.checkoutCompleted = index.createEvent(this, "checkout-completed", 7);
        this.checkoutExpired = index.createEvent(this, "checkout-expired", 7);
        this.errorEvent = index.createEvent(this, "error-event", 7);
        this.pollIntervalMs = 3000;
        this.pollTimeoutMs = 600000;
        this.terminalState = 'loading';
        this.paymentStatus = '';
        this.errorMessage = '';
        this.pollIntervalHandle = null;
        this.pollTimeoutHandle = null;
        this.failedDismissHandle = null;
        this.seenCompletionCreatedAts = new Set();
        this.inFlight = false;
    }
    componentWillLoad() {
        checkPkgVersion.checkPkgVersion();
        this.analytics = new Analytics.JustifiAnalytics(this);
        this.initialize();
    }
    disconnectedCallback() {
        var _a;
        this.stopAll();
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    propChanged() {
        this.stopAll();
        this.initialize();
    }
    suppressInnerErrors(event) {
        // Suppress error-event bubbling from inner justifi-checkout-qr-code
        event.stopPropagation();
    }
    get effectivePollInterval() {
        return Math.max(1000, this.pollIntervalMs);
    }
    initialize() {
        if (!this.authToken || !this.checkoutId) {
            this.errorEvent.emit({
                message: 'authToken and checkoutId are required',
                errorCode: Plaid.ComponentErrorCodes.MISSING_PROPS,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
            return;
        }
        this.terminalState = 'loading';
        this.getCheckout = checkoutActions.makeGetCheckout({
            authToken: this.authToken,
            checkoutId: this.checkoutId,
            service: new checkout_service.CheckoutService(),
        });
        this.getCheckout({
            onSuccess: ({ checkout }) => this.handleInitialLoad(checkout),
            onError: ({ error, code, severity }) => {
                this.terminalState = 'error';
                this.errorMessage = error;
                this.errorEvent.emit({ message: error, errorCode: code, severity });
            },
        });
    }
    handleInitialLoad(checkout) {
        var _a;
        switch (checkout.status) {
            case Plaid.ICheckoutStatus.expired:
                this.terminalState = 'expired';
                this.checkoutExpired.emit({ checkoutId: this.checkoutId });
                this.errorEvent.emit({
                    message: Plaid.ComponentErrorMessages.CHECKOUT_EXPIRED,
                    errorCode: Plaid.ComponentErrorCodes.CHECKOUT_EXPIRED,
                    severity: Plaid.ComponentErrorSeverity.ERROR,
                });
                break;
            case Plaid.ICheckoutStatus.completed:
                this.terminalState = 'completed';
                this.paymentStatus = this.resolvePaymentStatus(checkout);
                this.checkoutCompleted.emit({ checkoutId: this.checkoutId, paymentStatus: this.paymentStatus });
                break;
            default:
                ((_a = checkout.completions) !== null && _a !== void 0 ? _a : []).forEach((c) => this.seenCompletionCreatedAts.add(c.created_at));
                this.terminalState = 'ready';
                this.startPolling();
                break;
        }
    }
    startPolling() {
        this.pollTimeoutHandle = setTimeout(() => {
            this.stopAll();
            this.terminalState = 'error';
            this.errorMessage = 'Checkout polling timed out';
            this.errorEvent.emit({
                message: 'Checkout polling timed out',
                errorCode: Plaid.ComponentErrorCodes.FETCH_ERROR,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }, this.pollTimeoutMs);
        this.pollIntervalHandle = setInterval(() => this.tick(), this.effectivePollInterval);
    }
    tick() {
        if (this.inFlight)
            return;
        this.inFlight = true;
        this.getCheckout({
            onSuccess: ({ checkout }) => {
                this.inFlight = false;
                this.handlePollResult(checkout);
            },
            onError: ({ error, code, severity }) => {
                this.inFlight = false;
                this.stopAll();
                this.terminalState = 'error';
                this.errorMessage = error;
                this.errorEvent.emit({ message: error, errorCode: code, severity });
            },
        });
    }
    handlePollResult(checkout) {
        var _a;
        const completions = (_a = checkout.completions) !== null && _a !== void 0 ? _a : [];
        const newFailures = completions.filter((c) => !this.seenCompletionCreatedAts.has(c.created_at) && c.payment_status === 'failed');
        newFailures.forEach((c) => this.seenCompletionCreatedAts.add(c.created_at));
        if (newFailures.length > 0) {
            this.terminalState = 'payment-failed';
            if (this.failedDismissHandle)
                clearTimeout(this.failedDismissHandle);
            this.failedDismissHandle = setTimeout(() => {
                if (this.terminalState === 'payment-failed')
                    this.terminalState = 'ready';
            }, 3000);
        }
        if (checkout.status === Plaid.ICheckoutStatus.completed) {
            this.stopAll();
            this.terminalState = 'completed';
            this.paymentStatus = this.resolvePaymentStatus(checkout);
            this.checkoutCompleted.emit({ checkoutId: this.checkoutId, paymentStatus: this.paymentStatus });
            return;
        }
        if (checkout.status === Plaid.ICheckoutStatus.expired) {
            this.stopAll();
            this.terminalState = 'expired';
            this.checkoutExpired.emit({ checkoutId: this.checkoutId });
            this.errorEvent.emit({
                message: Plaid.ComponentErrorMessages.CHECKOUT_EXPIRED,
                errorCode: Plaid.ComponentErrorCodes.CHECKOUT_EXPIRED,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    resolvePaymentStatus(checkout) {
        var _a, _b;
        const completions = (_a = checkout.completions) !== null && _a !== void 0 ? _a : [];
        const sorted = [...completions].sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime());
        const latestStatus = (_b = sorted[0]) === null || _b === void 0 ? void 0 : _b.payment_status;
        if (latestStatus === Plaid.CompletionStatuses.succeeded)
            return 'succeeded';
        if (latestStatus == null) {
            return checkout.successful_payment_id ? 'succeeded' : 'pending';
        }
        return 'pending';
    }
    stopAll() {
        if (this.pollIntervalHandle) {
            clearInterval(this.pollIntervalHandle);
            this.pollIntervalHandle = null;
        }
        if (this.pollTimeoutHandle) {
            clearTimeout(this.pollTimeoutHandle);
            this.pollTimeoutHandle = null;
        }
        if (this.failedDismissHandle) {
            clearTimeout(this.failedDismissHandle);
            this.failedDismissHandle = null;
        }
        this.inFlight = false;
    }
    render() {
        if (!this.authToken || !this.checkoutId)
            return null;
        return (index.h("div", null, this.terminalState === 'loading' && null, (this.terminalState === 'ready' || this.terminalState === 'payment-failed') && (index.h("div", null, index.h("justifi-checkout-qr-code", { checkoutId: this.checkoutId }), this.terminalState === 'payment-failed' && (index.h("p", null, "Payment failed. Please try again.")), this.terminalState === 'ready' && (index.h("p", null, "Scan to pay")))), this.terminalState === 'completed' && (index.h("div", null, this.paymentStatus === 'succeeded'
            ? index.h("p", null, "Payment received")
            : index.h("p", null, "Payment pending"))), this.terminalState === 'expired' && (index.h("p", null, "Checkout expired. Please create a new checkout.")), this.terminalState === 'error' && (index.h("p", null, this.errorMessage))));
    }
    static get watchers() { return {
        "authToken": ["propChanged"],
        "checkoutId": ["propChanged"]
    }; }
};

exports.justifi_qr_terminal = JustifiQrTerminal;
