import { ref } from 'vue'
import Web3 from 'web3'

export function useWeb3() {
  const web3 = ref(null)
  const isConnected = ref(false)
  const chainId = ref(null)
  const accounts = ref([])

  const initWeb3 = async () => {
    if (window.ethereum) {
      web3.value = new Web3(window.ethereum)
      try {
        accounts.value = await window.ethereum.request({ method: 'eth_requestAccounts' })
        chainId.value = await window.ethereum.request({ method: 'eth_chainId' })
        isConnected.value = true
        
        // 监听账户变化
        window.ethereum.on('accountsChanged', (newAccounts) => {
          accounts.value = newAccounts
        })
        
        // 监听链变化
        window.ethereum.on('chainChanged', (newChainId) => {
          chainId.value = newChainId
          window.location.reload()
        })
      } catch (error) {
        console.error('User denied account access', error)
      }
    } else {
      console.log('Non-Ethereum browser detected. Consider installing MetaMask!')
    }
  }

  return { web3, isConnected, chainId, accounts, initWeb3 }
}