import { proxyCustomElement, HTMLElement, createEvent, h } from '@stencil/core/internal/client';
import { c as checkoutStore, o as onChange } from './checkout.store.js';
import { S as StyledHost } from './styled-host.js';
import './justifi-details2.js';
import './event-types.js';
import './justifi-radio-list-item2.js';
import { P as PlaidService } from './plaid.service.js';
import { P as PLAID_ERROR_SEVERITY, b as PLAID_ERROR_MESSAGES, c as PlaidErrorCodes, C as ComponentErrorSeverity } from './Plaid.js';
import { P as PAYMENT_METHODS } from './ModularCheckout.js';

const plaidIconSvg = 'data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjQ4IiB2aWV3Qm94PSIwIDAgMjggMjkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgY2xhc3M9ImNzcy0xcmRhajhtIj48ZyBmaWxsPSIjMTExIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxwYXRoIGQ9Ik0yNS43NjI5IDI2LjI2MjhMMjggMTcuNTMwOUwyNC45NjkxIDE0LjUwMDFMMjcuOTk5OSAxMS40NjkxTDI1Ljc2MjggMi43MzcwNkwxNy4wMzA5IDAuNUwxNC4wMDAxIDMuNTMxTDEwLjk2OSAwLjUwMDE0TDIuMjM3MDYgMi43MzczNEwwIDExLjQ2OTFMMy4wMzEyOCAxNC40OTk5TDAuMDAwMTQgMTcuNTMxTDIuMjM3MiAyNi4yNjI5TDEwLjk2OTEgMjguNUwxNC4wMDAxIDI1LjQ2OUwxNy4wMzEgMjguNDk5OUwyNS43NjI5IDI2LjI2MjhaTTE1LjczMjEgMjMuNzM3MUwxOC42MTg2IDIwLjg1MDVMMjIuMjkxMiAyNC41MjMzTDE3LjY5NTYgMjUuNzAwN0wxNS43MzIxIDIzLjczNzFaTTExLjExMzYgOS44ODE1NEwxNC4wMDAzIDYuOTk1MDJMMTYuODg2OCA5Ljg4MTRMMTQuMDAwMSAxMi43Njc5TDExLjExMzYgOS44ODE1NFpNMTIuMjY4MiAxNC41TDkuMzgxNTQgMTcuMzg2NUw2LjQ5NTAyIDE0LjVMOS4zODE1NCAxMS42MTM1TDEyLjI2ODIgMTQuNVpNMTguNjE4NyAxMS42MTMzTDIxLjUwNTMgMTQuNUwxOC42MTg2IDE3LjM4NjVMMTUuNzMyMSAxNC41TDE4LjYxODcgMTEuNjEzM1pNMTYuODg2NyAxOS4xMTg2TDE0LjAwMDEgMjIuMDA1MUwxMS4xMTM1IDE5LjExODVMMTQuMDAwMSAxNi4yMzE5TDE2Ljg4NjcgMTkuMTE4NlpNMTAuMzA0NCAyNS43MDA3TDUuNzA4NjQgMjQuNTIzM0w5LjM4MTU0IDIwLjg1MDRMMTIuMjY4MiAyMy43MzcxTDEwLjMwNDQgMjUuNzAwN1pNNC43NjMwOCAxNi4yMzE5TDcuNjQ5NiAxOS4xMTg1TDMuOTc2NyAyMi43OTE0TDIuNzk5MyAxOC4xOTU3TDQuNzYzMDggMTYuMjMxOVpNMy45NzY3IDYuMjA4MzZMNy42NDk3NCA5Ljg4MTRMNC43NjMwOCAxMi43NjgxTDIuNzk5MyAxMC44MDQxTDMuOTc2NyA2LjIwODM2Wk0xMi4yNjgzIDUuMjYyOTRMOS4zODE2OCA4LjE0OTZMNS43MDg5MiA0LjQ3NjdMMTAuMzA0NyAzLjI5OTNMMTIuMjY4MyA1LjI2Mjk0Wk0xNy42OTU5IDMuMjk5M0wyMi4yOTE1IDQuNDc2N0wxOC42MTg2IDguMTQ5NDZMMTUuNzMyMSA1LjI2Mjk0TDE3LjY5NTkgMy4yOTkzWk0yMy4yMzcyIDEyLjc2ODFMMjAuMzUwNSA5Ljg4MTRMMjQuMDIzMyA2LjIwODc4TDI1LjIwMDcgMTAuODA0NkwyMy4yMzcyIDEyLjc2ODFaTTI0LjAyMzMgMjIuNzkxNEwyMC4zNTA1IDE5LjExODZMMjMuMjM3MiAxNi4yMzIxTDI1LjIwMDcgMTguMTk1N0wyNC4wMjMzIDIyLjc5MTRaIj48L3BhdGg+PC9nPjwvc3ZnPgo=';

