import { h, Host, } from "@stencil/core";
import { configState, waitForConfig } from "../../config-provider/config-state";
import { checkoutStore } from "../../../store/checkout.store";
import GooglePaySkeleton from "./google-pay-skeleton";
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 = {}));
export class JustifiGooglePay {
    constructor() {
        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",
            } })));
    }
    static get is() { return "justifi-google-pay"; }
    static get encapsulation() { return "shadow"; }
    static get properties() {
        return {
            "environment": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "\"TEST\" | \"PRODUCTION\"",
                    "resolved": "\"PRODUCTION\" | \"TEST\"",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "If not provided, the environment will be determined by the account mode: 'test' or 'live'."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "environment"
            },
            "merchantDisplayName": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "merchant-display-name",
                "defaultValue": "\"JustiFi Checkout\""
            },
            "useNativePaymentRequest": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Set to true when embedding inside an Android WebView so the iframe uses the\nW3C Payment Request API (native Google Pay sheet) instead of pay.js's\nloadPaymentData popup, which Google blocks in WebViews (OR_BIBED_15)."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "use-native-payment-request",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "iframeOrigin": {},
            "iframeReady": {},
            "sdkLoaded": {},
            "isReadyToPay": {}
        };
    }
    static get events() {
        return [{
                "method": "googlePayStarted",
                "name": "googlePayStarted",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "googlePayCompleted",
                "name": "googlePayCompleted",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "{\n    success: boolean;\n    paymentMethodId?: string;\n    cardNetwork?: string;\n    cardDetails?: string;\n    error?: { code: string; message: string };\n  }",
                    "resolved": "{ success: boolean; paymentMethodId?: string; cardNetwork?: string; cardDetails?: string; error?: { code: string; message: string; }; }",
                    "references": {}
                }
            }, {
                "method": "googlePayCancelled",
                "name": "googlePayCancelled",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
}
