import { forwardRef, type ButtonHTMLAttributes, type ReactNode } from "react";
import { cn } from "@/lib/cn";

type Variant = "primary" | "outline" | "ghost" | "danger";
type Size = "sm" | "md" | "lg" | "icon";

export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: Variant;
  size?: Size;
  pulse?: boolean;
  leftIcon?: ReactNode;
  rightIcon?: ReactNode;
  loading?: boolean;
}

const BASE =
  "relative inline-flex items-center justify-center gap-2 rounded font-display uppercase transition-all overflow-hidden cursor-pointer disabled:opacity-35 disabled:cursor-not-allowed disabled:pointer-events-none";

const VARIANTS: Record<Variant, string> = {
  primary:
    "bg-grad-purple text-white shadow-purple-glow hover:brightness-110 hover:-translate-y-0.5 active:brightness-95 active:translate-y-0",
  outline:
    "bg-transparent text-purple-300 border border-[var(--border-purple)] shadow-[0_0_12px_rgba(139,92,246,0.12)] hover:bg-purple-500/10 hover:shadow-[0_0_20px_rgba(139,92,246,0.3)] hover:text-purple-200",
  ghost:
    "bg-white/5 text-white/70 border border-white/14 hover:bg-white/10 hover:text-white",
  danger:
    "bg-pink-500 text-white shadow-[0_0_20px_rgba(236,72,153,0.4)] hover:brightness-110",
};

const SIZES: Record<Size, string> = {
  sm: "h-8 px-3.5 text-[10px] tracking-[1.5px]",
  md: "h-11 px-6 text-xs tracking-[2.5px]",
  lg: "h-14 px-10 text-sm tracking-[2.5px]",
  icon: "h-11 w-11 p-0 text-base tracking-normal",
};

const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button(
  {
    className,
    variant = "primary",
    size = "md",
    pulse = false,
    leftIcon,
    rightIcon,
    loading = false,
    disabled,
    children,
    ...props
  },
  ref,
) {
  return (
    <button
      ref={ref}
      disabled={disabled || loading}
      className={cn(
        BASE,
        VARIANTS[variant],
        SIZES[size],
        pulse && "animate-pulse-glow",
        className,
      )}
      {...props}
    >
      {/* 微光扫过效果 */}
      <span
        aria-hidden
        className="absolute inset-0 -translate-x-full bg-[linear-gradient(105deg,transparent_40%,rgba(255,255,255,0.06)_50%,transparent_60%)] pointer-events-none group-hover:translate-x-full transition-transform duration-700"
      />
      {loading ? (
        <svg
          className="animate-spin h-4 w-4"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2.5"
        >
          <circle cx="12" cy="12" r="10" opacity="0.25" />
          <path d="M22 12a10 10 0 0 1-10 10" />
        </svg>
      ) : (
        leftIcon
      )}
      {children && <span className="relative z-10">{children}</span>}
      {!loading && rightIcon}
    </button>
  );
});

export default Button;
