import { cookieStorage, createStorage, noopStorage } from 'wagmi'
import { WagmiAdapter } from '@reown/appkit-adapter-wagmi'
import { mainnet, arbitrum, polygon, optimism, base, bsc, type AppKitNetwork } from '@reown/appkit/networks'

// Read Project ID from environment variables
// Hardcoded for testing - remove after confirming it works
const envProjectId = process.env.NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID
export const projectId = envProjectId || '50cd82701d75c524a38489fe8bd63742'

// Debug logging - updated
console.log('[UPDATED] WalletConnect Project ID from env:', envProjectId)
console.log('[UPDATED] WalletConnect Project ID (final):', projectId)
console.log('[UPDATED] All NEXT_PUBLIC env vars:', Object.keys(process.env).filter(k => k.startsWith('NEXT_PUBLIC_')))

// Ensure Project ID is defined at build time
if (!projectId) {
  throw new Error('NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID is not defined. Please set it in .env')
}

// Define supported networks, explicitly typed as a non-empty array of AppKitNetworks
export const networks: [AppKitNetwork, ...AppKitNetwork[]] = [mainnet, polygon, arbitrum, optimism, base, bsc]

// Custom storage that doesn't persist connection state to prevent auto-connect
const customStorage = createStorage({
  storage: typeof window !== 'undefined' ? {
    getItem: (key) => {
      // Only allow reading certain keys, not connection state
      if (key.includes('recentConnector') || key.includes('store')) {
        return null;
      }
      return window.localStorage.getItem(key);
    },
    setItem: (key, value) => {
      // Don't persist connector state
      if (key.includes('recentConnector') || key.includes('store')) {
        return;
      }
      window.localStorage.setItem(key, value);
    },
    removeItem: (key) => {
      window.localStorage.removeItem(key);
    },
  } : noopStorage,
});

// Create the Wagmi adapter instance
console.log('[wallet config] Creating WagmiAdapter with projectId:', projectId);
export const wagmiAdapter = new WagmiAdapter({
  storage: customStorage,
  ssr: true,
  projectId,
  networks,
})
console.log('[wallet config] WagmiAdapter created successfully');

// Export the Wagmi config generated by the adapter
// Use type assertion to handle viem version mismatches between @reown/appkit and wagmi
export const config = wagmiAdapter.wagmiConfig as any
