"use client";

import type { ReactElement } from "react";

import { cn } from "@/lib/utils";

const dotSizeClass = {
  sm: "size-1",
  md: "size-1.5",
  lg: "size-2",
} as const;

const gapClass = {
  sm: "gap-0.5",
  md: "gap-1",
  lg: "gap-1.5",
} as const;

export type LoadingDotsSize = keyof typeof dotSizeClass;

/**
 * 全局加载指示：三个圆点依次跳动。
 * 用于表格、卡片、区块等；完整文案请用 `label` + `showLabel` 或外层 {@link AdminLoadingState}。
 */
export function LoadingDots({
  size = "md",
  className,
  label,
  showLabel = false,
}: {
  size?: LoadingDotsSize;
  className?: string;
  /** 供屏幕阅读器；`showLabel` 为 true 时同时可见 */
  label?: string;
  showLabel?: boolean;
}): ReactElement {
  return (
    <span
      role="status"
      aria-live="polite"
      aria-busy="true"
      className={cn("inline-flex items-center", gapClass[size], className)}
    >
      {[0, 1, 2].map((index) => (
        <span
          key={index}
          aria-hidden
          className={cn(
            "rounded-full bg-current",
            dotSizeClass[size],
            "animate-loading-dot-bounce",
          )}
          style={{ animationDelay: `${index * 0.14}s` }}
        />
      ))}
      {label ? (
        <span className={showLabel ? "text-sm text-muted-foreground" : "sr-only"}>{label}</span>
      ) : null}
    </span>
  );
}
