import { useEffect, useState } from 'react'

const WINDOW_MS = 5 * 60_000
const PRUNE_MS = 10_000

/** Počet ERROR logů z /ws/logs za posledních 5 minut (podle času přijetí zprávy). */
export function useWsLogErrorCount(enabled: boolean): number {
  const [count, setCount] = useState(0)

  useEffect(() => {
    if (!enabled) {
      setCount(0)
      return
    }

    const timestamps: number[] = []
    const prune = () => {
      const cutoff = Date.now() - WINDOW_MS
      while (timestamps.length > 0 && timestamps[0]! < cutoff) {
        timestamps.shift()
      }
      setCount(timestamps.length)
    }

    const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const ws = new WebSocket(`${proto}//${window.location.host}/ws/logs`)

    ws.onmessage = (ev) => {
      let rec: { level?: string }
      try {
        rec = JSON.parse(ev.data as string) as { level?: string }
      } catch {
        return
      }
      if (rec.level === 'ERROR') {
        timestamps.push(Date.now())
        prune()
      }
    }

    const id = window.setInterval(prune, PRUNE_MS)
    return () => {
      window.clearInterval(id)
      ws.close()
    }
  }, [enabled])

  return count
}
