/**
 * useAriaLive - aria-live 区域管理
 *
 * 用途：动态向 aria-live 区域推送消息，供屏幕阅读器播报。
 * 迁移自 CICD 项目 A11y 工具集。
 *
 * @example
 * const { message, announce } = useAriaLive();
 * announce("表单提交成功", "polite");
 * // 渲染：<div aria-live="polite">{message}</div>
 */

import { useCallback, useState } from "react";

export type AriaLivePoliteness = "polite" | "assertive" | "off";

export interface UseAriaLiveReturn {
  /** 当前消息内容 */
  message: string;
  /** 当前 politeness 级别 */
  politeness: AriaLivePoliteness;
  /** 推送消息 */
  announce: (message: string, politeness?: AriaLivePoliteness) => void;
  /** 清除消息 */
  clear: () => void;
}

export function useAriaLive(): UseAriaLiveReturn {
  const [message, setMessage] = useState("");
  const [politeness, setPoliteness] = useState<AriaLivePoliteness>("polite");

  const announce = useCallback(
    (msg: string, level: AriaLivePoliteness = "polite"): void => {
      setPoliteness(level);
      // 先清空再设置，确保相同消息也能触发播报
      setMessage("");
      requestAnimationFrame(() => setMessage(msg));
    },
    [],
  );

  const clear = useCallback((): void => {
    setMessage("");
  }, []);

  return {
    message,
    politeness,
    announce,
    clear,
  };
}
