import { h } from "@stencil/core";
import classNames from "classnames";
import { ProviderLabelsEnum, ProviderTypeEnum } from "../../../types/provider.types";
import { EventBus } from "../../../utils/EventBus";
import { processImgSrc } from "../../../utils/processImgSrc";
import { getIsExtensionAvailable, getIsMetaMaskAvailable } from "./helpers";
import { UnlockPanelEventsEnum } from "./unlock-panel.types";
const DEFAULT_ALLOWED_PROVIDERS = Object.values(ProviderTypeEnum);
export class UnlockPanel {
    constructor() {
        this.eventBus = new EventBus();
        this.isOpen = false;
        this.allowedProviders = DEFAULT_ALLOWED_PROVIDERS;
        this.isLoggingIn = false;
        this.isIntroScreenVisible = false;
        this.selectedMethod = null;
        this.hasSlotContent = false;
        this.panelState = {
            isOpen: false,
            allowedProviders: DEFAULT_ALLOWED_PROVIDERS,
        };
        this.anchor = null;
        this.observer = null;
    }
    async getEventBus() {
        return this.eventBus;
    }
    handleIsOpenChange(newValue) {
        this.panelState = Object.assign(Object.assign({}, this.panelState), { isOpen: newValue });
    }
    handleAllowedProvidersChange(newValue) {
        this.panelState = Object.assign(Object.assign({}, this.panelState), { allowedProviders: newValue !== null && newValue !== void 0 ? newValue : DEFAULT_ALLOWED_PROVIDERS });
    }
    isExtensionInstalled(currentProvider) {
        return currentProvider === ProviderTypeEnum.extension && getIsExtensionAvailable();
    }
    isMetaMaskInstalled(currentProvider) {
        return currentProvider === ProviderTypeEnum.metamask && getIsMetaMaskAvailable();
    }
    async disconnectedCallback() {
        if (this.observer) {
            this.observer.disconnect();
            this.observer = null;
        }
        this.eventBus.unsubscribe(UnlockPanelEventsEnum.OPEN, this.unlockPanelUpdate.bind(this));
        this.isLoggingIn = false;
        this.selectedMethod = null;
        this.panelState = { isOpen: false, allowedProviders: DEFAULT_ALLOWED_PROVIDERS };
        return new Promise(resolve => setTimeout(resolve, 300));
    }
    observeContainer(element) {
        if (!element) {
            return;
        }
        this.anchor = element;
        if (this.observer) {
            this.observer.disconnect();
        }
        this.observer = new MutationObserver(() => {
            this.isLoggingIn = element.childElementCount > 0;
        });
        this.observer.observe(element, { childList: true, subtree: true });
    }
    handleLogin(provider) {
        this.eventBus.publish(UnlockPanelEventsEnum.LOGIN, { type: provider, anchor: this.anchor });
        this.selectedMethod = provider;
        switch (provider) {
            case ProviderTypeEnum.ledger:
                this.isIntroScreenVisible = true;
                break;
            default:
                this.handleAccess();
        }
    }
    handleResetLoginState(event) {
        event.preventDefault();
        this.isLoggingIn = false;
        this.isIntroScreenVisible = false;
        this.selectedMethod = null;
        if (!this.anchor) {
            return;
        }
        while (this.anchor.firstChild) {
            this.anchor.removeChild(this.anchor.firstChild);
        }
        this.eventBus.publish(UnlockPanelEventsEnum.CANCEL_LOGIN);
    }
    handleClose(event) {
        event.preventDefault();
        if (this.selectedMethod) {
            this.eventBus.publish(UnlockPanelEventsEnum.CANCEL_LOGIN);
        }
        this.eventBus.publish(UnlockPanelEventsEnum.CLOSE);
    }
    handleAccess() {
        this.isIntroScreenVisible = false;
        this.isLoggingIn = true;
        this.login.emit({ provider: this.selectedMethod, anchor: this.anchor });
    }
    render() {
        const detectedProviders = this.panelState.allowedProviders.filter(allowedProvider => this.isExtensionInstalled(allowedProvider) || this.isMetaMaskInstalled(allowedProvider));
        const otherProviders = this.panelState.allowedProviders.filter(allowedProvider => !detectedProviders.includes(allowedProvider));
        const panelTitle = this.selectedMethod ? ProviderLabelsEnum[this.selectedMethod] : 'Connect your wallet';
        const hasDetectedProviders = detectedProviders.length > 0;
        return (h("mvx-side-panel", { key: '6f8ee2b74d7f119124491bf9e2a80d89680d9f7e', isOpen: this.panelState.isOpen, panelTitle: panelTitle, withBackButton: this.isLoggingIn, onClose: this.handleClose.bind(this), onBack: this.handleResetLoginState.bind(this) }, h("div", { key: '06f67fbed4f5b63b02f7a9a52374dccb288fd89e', id: "anchor", ref: element => this.observeContainer(element), class: { 'unlock-panel-anchor': this.isLoggingIn } }), this.isIntroScreenVisible && h("mvx-unlock-provider-intro", { key: 'fab94eb622d27357c94ca092f481ce327db88398', provider: this.selectedMethod, onAccess: this.handleAccess.bind(this) }), !this.isLoggingIn && !this.isIntroScreenVisible && (h("div", { key: 'd57f66ce310eb15d0a0517b8ba9cd26a7df4eb60', class: "unlock-panel" }, h("div", { key: 'a6e8ba7860c767f0d074f327c2594caf9229bbcb', class: "unlock-panel-groups" }, hasDetectedProviders && (h("div", { key: '6a617926802ac1f0cd150b15712a48f24bb1166c', class: "unlock-panel-group" }, h("div", { key: '4da45982432ad1f31a4185de49c10198261b390f', class: "unlock-panel-group-label" }, "Detected"), h("div", { key: 'ddd514e4a7311b4e4dce19d484d234d5eab78289', class: "unlock-panel-group-providers" }, detectedProviders.map((provider, providerIndex) => (h("mvx-unlock-provider-button", { type: provider, onClick: this.handleLogin.bind(this, provider), class: classNames('unlock-panel-group-provider', {
                first: providerIndex === 0,
                last: providerIndex === detectedProviders.length - 1,
            }) })))))), h("div", { key: '3deb1fa6dae9f564a50ce4cb5116099475710d40', class: "unlock-panel-group" }, h("div", { key: '8b3da87444c513b2755de4e62cf86db85929d17c', class: "unlock-panel-group-label" }, hasDetectedProviders ? 'Other Options' : 'Options'), h("div", { key: '16b3e74b5bf359c15e8f99ec5dae366280af7fa2', class: "unlock-panel-group-providers" }, otherProviders.map((provider, providerIndex) => (h("mvx-unlock-provider-button", { type: provider, onClick: this.handleLogin.bind(this, provider), class: classNames('unlock-panel-group-provider', {
                first: providerIndex === 0,
                last: providerIndex === otherProviders.length - 1,
            }) }))), h("slot", { key: '2b697ba5e0bd54b094d50603b7bec49fb3e15ed2' })))), h("div", { key: 'dcd574870a4a24fa3f02b5b4964c44753081d3c2', class: "unlock-panel-footer" }, h("img", { key: 'dabe5db6be79487c78776804aab34a9e6e40c231', src: processImgSrc('unlock-panel-wallet.png'), class: "unlock-panel-footer-image" }), h("div", { key: 'bedb8591f7b813ececff4838b8fde7d2c8c89598', class: "unlock-panel-footer-wrapper" }, h("div", { key: 'fc478933e0df8a3e9f2b2d28c556be78aca9679b', class: "unlock-panel-footer-title" }, "Don't have a wallet?"), h("div", { key: '824c4d97f55299eb49fb14b35dc84cd69561e7f3', class: "unlock-panel-footer-subtitle" }, "Take full control of ", h("br", { key: 'ddc0da7f702dcda6753beaa5fa748f316cf31318' }), " your assets."), h("mvx-arrow-up-right-icon", { key: 'cc5233d90af4b71c6f0ed4fe6bfbd442ab964332', class: "unlock-panel-footer-icon" })))))));
    }
    componentDidLoad() {
        this.eventBus.subscribe(UnlockPanelEventsEnum.OPEN, this.unlockPanelUpdate.bind(this));
    }
    unlockPanelUpdate(payload) {
        var _a;
        this.panelState = Object.assign(Object.assign({}, payload), { allowedProviders: (_a = payload.allowedProviders) !== null && _a !== void 0 ? _a : DEFAULT_ALLOWED_PROVIDERS });
    }
    static get is() { return "mvx-unlock-panel"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["unlock-panel.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["unlock-panel.css"]
        };
    }
    static get properties() {
        return {
            "isOpen": {
                "type": "boolean",
                "attribute": "is-open",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "allowedProviders": {
                "type": "unknown",
                "attribute": "allowed-providers",
                "mutable": false,
                "complexType": {
                    "original": "ProviderTypeEnum[]",
                    "resolved": "ProviderTypeEnum[]",
                    "references": {
                        "ProviderTypeEnum": {
                            "location": "import",
                            "path": "types/provider.types",
                            "id": "src/types/provider.types.ts::ProviderTypeEnum"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "DEFAULT_ALLOWED_PROVIDERS"
            }
        };
    }
    static get states() {
        return {
            "isLoggingIn": {},
            "isIntroScreenVisible": {},
            "selectedMethod": {},
            "hasSlotContent": {},
            "panelState": {}
        };
    }
    static get events() {
        return [{
                "method": "close",
                "name": "close",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "login",
                "name": "login",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "{ provider: ProviderTypeEnum; anchor?: HTMLElement }",
                    "resolved": "{ provider: ProviderTypeEnum; anchor?: HTMLElement; }",
                    "references": {
                        "ProviderTypeEnum": {
                            "location": "import",
                            "path": "types/provider.types",
                            "id": "src/types/provider.types.ts::ProviderTypeEnum"
                        },
                        "HTMLElement": {
                            "location": "global",
                            "id": "global::HTMLElement"
                        }
                    }
                }
            }];
    }
    static get methods() {
        return {
            "getEventBus": {
                "complexType": {
                    "signature": "() => Promise<IEventBus>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "IEventBus": {
                            "location": "import",
                            "path": "utils/EventBus",
                            "id": "src/utils/EventBus.ts::IEventBus"
                        }
                    },
                    "return": "Promise<IEventBus>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "hostElement"; }
    static get watchers() {
        return [{
                "propName": "isOpen",
                "methodName": "handleIsOpenChange"
            }, {
                "propName": "allowedProviders",
                "methodName": "handleAllowedProvidersChange"
            }];
    }
}
//# sourceMappingURL=unlock-panel.js.map
