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

// 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 Chains
export const networks: [Chain, ...Chain[]] = [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
export const config = wagmiAdapter.wagmiConfig
