import { h, proxyCustomElement, HTMLElement, createEvent, Host } from '@stencil/core/internal/client';
import { w as waitForConfig, c as configState } from './config-state.js';
import { c as checkoutStore } from './checkout.store.js';
import { S as Skeleton } from './skeleton.js';
import './justifi-details2.js';
import './event-types.js';
import './justifi-radio-list-item2.js';

const GooglePaySkeleton = (props) => {
    const { isLoading } = props;
    if (!isLoading) {
        return null;
    }
    return (h("div", { class: 'container-fluid p-0' }, h("div", { class: 'row mb-3' }, h("div", { class: 'col-12 align-content-center' }, h(Skeleton, { height: '44px', width: '100%', styles: { borderRadius: "8px" } })))));
};

var GooglePayEventTypes;
(function (GooglePayEventTypes) {
    GooglePayEventTypes["initialize"] = "justifi.googlePay.initialize";
    GooglePayEventTypes["ready"] = "justifi.googlePay.ready";
    GooglePayEventTypes["sdkLoaded"] = "justifi.googlePay.sdkLoaded";
    GooglePayEventTypes["initializeResult"] = "justifi.googlePay.initializeResult";
    GooglePayEventTypes["error"] = "justifi.googlePay.error";
    GooglePayEventTypes["buttonClicked"] = "justifi.googlePay.buttonClicked";
    GooglePayEventTypes["startPayment"] = "justifi.googlePay.startPayment";
    GooglePayEventTypes["paymentSuccess"] = "justifi.googlePay.paymentSuccess";
    GooglePayEventTypes["paymentCanceled"] = "justifi.googlePay.paymentCanceled";
    GooglePayEventTypes["paymentError"] = "justifi.googlePay.paymentError";
})(GooglePayEventTypes || (GooglePayEventTypes = {}));
const JustifiGooglePay = /*@__PURE__*/ proxyCustomElement(class JustifiGooglePay extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.__attachShadow();
        this.googlePayStarted = createEvent(this, "googlePayStarted", 7);
        this.googlePayCompleted = createEvent(this, "googlePayCompleted", 7);
        this.googlePayCancelled = createEvent(this, "googlePayCancelled", 7);
        this.merchantDisplayName = "JustiFi Checkout";
        /** Set to true when embedding inside an Android WebView so the iframe uses the
         * W3C Payment Request API (native Google Pay sheet) instead of pay.js's
         * loadPaymentData popup, which Google blocks in WebViews (OR_BIBED_15). */
        this.useNativePaymentRequest = false;
        this.iframeReady = false;
        this.sdkLoaded = false;
        this.isReadyToPay = false;
        this.handleMessage = (event) => {
            if (event.origin !== this.iframeOrigin)
                return;
            const { eventType, data } = event.data || {};
            switch (eventType) {
                case GooglePayEventTypes.ready:
                    this.iframeReady = true;
                    break;
                case GooglePayEventTypes.sdkLoaded:
                    this.sdkLoaded = true;
                    this.sendInitialize();
                    break;
                case GooglePayEventTypes.initializeResult:
                    this.isReadyToPay = data.isReadyToPay;
                    if (data.error)
                        console.error("Init error:", data.error);
                    break;
                case GooglePayEventTypes.error:
                    console.error("Google Pay error:", data);
                    break;
                case GooglePayEventTypes.buttonClicked:
                    this.googlePayStarted.emit();
                    this.sendStartPayment();
                    break;
                case GooglePayEventTypes.paymentSuccess:
                    this.googlePayCompleted.emit({
                        success: true,
                        paymentMethodId: data.paymentMethodId,
                        cardNetwork: data.cardNetwork,
                        cardDetails: data.cardDetails,
                    });
                    break;
                case GooglePayEventTypes.paymentCanceled:
                    this.googlePayCancelled.emit();
                    break;
                case GooglePayEventTypes.paymentError:
                    this.googlePayCompleted.emit({
                        success: false,
                        error: { code: data.code, message: data.message },
                    });
                    break;
            }
        };
    }
    async componentWillLoad() {
        await waitForConfig();
        this.iframeOrigin = configState.iframeOrigin;
    }
    componentDidLoad() {
        window.addEventListener("message", this.handleMessage);
    }
    disconnectedCallback() {
        window.removeEventListener("message", this.handleMessage);
    }
    googlePayEnvironment() {
        if (this.environment !== undefined) {
            return this.environment;
        }
        return checkoutStore.checkoutMode === "test" ? "TEST" : "PRODUCTION";
    }
    sendInitialize() {
        var _a;
        if (!((_a = this.iframeElement) === null || _a === void 0 ? void 0 : _a.contentWindow))
            return;
        const config = {
            environment: this.googlePayEnvironment(),
            gatewayMerchantId: checkoutStore.accountId,
            merchantName: this.merchantDisplayName,
            authToken: checkoutStore.authToken,
            accountId: checkoutStore.accountId,
            useNativePaymentRequest: this.useNativePaymentRequest,
        };
        this.iframeElement.contentWindow.postMessage({
            eventType: GooglePayEventTypes.initialize,
            data: config,
        }, this.iframeOrigin);
    }
    sendStartPayment() {
        var _a;
        if (!((_a = this.iframeElement) === null || _a === void 0 ? void 0 : _a.contentWindow))
            return;
        const transactionInfo = {
            totalPrice: String(checkoutStore.paymentAmount / 100),
            totalPriceStatus: "FINAL",
            currencyCode: checkoutStore.paymentCurrency || "USD",
        };
        this.iframeElement.contentWindow.postMessage({
            eventType: GooglePayEventTypes.startPayment,
            data: transactionInfo,
        }, this.iframeOrigin);
    }
    render() {
        if (!checkoutStore.checkoutLoaded) {
            return null;
        }
        if (!checkoutStore.googlePayEnabled) {
            console.warn("Google Pay is not enabled for this checkout");
            return null;
        }
        return (h(Host, null, h(GooglePaySkeleton, { isLoading: !this.isReadyToPay }), h("iframe", { ref: (el) => (this.iframeElement = el), src: `${this.iframeOrigin}/v2/googlePay`, allow: "payment", style: {
                border: "none",
                width: "100%",
                height: "48px",
                display: this.isReadyToPay ? "block" : "none",
            } })));
    }
}, [257, "justifi-google-pay", {
        "environment": [1],
        "merchantDisplayName": [1, "merchant-display-name"],
        "useNativePaymentRequest": [4, "use-native-payment-request"],
        "iframeOrigin": [32],
        "iframeReady": [32],
        "sdkLoaded": [32],
        "isReadyToPay": [32]
    }]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["justifi-google-pay"];
    components.forEach(tagName => { switch (tagName) {
        case "justifi-google-pay":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, JustifiGooglePay);
            }
            break;
    } });
}
defineCustomElement();

export { JustifiGooglePay as J, defineCustomElement as d };
