"use client"

import * as React from "react"

export interface AnnounceOptions {
  /** 通知的礼貌级别，默认 polite */
  politeness?: "polite" | "assertive"
  /** 自动清除的超时时间（毫秒），0 表示不清除，默认 5000 */
  clearAfter?: number
}

export interface UseAriaLiveReturn {
  /** 播报一条消息到 aria-live 区域 */
  announce: (message: string, options?: AnnounceOptions) => void
  /** 渲染到页面中的 aria-live 区域（放在组件树根部即可） */
  liveRegion: React.ReactNode
}

/**
 * 管理 aria-live 区域的 Hook。
 * - 支持 polite / assertive 两种模式
 * - 自动清除过期通知（可配置超时）
 * - 用于表单提交结果、数据加载状态、错误提示
 */
export function useAriaLive(
  defaultOptions?: AnnounceOptions
): UseAriaLiveReturn {
  const [politeMessage, setPoliteMessage] = React.useState("")
  const [assertiveMessage, setAssertiveMessage] = React.useState("")
  const [politeKey, setPoliteKey] = React.useState(0)
  const [assertiveKey, setAssertiveKey] = React.useState(0)
  const timeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)

  const announce = React.useCallback(
    (message: string, options?: AnnounceOptions) => {
      const politeness =
        options?.politeness ?? defaultOptions?.politeness ?? "polite"
      const clearAfter =
        options?.clearAfter ?? defaultOptions?.clearAfter ?? 5000

      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current)
        timeoutRef.current = null
      }

      if (politeness === "assertive") {
        setAssertiveMessage(message)
        setAssertiveKey((k) => k + 1)
      } else {
        setPoliteMessage(message)
        setPoliteKey((k) => k + 1)
      }

      if (clearAfter > 0) {
        timeoutRef.current = setTimeout(() => {
          setPoliteMessage("")
          setAssertiveMessage("")
          timeoutRef.current = null
        }, clearAfter)
      }
    },
    [defaultOptions]
  )

  React.useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current)
      }
    }
  }, [])

  const liveRegion = React.createElement(
    React.Fragment,
    null,
    React.createElement(
      "div",
      {
        key: `polite-${politeKey}`,
        "aria-live": "polite",
        "aria-atomic": "true",
        className: "sr-only",
      },
      politeMessage
    ),
    React.createElement(
      "div",
      {
        key: `assertive-${assertiveKey}`,
        "aria-live": "assertive",
        "aria-atomic": "true",
        className: "sr-only",
      },
      assertiveMessage
    )
  )

  return { announce, liveRegion }
}
