---
export interface Props {
	variant?: "primary" | "secondary" | "outline" | "ghost" | "danger";
	size?: "sm" | "md" | "lg";
	type?: "button" | "submit" | "reset";
	disabled?: boolean;
	loading?: boolean;
	fullWidth?: boolean;
	href?: string;
	class?: string;
}

const {
	variant = "primary",
	size = "md",
	type = "button",
	disabled = false,
	loading = false,
	fullWidth = false,
	href,
	class: className = "",
	...attrs
} = Astro.props;

const baseStyles =
	"inline-flex items-center justify-center font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed";

const variants: Record<string, string> = {
	primary: "bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500",
	secondary: "bg-gray-600 text-white hover:bg-gray-700 focus:ring-gray-500",
	outline:
		"border-2 border-gray-300 text-gray-700 hover:bg-gray-50 focus:ring-gray-500",
	ghost: "text-gray-700 hover:bg-gray-100 focus:ring-gray-500",
	danger: "bg-red-600 text-white hover:bg-red-700 focus:ring-red-500",
};

const sizes: Record<string, string> = {
	sm: "px-3 py-1.5 text-sm gap-1.5",
	md: "px-4 py-2 text-base gap-2",
	lg: "px-6 py-3 text-lg gap-2.5",
};

const classes = [
	baseStyles,
	variants[variant],
	sizes[size],
	fullWidth ? "w-full" : "",
	className,
]
	.filter(Boolean)
	.join(" ");

const Tag = href ? "a" : "button";
---

{href ? (
  <a class={classes} href={href} {...attrs}>
    {loading && (
      <svg class="animate-spin h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
      </svg>
    )}
    <slot />
  </a>
) : (
  <button class={classes} type={type} disabled={disabled || loading} aria-disabled={disabled || loading} {...attrs}>
    {loading && (
      <svg class="animate-spin h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
      </svg>
    )}
    <slot />
  </button>
)}
