import { useEffect, useRef, useState } from 'react'
import { makeStyles } from '@fluentui/react-components'
import { useDownloads, type DownloadStatus } from '../store/downloads'

const useStyles = makeStyles({
  // Visually hidden, but present for screen readers (the standard sr-only recipe).
  srOnly: {
    position: 'absolute',
    width: '1px',
    height: '1px',
    padding: 0,
    margin: '-1px',
    overflow: 'hidden',
    clip: 'rect(0, 0, 0, 0)',
    whiteSpace: 'nowrap'
  }
})

/**
 * A polite ARIA live region (W17) so Narrator announces download completions and
 * failures even when the user isn't on the Downloads tab. Subscribes to the store
 * directly and announces only terminal transitions (→ completed / error), so it
 * never chatters on progress ticks. Mounted once, near the app root.
 */
export function LiveRegion(): React.JSX.Element {
  const styles = useStyles()
  const [message, setMessage] = useState('')
  const prev = useRef<Map<string, DownloadStatus>>(new Map())

  useEffect(() => {
    function check(items: ReturnType<typeof useDownloads.getState>['items']): void {
      const announcements: string[] = []
      for (const it of items) {
        if (prev.current.get(it.id) !== it.status) {
          if (it.status === 'completed') announcements.push(`Finished downloading ${it.title}`)
          else if (it.status === 'error') announcements.push(`Download failed: ${it.title}`)
        }
      }
      prev.current = new Map(items.map((i) => [i.id, i.status]))
      if (announcements.length > 0) setMessage(announcements.join('. '))
    }
    // Seed the baseline without announcing the items already present on mount.
    prev.current = new Map(useDownloads.getState().items.map((i) => [i.id, i.status]))
    return useDownloads.subscribe((st) => check(st.items))
  }, [])

  return (
    <div className={styles.srOnly} role="status" aria-live="polite" aria-atomic="true">
      {message}
    </div>
  )
}
