import { useEffect, useState } from 'react'

const SEVERE = new Set(['ERROR', 'CRITICAL'])

function wsLogsUrl(): string {
  const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  return `${proto}//${window.location.host}/ws/logs`
}

/** Počítá ERROR/CRITICAL z /ws/logs jen když stránka Logy není aktivní (aby nebyly 2 sockety). */
export function useLogSeverityBadge(logsPageActive: boolean): number {
  const [count, setCount] = useState(0)

  useEffect(() => {
    if (logsPageActive) {
      setCount(0)
      return
    }

    let ws: WebSocket | null = null
    let reconnectTimer: ReturnType<typeof setTimeout> | null = null
    let disposed = false

    const connect = () => {
      if (disposed) return
      ws = new WebSocket(wsLogsUrl())
      ws.onmessage = (e) => {
        try {
          const o = JSON.parse(e.data) as { level?: string }
          if (o.level && SEVERE.has(o.level)) setCount((c) => c + 1)
        } catch {
          /* ignore */
        }
      }
      ws.onclose = () => {
        if (disposed) return
        reconnectTimer = setTimeout(connect, 3000)
      }
    }

    connect()

    return () => {
      disposed = true
      if (reconnectTimer != null) clearTimeout(reconnectTimer)
      ws?.close()
    }
  }, [logsPageActive])

  return count
}
