import { h, } from "@stencil/core";
import { ApplePayService, ApplePayServiceErrorCode } from "../../../api/services/apple-pay.service";
import { ApplePayButtonType, ApplePayButtonStyle, ApplePayHelpers, ApplePayMerchantCapability, } from "../../../api/ApplePay";
import { StyledHost } from "../../../ui-components";
import ApplePaySkeleton from "./apple-pay-skeleton";
import { ApplePayButton } from "../../../ui-components/apple-pay-button";
import { checkoutStore, onChange } from "../../../store/checkout.store";
export class JustifiApplePay {
    constructor() {
        this.sdkLoaded = false;
        this.countryCode = "US";
        this.merchantIdentifier = "merchant.com.staging-justifi.checkout-dev";
        this.merchantDisplayName = "JustiFi Checkout";
        this.initiativeContext = "dev-checkout.justifi-staging.com";
        this.buttonType = ApplePayButtonType.PLAIN;
        this.buttonStyle = ApplePayButtonStyle.BLACK;
        this.disabled = false;
        this.width = "100%";
        this.height = "48px";
        this.isLoading = true;
        this.isProcessing = false;
        this.isAvailable = false;
        this.canMakePayments = false;
        this.isConfigValid = true;
        this.error = null;
        this.handleApplePayClick = async () => {
            var _a, _b, _c;
            if (this.isProcessing || this.disabled || !this.isAvailable) {
                return;
            }
            try {
                this.isProcessing = true;
                this.error = null;
                this.applePayStarted.emit();
                const paymentRequest = {
                    countryCode: this.countryCode,
                    currencyCode: checkoutStore.paymentCurrency,
                    merchantCapabilities: [
                        ApplePayMerchantCapability.SUPPORTS_3DS,
                        ApplePayMerchantCapability.SUPPORTS_CREDIT,
                        ApplePayMerchantCapability.SUPPORTS_DEBIT,
                    ],
                    supportedNetworks: ApplePayHelpers.getDefaultSupportedNetworks(),
                    total: ApplePayHelpers.createLineItem(checkoutStore.paymentDescription, checkoutStore.paymentAmount),
                };
                const result = await this.applePayService.startPaymentSession(paymentRequest, checkoutStore.authToken, checkoutStore.accountId);
                if (result.success) {
                    this.applePayCompleted.emit({
                        success: true,
                        token: result.token,
                        paymentMethodId: result.paymentMethodId,
                    });
                }
                else {
                    this.applePayCompleted.emit({
                        success: false,
                        error: result.error,
                    });
                    this.applePayError.emit({
                        error: ((_a = result.error) === null || _a === void 0 ? void 0 : _a.message) || "Payment failed",
                        code: ((_b = result.error) === null || _b === void 0 ? void 0 : _b.code) || JustifiApplePay.ErrorCode.PAYMENT_FAILED,
                    });
                }
            }
            catch (error) {
                if (((_c = error === null || error === void 0 ? void 0 : error.error) === null || _c === void 0 ? void 0 : _c.code) === ApplePayServiceErrorCode.USER_CANCELLED) {
                    this.applePayCancelled.emit();
                }
                else {
                    const errorMessage = error instanceof Error ? error.message : "Payment failed";
                    this.error = errorMessage;
                    this.applePayError.emit({ error: errorMessage, code: JustifiApplePay.ErrorCode.PAYMENT_FAILED });
                    this.applePayCompleted.emit({
                        success: false,
                        error: errorMessage,
                    });
                }
            }
            finally {
                this.isProcessing = false;
            }
        };
    }
    componentWillLoad() {
        this.isAvailable = ApplePayHelpers.isApplePaySupported();
        if (!this.isAvailable) {
            this.isLoading = false;
            return;
        }
        if (checkoutStore.checkoutLoaded) {
            this.loadApplePaySDK();
        }
        else {
            onChange('checkoutLoaded', (loaded) => {
                if (loaded)
                    this.loadApplePaySDK();
            });
        }
    }
    loadApplePaySDK() {
        if (this.sdkLoaded)
            return;
        this.sdkLoaded = true;
        const script = document.createElement('script');
        script.src = 'https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js';
        script.async = true;
        script.onload = () => this.initializeApplePay();
        document.head.appendChild(script);
    }
    async initializeApplePay() {
        try {
            this.isLoading = true;
            this.error = null;
            this.isConfigValid = true;
            const hasRequiredConfig = Boolean(checkoutStore.paymentAmount) &&
                Boolean(checkoutStore.paymentCurrency) &&
                Boolean(checkoutStore.authToken);
            if (!hasRequiredConfig) {
                this.error = "Missing required Apple Pay configuration";
                this.isConfigValid = false;
                this.applePayError.emit({ error: this.error, code: JustifiApplePay.ErrorCode.CONFIG_ERROR });
                this.isLoading = false;
                return;
            }
            this.isAvailable = ApplePayHelpers.isApplePaySupported();
            this.canMakePayments = ApplePayHelpers.canMakePayments();
            if (!this.isAvailable) {
                this.error = "Apple Pay is not supported on this device";
                this.applePayError.emit({ error: this.error, code: JustifiApplePay.ErrorCode.NOT_SUPPORTED });
                this.isLoading = false;
                return;
            }
            if (!this.canMakePayments) {
                this.error = "Apple Pay is not available";
                this.applePayError.emit({ error: this.error, code: JustifiApplePay.ErrorCode.NOT_AVAILABLE });
                this.isLoading = false;
                return;
            }
            const applePayConfig = {
                merchantIdentifier: this.merchantIdentifier,
                displayName: this.merchantDisplayName,
                initiative: "web",
                initiativeContext: this.initiativeContext,
                buttonType: this.buttonType,
                buttonStyle: this.buttonStyle,
            };
            this.applePayService = new ApplePayService();
            this.applePayService.initialize(applePayConfig);
            const hasActiveCard = await this.applePayService.canMakePaymentsWithActiveCard();
            if (!hasActiveCard) {
                console.warn("No Apple Pay cards available, but continuing...");
            }
        }
        catch (error) {
            this.error =
                error instanceof Error
                    ? error.message
                    : "Failed to initialize Apple Pay";
            this.applePayError.emit({ error: this.error, code: JustifiApplePay.ErrorCode.INITIALIZATION_ERROR });
        }
        finally {
            this.isLoading = false;
        }
    }
    async isSupported() {
        return this.isAvailable && this.canMakePayments;
    }
    async getPaymentMethods() {
        if (!this.isAvailable) {
            return [];
        }
        return ApplePayHelpers.getDefaultSupportedNetworks();
    }
    async abort() {
        var _a;
        (_a = this.applePayService) === null || _a === void 0 ? void 0 : _a.abortPaymentSession();
        this.isProcessing = false;
        this.applePayCancelled.emit();
    }
    render() {
        if (!checkoutStore.applePayEnabled) {
            // Render nothing when Apple Pay is disabled at the checkout settings level
            return null;
        }
        if (!this.isAvailable) {
            return null;
        }
        const isReady = !this.isLoading &&
            this.isAvailable &&
            this.canMakePayments &&
            this.isConfigValid;
        return (h(StyledHost, null, h("div", { class: 'apple-pay-container' }, h(ApplePaySkeleton, { isLoading: this.isLoading }), isReady && (h(ApplePayButton, { buttonType: this.buttonType, buttonStyle: this.buttonStyle, disabled: this.disabled, isProcessing: this.isProcessing, isAvailable: this.isAvailable, clickHandler: this.handleApplePayClick, width: this.width, height: this.height }))), h("style", null, `
            .apple-pay-container {
              width: 100%;
            }
          `)));
    }
    static get is() { return "justifi-apple-pay"; }
    static get encapsulation() { return "shadow"; }
    static get properties() {
        return {
            "countryCode": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "country-code",
                "defaultValue": "\"US\""
            },
            "merchantIdentifier": {
                "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-identifier",
                "defaultValue": "\"merchant.com.staging-justifi.checkout-dev\""
            },
            "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\""
            },
            "initiativeContext": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "initiative-context",
                "defaultValue": "\"dev-checkout.justifi-staging.com\""
            },
            "buttonType": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "ApplePayButtonType",
                    "resolved": "ApplePayButtonType.BOOK | ApplePayButtonType.BUY | ApplePayButtonType.CHECK_OUT | ApplePayButtonType.DONATE | ApplePayButtonType.PLAIN | ApplePayButtonType.SET_UP | ApplePayButtonType.SUBSCRIBE",
                    "references": {
                        "ApplePayButtonType": {
                            "location": "import",
                            "path": "../../../api/ApplePay",
                            "id": "src/api/ApplePay.ts::ApplePayButtonType"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "button-type",
                "defaultValue": "ApplePayButtonType.PLAIN"
            },
            "buttonStyle": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "ApplePayButtonStyle",
                    "resolved": "ApplePayButtonStyle.BLACK | ApplePayButtonStyle.WHITE | ApplePayButtonStyle.WHITE_OUTLINE",
                    "references": {
                        "ApplePayButtonStyle": {
                            "location": "import",
                            "path": "../../../api/ApplePay",
                            "id": "src/api/ApplePay.ts::ApplePayButtonStyle"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "button-style",
                "defaultValue": "ApplePayButtonStyle.BLACK"
            },
            "disabled": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "disabled",
                "defaultValue": "false"
            },
            "width": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "width",
                "defaultValue": "\"100%\""
            },
            "height": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "height",
                "defaultValue": "\"48px\""
            }
        };
    }
    static get states() {
        return {
            "isLoading": {},
            "isProcessing": {},
            "isAvailable": {},
            "canMakePayments": {},
            "isConfigValid": {},
            "error": {}
        };
    }
    static get events() {
        return [{
                "method": "applePayStarted",
                "name": "applePayStarted",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "applePayCompleted",
                "name": "applePayCompleted",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "{\n    success: boolean;\n    token?: IApplePayToken;\n    paymentMethodId?: string;\n    error?: any;\n  }",
                    "resolved": "{ success: boolean; token?: IApplePayToken; paymentMethodId?: string; error?: any; }",
                    "references": {
                        "IApplePayToken": {
                            "location": "import",
                            "path": "../../../api/ApplePay",
                            "id": "src/api/ApplePay.ts::IApplePayToken"
                        }
                    }
                }
            }, {
                "method": "applePayCancelled",
                "name": "applePayCancelled",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "applePayError",
                "name": "applePayError",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "{ error: string, code: string }",
                    "resolved": "{ error: string; code: string; }",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "isSupported": {
                "complexType": {
                    "signature": "() => Promise<boolean>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<boolean>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "getPaymentMethods": {
                "complexType": {
                    "signature": "() => Promise<string[]>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<string[]>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "abort": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
}
// Centralized error codes for the Apple Pay component layer
JustifiApplePay.ErrorCode = {
    CONFIG_ERROR: 'CONFIG_ERROR',
    NOT_SUPPORTED: 'NOT_SUPPORTED',
    NOT_AVAILABLE: 'NOT_AVAILABLE',
    INITIALIZATION_ERROR: 'INITIALIZATION_ERROR',
    PAYMENT_FAILED: 'PAYMENT_FAILED',
};
