import { Connection } from '@solana/web3.js';
import { CHAIN_NAMESPACES, SolanaWallet } from '@web3auth/no-modal';
import { ref, shallowRef, watch } from 'vue';
import '@web3auth/no-modal/vue';
import { useWeb3Auth } from '../../composables/useWeb3Auth.js';

const useSolanaWallet = () => {
  const {
    provider,
    web3Auth
  } = useWeb3Auth();
  const accounts = ref([]);
  const solanaWallet = shallowRef(null);
  const connection = shallowRef(null);
  const setupWallet = async () => {
    var _web3Auth$value, _web3Auth$value2;
    if (!((_web3Auth$value = web3Auth.value) !== null && _web3Auth$value !== void 0 && (_web3Auth$value = _web3Auth$value.currentChain) !== null && _web3Auth$value !== void 0 && _web3Auth$value.chainNamespace) || web3Auth.value.currentChain.chainNamespace !== CHAIN_NAMESPACES.SOLANA) {
      return;
    }
    solanaWallet.value = new SolanaWallet(provider.value);
    const result = await solanaWallet.value.requestAccounts();
    if ((result === null || result === void 0 ? void 0 : result.length) > 0) {
      accounts.value = result;
    }
    connection.value = new Connection((_web3Auth$value2 = web3Auth.value) === null || _web3Auth$value2 === void 0 || (_web3Auth$value2 = _web3Auth$value2.currentChain) === null || _web3Auth$value2 === void 0 ? void 0 : _web3Auth$value2.rpcTarget);
  };
  if (provider.value && !solanaWallet.value) {
    setupWallet();
  }
  watch(provider, async newVal => {
    if (!newVal && solanaWallet.value) {
      solanaWallet.value = null;
      accounts.value = null;
      connection.value = null;
      return;
    }
    if (newVal && !solanaWallet.value) {
      setupWallet();
    }
  }, {
    immediate: true
  });
  return {
    solanaWallet,
    accounts,
    connection
  };
};

export { useSolanaWallet };
