import { useEffect, useState } from 'react'
import { supabase } from '../../lib/supabaseClient'

/**
 * Highest `highscore` in `player_stats`, same ordering as {@link LeaderboardPage}.
 */
export function useTopHighscore() {
  const [topScore, setTopScore] = useState<number | null>(null)
  const [topName, setTopName] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false

    async function load() {
      const { data, error } = await supabase
        .from('player_stats')
        .select('highscore, username')
        .order('highscore', { ascending: false })
        .limit(1)

      if (cancelled) return

      if (error || !data?.length) {
        setTopScore(null)
        setTopName(null)
      } else {
        const row = data[0] as { highscore: number; username?: string }
        setTopScore(typeof row.highscore === 'number' ? row.highscore : null)
        setTopName(typeof row.username === 'string' ? row.username : null)
      }
      setLoading(false)
    }

    void load()
    return () => {
      cancelled = true
    }
  }, [])

  return { topScore, topName, loading }
}
