import { useMemo, useEffect } from 'react';
import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react';
import { WalletModalProvider } from '@solana/wallet-adapter-react-ui';
import { registerLazorkitWallet } from '@lazorkit/wallet';

// Configuration
const CONFIG = {
  RPC_URL: "https://api.devnet.solana.com",
  PORTAL_URL: "https://portal.lazor.sh",
  PAYMASTER: {
    paymasterUrl: "https://kora.devnet.lazorkit.com",
  },
  CLUSTER: 'devnet' as 'devnet' | 'mainnet' | undefined
};

let lazorkitWalletRegistered = false;

export function AppProviders({ children }: { children: React.ReactNode }) {
  // Register LazorKit once on mount
  useEffect(() => {
    if (!lazorkitWalletRegistered) {
      registerLazorkitWallet({
          rpcUrl: CONFIG.RPC_URL,
          portalUrl: CONFIG.PORTAL_URL,
          paymasterConfig: CONFIG.PAYMASTER,
          clusterSimulation: CONFIG.CLUSTER,
      });
      lazorkitWalletRegistered = true;
    }
  }, []);

  const wallets = useMemo(
    () => [
      // Standard wallets are automatically detected. 
      // LazorKit will appear here after registration.
    ],
    []
  );

  return (
    <ConnectionProvider endpoint={CONFIG.RPC_URL}>
      <WalletProvider wallets={wallets} autoConnect>
        <WalletModalProvider>
          {children}
        </WalletModalProvider>
      </WalletProvider>
    </ConnectionProvider>
  );
}