<script lang="ts">
  // v0.2 Phase 5 primitive — native <button> + token-driven styling.
  // Replaces the ~60 ad-hoc button blocks scattered across pages with
  // one grammar (primary | secondary | tertiary | destructive × sm | md | lg).
  // Bypasses Bits UI deliberately: <button> is already accessible and
  // the headless library would only add weight here.
  import type { Snippet } from "svelte";

  type Variant = "primary" | "secondary" | "tertiary" | "destructive";
  type Size = "sm" | "md" | "lg";

  interface Props {
    variant?: Variant;
    size?: Size;
    type?: "button" | "submit" | "reset";
    disabled?: boolean;
    loading?: boolean;
    fullWidth?: boolean;
    title?: string;
    ariaLabel?: string;
    onclick?: (e: MouseEvent) => void;
    children?: Snippet;
    classes?: string;
  }

  let {
    variant = "secondary" as Variant,
    size = "md" as Size,
    type = "button",
    disabled = false,
    loading = false,
    fullWidth = false,
    title,
    ariaLabel,
    onclick,
    children,
    classes = "",
  }: Props = $props();

  const sizeClass: Record<Size, string> = {
    sm: "btn-sm",
    md: "btn-md",
    lg: "btn-lg",
  };

  // Variant palette uses semantic tokens; primary fills with --color-accent
  // (amber/copper) and pairs with .btn-filled-text for AA. Destructive
  // mirrors primary on --color-danger.
  const variantClass: Record<Variant, string> = {
    primary:
      "bg-accent btn-filled-text font-medium hover:bg-accent-hover shadow-[var(--shadow-accent-pill)]",
    secondary:
      "bg-bg-elevated text-text border border-border-subtle hover:bg-hover",
    tertiary:
      "bg-transparent text-text-secondary hover:bg-hover hover:text-text",
    destructive:
      "bg-danger btn-filled-text font-medium hover:bg-danger/90",
  };

  const busy = $derived(loading || disabled);
</script>

<button
  {type}
  class="rounded-lg font-medium select-none disabled:opacity-50 disabled:cursor-not-allowed
    {sizeClass[size]}
    {variantClass[variant]}
    {fullWidth ? 'w-full' : ''}
    {classes}"
  style="transition-duration: var(--duration-ui)"
  disabled={busy}
  aria-busy={loading ? "true" : undefined}
  aria-label={ariaLabel}
  {title}
  {onclick}
>
  {#if loading}
    <span class="inline-block animate-spin" aria-hidden="true">⟳</span>
  {/if}
  {#if children}{@render children()}{/if}
</button>
