import { http, fallback } from 'wagmi'
import { mainnet, sepolia, arbitrum, base, arbitrumSepolia, bscTestnet, bsc } from 'wagmi/chains'
import { injected } from 'wagmi/connectors'
import { WagmiAdapter } from '@reown/appkit-adapter-wagmi'
import { createAppKit } from '@reown/appkit/react'

// WalletConnect Project ID
const projectId = process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID || ''

const networks = [mainnet, sepolia, arbitrum, base, bsc, arbitrumSepolia, bscTestnet] as const

// Mutable copy for AppKit which requires non-readonly tuple
const mutableNetworks = [...networks] as unknown as [import('@reown/appkit/networks').AppKitNetwork, ...import('@reown/appkit/networks').AppKitNetwork[]]

const transports = {
  [mainnet.id]: http(),
  [sepolia.id]: http(),
  [arbitrum.id]: http(),
  [base.id]: http(),
  [bsc.id]: http(),
  [arbitrumSepolia.id]: http(),
  [bscTestnet.id]: fallback([
    http('https://bsc-testnet-rpc.publicnode.com'),
    http('https://bsc-testnet.blockpi.network/v1/rpc/public'),
    http('https://endpoints.omniatech.io/v1/bsc/testnet/public'),
    http('https://data-seed-prebsc-1-s1.binance.org:8545'),
  ]),
}

// Wagmi Adapter for AppKit — WalletConnect Core is initialized here only once
export const wagmiAdapter = new WagmiAdapter({
  networks: mutableNetworks,
  projectId,
  connectors: [injected({ shimDisconnect: true })],
  transports,
})

// Create AppKit modal
createAppKit({
  adapters: [wagmiAdapter],
  networks: mutableNetworks,
  projectId,
  metadata: {
    name: 'AssetX',
    description: 'DeFi Asset Management Platform',
    url: typeof window !== 'undefined' ? window.location.origin : 'https://assetx.io',
    icons: ['/logo.svg'],
  },
  features: {
    analytics: true,
    email: false,
    socials: [],
    onramp: false,
    swaps: false,
  },
  themeMode: 'light',
  themeVariables: {
    '--w3m-z-index': 9999,
  },
})

// Use wagmiAdapter.wagmiConfig as the single source of truth
export const config = wagmiAdapter.wagmiConfig
