/**
 * Sidebar Badge Module
 *
 * SSE-driven badge count updates for sidebar nav items.
 * Uses the shared SSEManager — no new EventSource connections per badge.
 *
 * Usage:
 *   import { SSEManager } from '@countermeasure/web-components/services/sse'
 *   import { connectBadges } from '@countermeasure/web-components/sidebar/badge'
 *
 *   const sse = new SSEManager({ url: '/api/v1/sse' })
 *   sse.connect()
 *
 *   const cleanup = connectBadges(sse, {
 *     'unread-messages': 'notifications:messages',
 *     'deployment-errors': 'notifications:deployments',
 *   })
 */

import type { SSEManager, SSEEventHandler } from '../services/sse'

export interface BadgeCountPayload {
  count: number
}

/**
 * Connect badge elements to SSE events via a shared SSEManager.
 *
 * @param sse - Shared SSEManager instance (already connected or will be connected).
 * @param mapping - Maps badge data attribute IDs to SSE event type names.
 *                  e.g. { 'unread-messages': 'notifications:messages' }
 *                  Badge elements are found via [data-badge="<id>"].
 * @returns Cleanup function that unsubscribes all handlers.
 */
export function connectBadges(sse: SSEManager, mapping: Record<string, string>): () => void {
  const unsubscribers: (() => void)[] = []

  for (const [badgeId, eventType] of Object.entries(mapping)) {
    const handler: SSEEventHandler = (data: unknown) => {
      const payload = data as BadgeCountPayload
      const count = typeof payload.count === 'number' ? payload.count : 0

      // Update all matching badge elements
      document.querySelectorAll<HTMLElement>(`[data-badge="${badgeId}"]`).forEach(badge => {
        badge.textContent = count > 0 ? String(count) : ''

        // Toggle visibility — empty badges are hidden via CSS (.sidebar__badge:empty)
        if (count > 0) {
          badge.removeAttribute('hidden')
        }
      })
    }

    const unsub = sse.on(eventType, handler)
    unsubscribers.push(unsub)
  }

  return () => {
    unsubscribers.forEach(fn => {
      fn()
    })
  }
}

/**
 * Manually update a badge count (for non-SSE updates like after an API call).
 */
export function updateBadge(badgeId: string, count: number): void {
  document.querySelectorAll<HTMLElement>(`[data-badge="${badgeId}"]`).forEach(badge => {
    badge.textContent = count > 0 ? String(count) : ''
  })
}
