<template>
  <div class="chain-modal" v-if="props.visible" :class="{ mobile: 'mobile' }">
    <div class="modal-bg" @click="cancelSelect"></div>
    <div class="modal-content" :class="{ mobile: 'mobile' }">
      <div class="modal-title">
        <div>{{title||'Please connect your wallet'}}</div>
        <img
          src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAfCAYAAACGVs+MAAAAAXNSR0IArs4c6QAAApVJREFUWEe1lj1v01AUht/jBMrAwBIWmEBCldgSd2hrFGdhKAMLQQIJVSQSQ/IHGJjhD4AoMFGUDlEnJNQBNXFxUoZ8sSBmxC9goUjE9yA7cUhcf1w7JsoU697n8fnKIQD41Orfyij0hAj29+l6Mf/e/j3tT/ewfxMZemzfyxDPNH3tI5lm70pGKN+YcXYKtAB6uKnn36Up0G337oCUPQBnpvf+hkWr1Dnq3yemhgdmCRKVG8W13TQkfOCTa5nukWl+uaZY1lcA2f8hEQgHLM5mr5MNPT4aVpj5DQAlTYkQODNzTSupO46AI9EeVpn4dVoSYXCA65u6+tLmzgTSlJCFnxJIQyIO3FdgGYm48EAB+0Gn3asSKb41QUSVjWJ+oUXNw35ZyTjt7Pa5W148n3NvWy/UgPehrERSeGgEXJkoCWssTpK8uXt/aARkJAAIv7ArTLX1Un4napJKCUTUhJfBsnCpFMzfHpKOWcHFgccWsA90jcErAI/8Qkug3Q09vx0V9vnn0imwD5lGv6wAewB5/7jcOy2/Fg0TkhaQgM8kmLmqldS3MpGQEgiBs7Pc+PyLykpECoTB7YKzYP0JmpgyEqECx8aozLD8cr7QamHDKkoiUCAITkRCCNQ1z5BJKuErEBcuMzGDInFKICk8qcTiRhSQ86CwB7VZ2I7JxFWt+K9FZwKd1uAuKdzwDpm4cFdKVsIR6LZGt6GIfe9qnhQuJcHY1kqFxmQtN4Y/GHx5YUY71S7q9uosM9ESpOPnhdy5i8TM1DWGJ0RYmS0JKcEjIsHZ8Tg3SYExeAGgNj0gmHnpN/dGxFsTDBxoemHLEWg2m5lLuasPAFpl4g+aXjCXCXvQ2c/tkS5IlAF8XznPz1VV/fUXin/NrsS/4PgAAAAASUVORK5CYII="
          alt="close"
          class="close"
          @click="cancelSelect"/>
      </div>
      <div class="modal-sub-title">
        {{subTitle || 'Connect your wallet to start your Counter Fire journey'}}
      </div>
      <div class="modal-body">
        <div
          class="chain-modal-card"
          v-for="data in currentDatas"
          :key="data.name"
          @click="cardClicked(data.id)"
        >
          <div class="icon">
            <img :src="data.logo" :alt="data.name" />
          </div>
          <div class="name">{{ data.name }}</div>
          <div class="tip">{{ data.tip }}</div>
          <div class="fire-wallet" v-if="data.id == 5 && isFireWallet">
            <div class="fire-wallet-item" @click="googleLogin">
              <div class="icon">
                <img :src="icon_google" alt="">
              </div>
              <div class="name">Google</div>
            </div>
            <div class="fire-wallet-item" @click="appleLogin">
              <div class="icon">
                <img :src="icon_apple" alt="">
              </div>
              <div class="name">Apple</div>
            </div>
          </div>
        </div>
      </div>
      
    </div>
  </div>
</template>
<script setup>
import { computed, ref } from "vue";
import { ALL_PROVIDERS, icon_google, icon_apple } from "@/configs/configchain";
import { allProviders } from "@/components/chain/BlockChain"
import { getlogin } from "@/api/User";

import {apiCecInfo} from "@/utils/marketplace"
import { useMarketplaceStore } from "@/store/marketplace"
import {} from "@/store/wallet"
const marketplaceStore = useMarketplaceStore()

const props = defineProps({
  visible: ref(Boolean),
  close: Function,
  title: ref(String),
  subTitle: ref(String),
  initData: Object,
  disabled: Array
});

const currentDatas = computed(() => {
  let list = ALL_PROVIDERS.map((item) => {
    const Provider = allProviders[item.id];
    // console.log(Provider)
    const installed = new Provider().installed;
    // console.log(installed)
    const initData = props.initData;
    let current = null;
    if (initData) {
      current = initData[item.id];
    }
    const tip = installed ? current?.tip || item.tip || '' : "Click to Install";
    return {
      id: item.id,
      name: item.name,
      logo: item.logo,
      installed,
      downloadUrl: item.downloadUrl,
      tip,
    };
  });
  const disabled = props.disabled || [];
  list = list.filter((item) => !disabled.includes(item.id));
  return list;
});

async function selectWallet(id) {
  const Provider = allProviders[id];
  const walletInstance = new Provider()
  const { provider, accounts } = await walletInstance.web3Provider();
  hideModal({errcode: 0, provider, wallet: id, walletInstance, accounts});
}

const isFireWallet = ref(false)
async function cardClicked(id) {
  if(id == 5) {
    isFireWallet.value = !isFireWallet.value
  } else {
    const data = currentDatas.value.find((item) => item.id === id);
    if (!data.installed) {
      // return
      // // open download page
      if (!data.downloadUrl) {
        return;
      }
      window.open(data.downloadUrl, '_blank');
    } else {
      await selectWallet(id);
    }
  }
}

