import { createWeb3Modal } from '@web3modal/wagmi/react'
import { http, createConfig, createStorage } from 'wagmi'
import { arbitrumSepolia, bscTestnet } from 'wagmi/chains'
import { QueryClient } from '@tanstack/react-query'
import { injected } from 'wagmi/connectors'

export const queryClient = new QueryClient()

// WalletConnect Project ID - 从 https://cloud.walletconnect.com/ 获取
const projectId = '3a8170812b534d0ff9d794f19a901d64'

// 检查是否应该跳过自动重连
const shouldSkipReconnect = () => {
  if (typeof window === 'undefined') return false
  const skip = sessionStorage.getItem('skipReconnect') === 'true'
  if (skip) {
    sessionStorage.removeItem('skipReconnect')
  }
  return skip
}

// 自定义 storage，在需要时禁用重连
const customStorage = createStorage({
  storage: {
    getItem: (key: string) => {
      // 如果设置了跳过重连，返回 null 来阻止重连
      if (shouldSkipReconnect() && key === 'wagmi.recentConnectorId') {
        return null
      }
      return localStorage.getItem(key)
    },
    setItem: (key: string, value: string) => localStorage.setItem(key, value),
    removeItem: (key: string) => localStorage.removeItem(key),
  },
})

export const config = createConfig({
  chains: [arbitrumSepolia, bscTestnet], // 支持多链
  connectors: [
    injected(), // 支持 MetaMask 等浏览器钱包
    // Web3Modal 会自动添加 WalletConnect 和其他钱包
  ],
  transports: {
    [arbitrumSepolia.id]: http(), // ARB Sepolia (421614)
    [bscTestnet.id]: http(),      // BNB Testnet (97)
  },
  storage: customStorage,
})

createWeb3Modal({
  wagmiConfig: config,
  projectId,
  enableAnalytics: false,
  themeMode: 'light',
})
