import { WagmiAdapter } from '@reown/appkit-adapter-wagmi'
import { TronAdapter } from '@reown/appkit-adapter-tron'
import { createAppKit, type AppKit } from '@reown/appkit/vue'
import { TronLinkAdapter } from '@tronweb3/tronwallet-adapter-tronlink'
import { MetaMaskAdapter } from '@tronweb3/tronwallet-adapter-metamask-tron'
import {
  arbitrum,
  base,
  bsc,
  mainnet,
  optimism,
  polygon,
  tronMainnet,
  type AppKitNetwork,
} from '@reown/appkit/networks'
import { TRON_MAINNET_CAIP2 } from '@/utils/tronRecharge'

export const reownProjectId = String(import.meta.env.VITE_WALLETCONNECT_PROJECT_ID ?? '').trim()
export const reownEnabled = reownProjectId.length > 0

function tronRpcUrl(): string {
  return String(import.meta.env.VITE_TRON_FULL_HOST ?? '').trim() || 'https://api.trongrid.io'
}

export const evmNetworks: [AppKitNetwork, ...AppKitNetwork[]] = [
  mainnet,
  bsc,
  polygon,
  arbitrum,
  base,
  optimism,
]

export const reownNetworks: [AppKitNetwork, ...AppKitNetwork[]] = [
  ...evmNetworks,
  tronMainnet,
]

const metadata = {
  name: 'iBit',
  description: '链上充值',
  url: typeof window !== 'undefined' ? window.location.origin : 'https://ibit.com',
  icons: [] as string[],
}

export let wagmiAdapter: WagmiAdapter | null = null
export let tronAdapter: TronAdapter | null = null
export let reownAppKit: AppKit | null = null

if (reownEnabled) {
  wagmiAdapter = new WagmiAdapter({
    networks: evmNetworks,
    projectId: reownProjectId,
  })

  tronAdapter = new TronAdapter({
    walletAdapters: [
      new TronLinkAdapter({
        openUrlWhenWalletNotFound: false,
        checkTimeout: 3000,
      }),
      new MetaMaskAdapter(),
    ],
  })

  reownAppKit = createAppKit({
    adapters: [wagmiAdapter, tronAdapter],
    networks: reownNetworks,
    projectId: reownProjectId,
    metadata,
    themeMode: 'dark',
    themeVariables: {
      '--w3m-z-index': 3000,
    },
    features: {
      analytics: false,
      email: false,
      socials: false,
    },
    enableWallets: true,
    customRpcUrls: {
      [TRON_MAINNET_CAIP2]: [{ url: tronRpcUrl() }],
    },
  })
}

export function getWagmiConfig() {
  if (!wagmiAdapter) {
    throw new Error('未配置 VITE_WALLETCONNECT_PROJECT_ID')
  }
  return wagmiAdapter.wagmiConfig
}

export function getReownAppKit() {
  if (!reownAppKit) {
    throw new Error('未配置 VITE_WALLETCONNECT_PROJECT_ID')
  }
  return reownAppKit
}
