import type { HTMLAttributes, ReactNode } from 'react';

const ARIA_LIVE_ROLE_MAP = {
  assertive: 'alert',
  polite: 'status',
} as const;

export type AriaLive = 'off' | 'polite' | 'assertive';

export interface LiveRegionProps extends Omit<
  HTMLAttributes<HTMLDivElement>,
  'role' | 'aria-live' | 'aria-atomic'
> {
  /**
   * Determines urgency: 'assertive' interrupts, 'polite' waits for idle, 'off' disables live region.
   */
  'aria-live': AriaLive;
  /** Test ID for testing tools */
  'data-testid'?: string;
  children?: ReactNode;
}

/**
 * Renders an ARIA live region with the correct implicit role.
 *
 * - `aria-live="polite"` → `role="status"`
 * - `aria-live="assertive"` → `role="alert"`
 * - `aria-live="off"` → no live region
 *
 * The `role` prop is intentionally excluded from the public API
 * to prevent mismatches between `aria-live` and `role`.
 */
export const LiveRegion = ({ 'aria-live': ariaLive, children, ...props }: LiveRegionProps) => {
  if (ariaLive === 'off') {
    return <>{children}</>;
  }

  return (
    <div
      role={ARIA_LIVE_ROLE_MAP[ariaLive]}
      aria-live={ariaLive}
      aria-atomic="true"
      style={{ display: 'contents' }}
      {...props}
    >
      {children}
    </div>
  );
};
