'use client';

import { useEffect, useRef, useState } from 'react'
import { detectSolana } from './solana'
import { useBuddyState, BUDDY_WALLETS } from '../../../../index'

export const Detect = () => {
  const [wallets, setWallets] = useBuddyState(BUDDY_WALLETS);
  const intervalRef = useRef(null);

  // Helper function to compare wallet objects by their keys only
  const walletsChanged = (prev, current) => {
    const prevKeys = Object.keys(prev).sort()
    const currentKeys = Object.keys(current).sort()
    
    if (prevKeys.length !== currentKeys.length) return true
    
    return prevKeys.some((key, index) => key !== currentKeys[index])
  }

  useEffect(() => {
    const detect = () => {
      try {
        if (typeof window === 'undefined') return

        const detected = detectSolana()

        setWallets((prev) =>
          walletsChanged(prev, detected) ? detected : prev
        )
      } catch (_) {}
    }

    detect()
    intervalRef.current = setInterval(detect, 1000)

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
        intervalRef.current = null
      }
    }
  }, [])

  return null
}