const JustifiPlaidPaymentMethod = /*@__PURE__*/ proxyCustomElement(class JustifiPlaidPaymentMethod extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.__attachShadow();
        this.paymentMethodOptionSelected = createEvent(this, "paymentMethodOptionSelected", 7);
        this.plaidError = createEvent(this, "plaidError", 7);
        this.plaidErrorRecovered = createEvent(this, "plaidErrorRecovered", 7);
        this.isAuthenticating = false;
        this.publicToken = null;
        this.linkToken = null;
        this.linkTokenId = null;
        this.error = null;
        this.plaidLink = null;
        this.isSelected = false;
        this.retryCount = 0;
        this.isRetrying = false;
        this.sdkLoaded = false;
        this.plaidService = new PlaidService();
        this.maxRetries = 3;
        this.retryDelay = 2000; // 2 seconds
        this.timeoutId = null;
        this.abortController = null;
        this.hasLoggedDisabledWarning = false;
        this.hasLoggedAchPaymentsDisabledWarning = false;
        this.waitForStoreAndInitialize = () => {
            // Check if store has necessary data
            if (checkoutStore.authToken && checkoutStore.accountId && checkoutStore.checkoutId) {
                this.initializePlaidLink();
            }
            else {
                // Wait a bit and try again
                setTimeout(() => {
                    this.waitForStoreAndInitialize();
                }, 100);
            }
        };
        this.initializePlaidLink = async () => {
            try {
                // Check if Plaid is available globally
                if (typeof window.Plaid === 'undefined') {
                    this.handleError({
                        code: PlaidErrorCodes.PLAID_SDK_LOAD_FAILED,
                        message: PLAID_ERROR_MESSAGES[PlaidErrorCodes.PLAID_SDK_LOAD_FAILED],
                        severity: PLAID_ERROR_SEVERITY[PlaidErrorCodes.PLAID_SDK_LOAD_FAILED],
                        retryable: true,
                        userAction: 'Refresh the page and try again'
                    });
                    return;
                }
                // Get link token from backend
                await this.getLinkToken();
                if (!this.linkToken) {
                    this.handleError({
                        code: PlaidErrorCodes.PLAID_LINK_TOKEN_FAILED,
                        message: PLAID_ERROR_MESSAGES[PlaidErrorCodes.PLAID_LINK_TOKEN_FAILED],
                        severity: PLAID_ERROR_SEVERITY[PlaidErrorCodes.PLAID_LINK_TOKEN_FAILED],
                        retryable: true,
                        userAction: 'Click to try again'
                    });
                    return;
                }
                // Initialize Plaid Link
                const Plaid = window.Plaid;
                this.plaidLink = Plaid.create({
                    token: this.linkToken,
                    onSuccess: this.handlePlaidSuccess,
                    onExit: this.handlePlaidExit,
                    onEvent: this.handlePlaidEvent,
                    onLoad: this.handlePlaidLoad,
                });
            }
            catch (error) {
                this.handleError({
                    code: PlaidErrorCodes.PLAID_LINK_INIT_FAILED,
                    message: PLAID_ERROR_MESSAGES[PlaidErrorCodes.PLAID_LINK_INIT_FAILED],
                    severity: PLAID_ERROR_SEVERITY[PlaidErrorCodes.PLAID_LINK_INIT_FAILED],
                    originalError: error,
                    retryable: true,
                    userAction: 'Click to try again'
                });
            }
        };
        this.getLinkToken = async () => {
            var _a, _b, _c, _d, _e;
            try {
                if (!checkoutStore.authToken || !checkoutStore.accountId) {
                    this.handleError({
                        code: PlaidErrorCodes.PLAID_LINK_TOKEN_FAILED,
                        message: 'Missing authentication. Please refresh the page and try again.',
                        severity: ComponentErrorSeverity.ERROR,
                        retryable: false,
                        userAction: 'Refresh the page'
                    });
                    return;
                }
                // Create abort controller for timeout handling
                this.abortController = new AbortController();
                // Set timeout for the request
                this.timeoutId = setTimeout(() => {
                    var _a;
                    (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort();
                }, 30000); // 30 second timeout
                const response = await this.plaidService.getLinkToken(checkoutStore.authToken, checkoutStore.accountId, checkoutStore.checkoutId, this.abortController.signal);
                // Clear timeout
                if (this.timeoutId) {
                    clearTimeout(this.timeoutId);
                    this.timeoutId = null;
                }
                if (response.error) {
                    const errorMessage = typeof response.error === 'string'
                        ? response.error
                        : response.error.message || 'Failed to get link token';
                    throw new Error(errorMessage);
                }
                // Some backends may return an id along with the link token
                this.linkToken = response.data.link_token;
                // Try to capture link token id if present in envelope
                this.linkTokenId = (response === null || response === void 0 ? void 0 : response.id) || ((_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.id) || null;
                if (this.linkTokenId) {
                    checkoutStore.plaidLinkTokenId = this.linkTokenId;
                }
            }
            catch (error) {
                // Clear timeout
                if (this.timeoutId) {
                    clearTimeout(this.timeoutId);
                    this.timeoutId = null;
                }
                let errorCode = PlaidErrorCodes.PLAID_LINK_TOKEN_FAILED;
                let message = PLAID_ERROR_MESSAGES[errorCode];
                let retryable = true;
                // Handle specific error types
                if (error.name === 'AbortError') {
                    errorCode = PlaidErrorCodes.PLAID_TIMEOUT;
                    message = PLAID_ERROR_MESSAGES[errorCode];
                    retryable = true;
                }
                else if (((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('network')) || ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('fetch'))) {
                    errorCode = PlaidErrorCodes.PLAID_NETWORK_ERROR;
                    message = PLAID_ERROR_MESSAGES[errorCode];
                    retryable = true;
                }
                else if (((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes('401')) || ((_e = error.message) === null || _e === void 0 ? void 0 : _e.includes('unauthorized'))) {
                    errorCode = PlaidErrorCodes.PLAID_INVALID_CREDENTIALS;
                    message = 'Authentication failed. Please refresh the page and try again.';
                    retryable = false;
                }
                this.handleError({
                    code: errorCode,
                    message: message,
                    severity: PLAID_ERROR_SEVERITY[errorCode],
                    originalError: error,
                    retryable,
                    userAction: retryable ? 'Click to try again' : 'Refresh the page'
                });
            }
        };
        this.mapApiErrorToPlaidError = (apiError) => {
            if (typeof apiError === 'string') {
                if (apiError.includes('rate_limit'))
                    return PlaidErrorCodes.PLAID_RATE_LIMITED;
                if (apiError.includes('maintenance'))
                    return PlaidErrorCodes.PLAID_MAINTENANCE;
                if (apiError.includes('not_authenticated'))
                    return PlaidErrorCodes.PLAID_INVALID_CREDENTIALS;
            }
            if (apiError === null || apiError === void 0 ? void 0 : apiError.code) {
                switch (apiError.code) {
                    case 'rate_limited': return PlaidErrorCodes.PLAID_RATE_LIMITED;
                    case 'maintenance': return PlaidErrorCodes.PLAID_MAINTENANCE;
                    case 'not_authenticated': return PlaidErrorCodes.PLAID_INVALID_CREDENTIALS;
                    case 'invalid_parameter': return PlaidErrorCodes.PLAID_LINK_TOKEN_FAILED;
                    default: return PlaidErrorCodes.PLAID_LINK_TOKEN_FAILED;
                }
            }
            return PlaidErrorCodes.PLAID_LINK_TOKEN_FAILED;
        };
        this.openPlaidLink = () => {
            if (this.plaidLink && this.linkToken) {
                this.isAuthenticating = true;
                this.clearError();
                this.plaidLink.open();
            }
        };
        this.handlePlaidSuccess = (publicToken, _metadata) => {
            this.publicToken = publicToken;
            this.isAuthenticating = false;
            this.clearError();
            this.retryCount = 0; // Reset retry count on success
            // Ensure the component remains selected after successful authentication
            if (!this.isSelected) {
                this.isSelected = true;
                checkoutStore.selectedPaymentMethod = { type: PAYMENT_METHODS.PLAID };
            }
            // Emit success event for parent components
            this.plaidErrorRecovered.emit({
                code: 'plaid-success',
                message: 'Bank account connected successfully',
                severity: ComponentErrorSeverity.INFO
            });
            // Store public token in checkout store; exchange will be handled on submit
            checkoutStore.plaidPublicToken = publicToken;
        };
        // Exchange logic moved to Modular Checkout submit flow.
        this.handlePlaidExit = (err, _metadata) => {
            this.isAuthenticating = false;
            if (err) {
                this.handlePlaidError(err);
            }
        };
        this.handlePlaidEvent = (eventName, metadata) => {
            // Handle specific events if needed
            switch (eventName) {
                case 'OPEN':
                    this.isAuthenticating = true;
                    break;
                case 'CLOSE':
                    this.isAuthenticating = false;
                    break;
                case 'ERROR':
                    this.handlePlaidError(metadata);
                    break;
            }
        };
        this.handlePlaidLoad = () => {
        };
        this.handlePlaidError = (error) => {
            let errorCode = PlaidErrorCodes.PLAID_AUTHENTICATION_FAILED;
            let message = PLAID_ERROR_MESSAGES[errorCode];
            let retryable = true;
            let userAction = 'Click to try again';
            // Map Plaid error codes to our error codes
            if (error.error_code) {
                switch (error.error_code) {
                    case 'INVALID_CREDENTIALS':
                        errorCode = PlaidErrorCodes.PLAID_INVALID_CREDENTIALS;
                        message = PLAID_ERROR_MESSAGES[errorCode];
                        retryable = true;
                        break;
                    case 'ITEM_LOGIN_REQUIRED':
                        errorCode = PlaidErrorCodes.PLAID_INVALID_CREDENTIALS;
                        message = 'Your bank requires re-authentication. Please try again.';
                        retryable = true;
                        break;
                    case 'ITEM_LOCKED':
                        errorCode = PlaidErrorCodes.PLAID_ACCOUNT_LOCKED;
                        message = PLAID_ERROR_MESSAGES[errorCode];
                        retryable = false;
                        userAction = 'Contact your bank';
                        break;
                    case 'INSTITUTION_NOT_RESPONDING':
                        errorCode = PlaidErrorCodes.PLAID_MAINTENANCE;
                        message = PLAID_ERROR_MESSAGES[errorCode];
                        retryable = true;
                        break;
                    case 'RATE_LIMIT_EXCEEDED':
                        errorCode = PlaidErrorCodes.PLAID_RATE_LIMITED;
                        message = PLAID_ERROR_MESSAGES[errorCode];
                        retryable = true;
                        break;
                    case 'INVALID_REQUEST':
                        errorCode = PlaidErrorCodes.PLAID_AUTHENTICATION_FAILED;
                        message = 'Invalid request. Please try again.';
                        retryable = true;
                        break;
                    case 'PLAID_ERROR':
                        errorCode = PlaidErrorCodes.PLAID_AUTHENTICATION_FAILED;
                        message = error.error_message || 'Bank authentication failed. Please try again.';
                        retryable = true;
                        break;
                    default:
                        // Use the error message from Plaid if available
                        if (error.error_message) {
                            message = error.error_message;
                        }
                        break;
                }
            }
            // Handle specific error messages
            if (error.error_message) {
                const lowerMessage = error.error_message.toLowerCase();
                if (lowerMessage.includes('not supported') || lowerMessage.includes('unsupported')) {
                    errorCode = PlaidErrorCodes.PLAID_BANK_NOT_SUPPORTED;
                    message = PLAID_ERROR_MESSAGES[errorCode];
                    retryable = false;
                    userAction = 'Try a different payment method';
                }
                else if (lowerMessage.includes('expired') || lowerMessage.includes('timeout')) {
                    errorCode = PlaidErrorCodes.PLAID_TOKEN_EXPIRED;
                    message = PLAID_ERROR_MESSAGES[errorCode];
                    retryable = true;
                }
            }
            this.handleError({
                code: errorCode,
                message,
                severity: PLAID_ERROR_SEVERITY[errorCode],
                originalError: error,
                retryable,
                userAction
            });
            this.isAuthenticating = false;
        };
        this.handleError = (plaidError) => {
            this.error = plaidError;
            // Emit error event for parent components
            this.plaidError.emit({
                code: plaidError.code,
                message: plaidError.message,
                severity: plaidError.severity,
                data: {
                    originalError: plaidError.originalError,
                    retryable: plaidError.retryable,
                    userAction: plaidError.userAction,
                    retryCount: this.retryCount
                }
            });
            console.error('Plaid error:', plaidError);
            // Auto-retry for retryable errors if under max retries
            if (plaidError.retryable && this.retryCount < this.maxRetries) {
                this.scheduleRetry();
            }
        };
        this.scheduleRetry = () => {
            if (this.isRetrying)
                return;
            this.isRetrying = true;
            this.retryCount++;
            setTimeout(() => {
                this.isRetrying = false;
                this.clearError();
                this.waitForStoreAndInitialize();
            }, this.retryDelay * this.retryCount); // Exponential backoff
        };
        this.clearError = () => {
            if (this.error) {
                this.error = null;
                this.retryCount = 0;
            }
        };
        // Watch for store changes to sync component state
        this.syncWithStore = () => {
            var _a;
            const shouldBeSelected = ((_a = checkoutStore.selectedPaymentMethod) === null || _a === void 0 ? void 0 : _a.type) === PAYMENT_METHODS.PLAID;
            if (this.isSelected !== shouldBeSelected) {
                this.isSelected = shouldBeSelected;
            }
        };
    }
    onSelectionChange(newValue) {
        var _a;
        // Ensure store is updated when component selection changes
        if (newValue && ((_a = checkoutStore.selectedPaymentMethod) === null || _a === void 0 ? void 0 : _a.type) !== PAYMENT_METHODS.PLAID) {
            checkoutStore.selectedPaymentMethod = { type: PAYMENT_METHODS.PLAID };
        }
        // Auto-start Plaid flow when selected and ready
        if (newValue &&
            this.plaidLink &&
            !this.publicToken &&
            !this.isAuthenticating &&
            !this.error) {
            this.openPlaidLink();
        }
    }
    componentWillLoad() {
        var _a;
        this.isSelected = ((_a = checkoutStore.selectedPaymentMethod) === null || _a === void 0 ? void 0 : _a.type) === PAYMENT_METHODS.PLAID;
        if (checkoutStore.bankAccountVerification !== true)
            return;
        if (checkoutStore.checkoutLoaded) {
            if (checkoutStore.achPaymentsEnabled) {
                this.loadPlaidSDK();
            }
        }
        else {
            onChange('checkoutLoaded', (loaded) => {
                if (loaded &&
                    checkoutStore.bankAccountVerification === true &&
                    checkoutStore.achPaymentsEnabled) {
                    this.loadPlaidSDK();
                }
            });
        }
    }
    loadPlaidSDK() {
        if (this.sdkLoaded)
            return;
        this.sdkLoaded = true;
        const script = document.createElement('script');
        script.src = 'https://cdn.plaid.com/link/v2/stable/link-initialize.js';
        script.async = true;
        script.onload = () => this.initializePlaidLink();
        script.onerror = () => {
            this.handleError({
                code: PlaidErrorCodes.PLAID_SDK_LOAD_FAILED,
                message: PLAID_ERROR_MESSAGES[PlaidErrorCodes.PLAID_SDK_LOAD_FAILED],
                severity: PLAID_ERROR_SEVERITY[PlaidErrorCodes.PLAID_SDK_LOAD_FAILED],
                retryable: true,
                userAction: 'Refresh the page and try again'
            });
        };
        document.head.appendChild(script);
    }
    async resolvePaymentMethod() {
        if (!this.publicToken) {
            return { validationError: true };
        }
        return {
            token: this.publicToken,
            data: {
                type: 'bank_account',
                plaid_public_token: this.publicToken
            }
        };
    }
    // Returns a usable payment method token for checkout completion.
    // Will perform the backend exchange if the token is not yet present in the store.
    async getPaymentToken() {
        return checkoutStore.paymentToken;
    }
    async handleSelectionClick() {
        // Update local selection state
        this.isSelected = true;
        // Update store selection
        checkoutStore.selectedPaymentMethod = { type: PAYMENT_METHODS.PLAID };
        // If there's an error, clear it and try to initialize again
        if (this.error) {
            this.clearError();
            this.waitForStoreAndInitialize();
            return;
        }
        // If Plaid Link is ready and no public token exists, open Plaid Link
        if (this.plaidLink && !this.publicToken && !this.isAuthenticating) {
            this.openPlaidLink();
        }
    }
    // Method to handle external selection changes (e.g., from other payment methods)
    async setSelected(selected) {
        this.isSelected = selected;
        if (selected) {
            checkoutStore.selectedPaymentMethod = { type: PAYMENT_METHODS.PLAID };
        }
    }
    // Method to check if component is currently selected
    async isCurrentlySelected() {
        return this.isSelected;
    }
    // Method to handle external deselection (when another payment method is selected)
    async deselect() {
        this.isSelected = false;
        // Don't clear the public token or error state as they might be needed if user reselects
    }
    // Method to reset component state (useful for testing or error recovery)
    async reset() {
        this.publicToken = null;
        this.clearError();
        this.isAuthenticating = false;
        this.linkToken = null;
        this.plaidLink = null;
        this.retryCount = 0;
        this.isRetrying = false;
        // Clear any pending timeouts
        if (this.timeoutId) {
            clearTimeout(this.timeoutId);
            this.timeoutId = null;
        }
        // Abort any pending requests
        if (this.abortController) {
            this.abortController.abort();
            this.abortController = null;
        }
    }
    // Method to check if component is ready for authentication
    async isReadyForAuthentication() {
        return !!(this.plaidLink && this.linkToken && !this.isAuthenticating);
    }
    // Method to manually retry after an error
    async retry() {
        if (this.error && this.error.retryable) {
            this.clearError();
            this.waitForStoreAndInitialize();
        }
    }
    // Method to get current error information
    async getErrorInfo() {
        return this.error;
    }
    componentDidLoad() {
        // Set up store change listener to keep component in sync
        const unsubscribe = onChange('selectedPaymentMethod', this.syncWithStore);
        // Store unsubscribe function for cleanup
        this.unsubscribeFromStore = unsubscribe;
    }
    disconnectedCallback() {
        // Clean up store subscription
        if (this.unsubscribeFromStore) {
            this.unsubscribeFromStore();
        }
        // Clean up timeouts and abort controllers
        if (this.timeoutId) {
            clearTimeout(this.timeoutId);
        }
        if (this.abortController) {
            this.abortController.abort();
        }
    }
    render() {
        if (checkoutStore.checkoutLoaded && !checkoutStore.achPaymentsEnabled) {
            if (!this.hasLoggedAchPaymentsDisabledWarning) {
                console.warn('[JustifiPlaidPaymentMethod] ACH payments are disabled for this checkout. Component will not render.');
                this.hasLoggedAchPaymentsDisabledWarning = true;
            }
            return null;
        }
        // Only allow use if enabled in checkout settings
        if (checkoutStore.bankAccountVerification !== true) {
            if (!this.hasLoggedDisabledWarning) {
                // Log once per component lifecycle
                console.warn('[JustifiPlaidPaymentMethod] bank_account_verification is disabled. Component will not render.');
                this.hasLoggedDisabledWarning = true;
            }
            return null;
        }
        const plaidLogo = (h("img", { class: "plaid-logo-img", src: plaidIconSvg, alt: "Plaid", title: "Plaid", style: {
                display: 'inline',
                width: '20px',
                height: '20px',
                marginLeft: '5px',
                marginTop: '-2px',
            } }));
        const renderErrorState = () => {
            if (!this.error)
                return null;
            const errorClass = this.error.severity === ComponentErrorSeverity.ERROR
                ? 'text-danger'
                : this.error.severity === ComponentErrorSeverity.WARNING
                    ? 'text-warning'
                    : 'text-info';
            return (h("div", { class: `${errorClass} mt-2` }, h("small", null, this.error.message), h("br", null), h("small", { class: "text-muted" }, this.error.userAction, this.error.retryable && this.retryCount < this.maxRetries && (h("span", null, " \u2022 Auto-retry in progress...")))));
        };
        const renderStatusState = () => {
            if (this.error)
                return null;
            if (this.isAuthenticating) {
                return (h("div", { class: "text-info mt-2" }, h("small", null, "Connecting to your bank...")));
            }
            if (this.publicToken) {
                return (h("div", { class: "text-success mt-2" }, h("small", null, "\u2713 Bank account connected successfully")));
            }
            if (this.isSelected && !this.publicToken && !this.error && !this.isAuthenticating) {
                return (h("div", { class: "text-muted mt-2" }, h("small", null, "Click to connect your bank account")));
            }
            return null;
        };
        return (h(StyledHost, { class: "payment-method" }, h("div", { title: "Pay with Plaid" }, h("div", { onClick: (event) => { event.preventDefault(); this.handleSelectionClick(); } }, "Pay with Bank Account ", plaidLogo, " "), renderErrorState(), renderStatusState())));
    }
    static get watchers() { return {
        "isSelected": ["onSelectionChange"]
    }; }
}, [257, "justifi-plaid-payment-method", {
        "isAuthenticating": [32],
        "publicToken": [32],
        "linkToken": [32],
        "linkTokenId": [32],
        "error": [32],
        "plaidLink": [32],
        "isSelected": [32],
        "retryCount": [32],
        "isRetrying": [32],
        "resolvePaymentMethod": [64],
        "getPaymentToken": [64],
        "handleSelectionClick": [64],
        "setSelected": [64],
        "isCurrentlySelected": [64],
        "deselect": [64],
        "reset": [64],
        "isReadyForAuthentication": [64],
        "retry": [64],
        "getErrorInfo": [64]
    }, undefined, {
        "isSelected": ["onSelectionChange"]
    }]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["justifi-plaid-payment-method"];
    components.forEach(tagName => { switch (tagName) {
        case "justifi-plaid-payment-method":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, JustifiPlaidPaymentMethod);
            }
            break;
    } });
}
defineCustomElement();

export { JustifiPlaidPaymentMethod as J, defineCustomElement as d };