const walletTake = import.meta.env.VUE_APP_WALLET_TAKE
const googleLogin = async () => {
  let res = await callMethod("walletLogin", "0", walletTake);
  res = JSON.parse(res);
  marketplaceStore.fireAddress = res.data.address
  marketplaceStore.fireToken = res.data.token + '.cf'
  hideModal({errcode: 0})

    // let token = 'eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY1YjBjMmM4ZDY3MTBhYmQ1YjFhN2RhMyIsInVpZCI6IiIsImdpZCI6IiIsIm9wZW5pZCI6IjEwODc4Nzc3NTE0NTY3NzY2NzkwMCIsInZlcnNpb24iOjAsInBsYXQiOjAsImlhdCI6MTcyNDMyODg1NSwiZXhwIjoxNzI0NDE1MjU1fQ.1Qg06-q7t9YBgteWL4DtXphaHb9qlWbNJfIObdftqdO6uR2Qw5XTaZZoqdBJM8htjXpeKiYWD44ddTuMEVTHCA'
    // try{
    //   let data = await apiCecInfo('0x50f82c3e944f92cbbc1d8bfc601fc3fc5f7ab155', res.data.token+'.cf')
    //   console.log(data)
    // } catch (e) {
    //   console.log(e)
    // }
}
const appleLogin = async () => {
  let res = await callMethod("walletLogin", "1", walletTake);
  res = JSON.parse(res);
  marketplaceStore.fireAddress = res.data.address
  marketplaceStore.fireToken = res.data.token + '.cf'
  hideModal({errcode: 0})
}

function cancelSelect() {
  hideModal({errcode: 1, errmsg: "user cancel select wallet"});
}

function hideModal(result = null) {
  props.close(result);
}
</script>
<style lang="scss" scoped>
.chain-modal {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
  margin: 0;
  z-index: 10001;
  .modal-bg {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: auto;
    margin: 0;
    background-color: #000000a3;
  }
  .modal-content {
    width: 481px;
    background-color: #2d2738;
    border-radius: 40px;
    color: white;
    // margin: auto;
    display: flex;
    position: relative;
    right: -100%;
    transform: translateX(-481px);
    // margin-top: 15vh;
    margin-top: 84px;
    flex-direction: column;
    .mobile {
      width: 100vw;
    }
    .modal-title {
      border-radius: 40px 40px 0 0;
      padding: .78125vw 1.5625vw;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      height: 3.125vw;
      font-family: 'Anton';
      font-weight: 400;
      font-size: 26px;
      color: #FFFFFF;
      background-color: #1c1725;
      .close{
        width: 32px;
        height: 31px;
        cursor: pointer;
      }
    }
    .modal-sub-title {
      margin: 16px 29px 16px 31px;
      margin-left: 16px 31px;
      font-family: 'Poppins-Regular';
      font-size: 15px;
      font-weight: 400;
    }
    .modal-body {
      padding: 0 1.5625vw 1.04167vw;
      .chain-modal-card {
        transition: background-color 0.2s ease-in-out 0s;
        display: flex;
        align-items: center;
        cursor: pointer;
        margin: 9px 0;
        position: relative;
        width: 421px;
        height: 52px;
        background: url('@/assets/img/login/btn_frame1.png') no-repeat;
        background-size: 100% 100%;
        .icon {
          width: 40px !important;
          height: 40px !important;
          margin-left: 24px;
          overflow: visible;
          box-shadow: none;
          -webkit-box-pack: center;
          justify-content: center;
          -webkit-box-align: center;
          align-items: center;
          img {
            width: 100%;
            height: 100%;
          }
          .icon-svg {
            width: 100%;
            height: 100%;
            fill: currentColor;
            color: unset;
            stroke: none;
          }
        }
        .name {
          width: 55%;
          font-family: 'Poppins-Regular';
          font-weight: 400;
          font-size: 18px;
          color: #FFFFFF;
          text-align: left;
          margin-left: 15px;
        }
        .tip {
          text-align: right;
          color: red;
        }
        .tip a{
          color: red;
        }
        .fire-wallet {
          position: absolute;
          top: 0;
          left: -260px;
          width: 256px;
          // height: 100%;
          // border-radius: .41667vw;
          z-index: 9;
          .fire-wallet-item {
            display: flex;
            align-items: center;
            width: 256px;
            height: 40px;
            background: #2D2738;
            border-radius: 10px;
            border: 2px solid #625A6B;
            margin-bottom: 5px;
            .icon {
              width: 30px !important;
              height: 30px !important;
              margin-left: 30px !important;
              img {
                width: 100%;
                height: 100%;
              }
            }
            .name {
              margin-left: 18px;
              font-family: 'Poppins-Regular';
              font-weight: 400;
              font-size: 16px;
              color: #fff;
            }
            &:last-child {
              // border: 0px;
            }
            &:hover {
              background: #D5BEFA;
              border: 0px;
              .name {
                font-family: 'Poppins-Regular';
                font-weight: 400;
                font-size: 16px;
                color: #000;
              }
            }
          }
        }
      }
      .chain-modal-card:hover {
        background: url('@/assets/img/login/btn_frame2 .png') no-repeat;
        background-size: 100% 100%;
        color: #0A090A;
        .name {
          color: #0A090A;
        }
      }
    }
    
  }
}
</style>
