import { Component, Event, Prop, State, Host, h, Method } from '@stencil/core';
import { Env } from '@stencil/core';
import Dropkit from 'dropkit.js';
import CoinbaseWalletSDK from '@coinbase/wallet-sdk';
import WalletConnectProvider from '@walletconnect/web3-provider';
import { METAMASK_BASE64 } from '../../config/logos';
export class NkDropkit {
  constructor() {
    /**
     * Flag to enable testnet mode
     */
    this.dev = false;
    /**
     * Flag to enable multiple wallet support
     */
    this.multiple = true;
    /**
     * Connect Wallet Button default text
     */
    this.walletText = 'Connect Wallet';
    /**
     * Mint Button default text
     */
    this.mintText = 'Mint NFT';
    /**
     * Sold Out default text
     */
    this.soldOutText = 'Sold Out';
    this.msg = null;
    this.drop = null;
    this.maxPerMint = 0;
    this.isSoldOut = false;
  }
  render() {
    const NkMsg = () => {
      if (!this.msg) {
        return null;
      }
      const Msg = this.msg.error ? 'nk-error-message' : 'nk-success-message';
      return (h(Msg, { class: "info", exportparts: "info", onClosed: () => (this.msg = null) }, this.msg.text));
    };
    const ConnectWalletBtn = () => {
      return (h("nk-wallet-button", { exportparts: "wallet-btn-container, wallet-btn", disabled: this.loading, loading: this.loading, onClick: () => this.initDrop() }, this.walletText));
    };
    const MintBtn = () => {
      return (h("nk-mint-button", { exportparts: "mint-btn-container, mint-btn, mint-text, mint-dropdown-icon", selectedValue: this.selectValue, maxPerMint: this.maxPerMint, disabled: this.loading, loading: this.loading, placeholder: this.mintText, onTokensChanged: event => this.handleSelect(event) }));
    };
    return (h(Host, null,
      h(NkMsg, null),
      !this.dropStarted ? (h(ConnectWalletBtn, null)) : this.isSoldOut ? (h("nk-sold-out", { exportparts: "sold-out-container, sold-out-text" }, this.soldOutText)) : (h(MintBtn, null)),
      h("slot", null)));
  }
  async handleSelect(event) {
    this.msg = null;
    this.loading = true;
    try {
      this.selectValue = Math.max(event.detail, 1);
      await this.mint(this.selectValue);
    }
    catch (e) {
      this.msg = { error: true, text: e.message };
    }
    finally {
      this.loading = false;
    }
  }
  async mint(quantity) {
    if (!this.drop) {
      await this.initDrop();
    }
    await this.drop.mint(quantity);
    const dropCollection = await this.getCollectionInfo();
    this.minted.emit(dropCollection);
    this.msg = { error: false, text: `Tokens Minted: ${quantity}` };
  }
  async initDrop() {
    var _a;
    this.loading = true;
    try {
      const providers = this.getProviders();
      this.drop = await Dropkit.create(this.apikey, this.dev, providers);
      if (this.isMobile() && ((_a = this.drop.ethInstance) === null || _a === void 0 ? void 0 : _a.on)) {
        this.drop.ethInstance.on('chainChanged', async () => {
          this.dropStarted = false;
          this.msg = { error: false, text: 'Switching networks...' };
          window.location.reload();
        });
      }
      this.maxPerMint = await this.drop.maxPerMint();
      const dropCollection = await this.getCollectionInfo();
      this.isSoldOut = dropCollection.totalSupply >= dropCollection.maxAmount;
      this.walletConnected.emit(dropCollection);
      this.dropStarted = true;
    }
    catch (e) {
      this.msg = { error: true, text: e.message };
    }
    finally {
      this.loading = false;
    }
  }
  async getCollectionInfo() {
    if (!this.drop) {
      throw new Error('Dropkit is not initialized');
    }
    const dropCollection = {
      maxAmount: await this.drop.maxAmount(),
      maxPerMint: await this.drop.maxPerMint(),
      maxPerWallet: await this.drop.maxPerWallet(),
      totalSupply: await this.drop.totalSupply(),
      walletTokensCount: await this.drop.walletTokensCount(),
      walletAddress: this.drop.walletAddress,
    };
    return dropCollection;
  }
  isMobile() {
    return this.deviceType() !== 'desktop';
  }
  deviceType() {
    const ua = navigator.userAgent;
    if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
      return 'tablet';
    }
    if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
      return 'mobile';
    }
    return 'desktop';
  }
  getProviders() {
    let providers = {};
    const infuraId = Env.infuraId;
    if (infuraId && this.multiple) {
      providers = {
        walletlink: {
          package: CoinbaseWalletSDK,
          options: {
            appName: 'Dropkit',
            infuraId,
          },
        },
        walletconnect: {
          package: WalletConnectProvider,
          options: {
            infuraId,
            rpc: {
              80001: 'https://matic-mumbai.chainstacklabs.com',
              137: 'https://polygon-rpc.com',
            },
          },
        },
      };
    }
    if (this.isMobile()) {
      providers = Object.assign(Object.assign({}, providers), { 'custom-metamask': {
          display: {
            logo: METAMASK_BASE64,
            name: 'MetaMask',
            description: 'Connect to your MetaMask Wallet',
          },
          package: true,
          connector: () => {
            const url = `${window.location.origin}${window.location.pathname}`;
            window.location.href = `https://metamask.app.link/dapp/${url}`;
          },
        } });
    }
    return providers;
  }
  static get is() { return "nk-dropkit"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["nk-dropkit.css"]
  }; }
  static get styleUrls() { return {
    "$": ["nk-dropkit.css"]
  }; }
  static get properties() { return {
    "apikey": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": true,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Drop SDK Key"
      },
      "attribute": "apikey",
      "reflect": false
    },
    "dev": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Flag to enable testnet mode"
      },
      "attribute": "dev",
      "reflect": false,
      "defaultValue": "false"
    },
    "multiple": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Flag to enable multiple wallet support"
      },
      "attribute": "multiple",
      "reflect": false,
      "defaultValue": "true"
    },
    "walletText": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Connect Wallet Button default text"
      },
      "attribute": "wallet-text",
      "reflect": false,
      "defaultValue": "'Connect Wallet'"
    },
    "mintText": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Mint Button default text"
      },
      "attribute": "mint-text",
      "reflect": false,
      "defaultValue": "'Mint NFT'"
    },
    "soldOutText": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Sold Out default text"
      },
      "attribute": "sold-out-text",
      "reflect": false,
      "defaultValue": "'Sold Out'"
    }
  }; }
  static get states() { return {
    "loading": {},
    "dropStarted": {},
    "selectValue": {},
    "msg": {}
  }; }
  static get events() { return [{
      "method": "walletConnected",
      "name": "walletConnected",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "DropCollection",
        "resolved": "DropCollection",
        "references": {
          "DropCollection": {
            "location": "import",
            "path": "../../types/drop-collection.interface"
          }
        }
      }
    }, {
      "method": "minted",
      "name": "minted",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "DropCollection",
        "resolved": "DropCollection",
        "references": {
          "DropCollection": {
            "location": "import",
            "path": "../../types/drop-collection.interface"
          }
        }
      }
    }]; }
  static get methods() { return {
    "mint": {
      "complexType": {
        "signature": "(quantity: number) => Promise<void>",
        "parameters": [{
            "tags": [],
            "text": ""
          }],
        "references": {
          "Promise": {
            "location": "global"
          }
        },
        "return": "Promise<void>"
      },
      "docs": {
        "text": "",
        "tags": []
      }
    },
    "initDrop": {
      "complexType": {
        "signature": "() => Promise<void>",
        "parameters": [],
        "references": {
          "Promise": {
            "location": "global"
          }
        },
        "return": "Promise<void>"
      },
      "docs": {
        "text": "",
        "tags": []
      }
    }
  }; }
}
