"use client";

import type { ButtonHTMLAttributes, ReactNode } from "react";
import { FOCUS_RING } from "./focus-ring";
import { HEADER_CHROME } from "./header-button";

// Global button component mirroring the iOS button design.
//
// Seven visual variants (primary, pro-special, secondary, neutral, tertiary,
// ghost, destructive) crossed with four sizes (large / small full-width,
// rounded content-width pill, header pill). Disabled is a styling-only state — the underlying
// <button> still receives the `disabled` attribute so it's not interactive.
//
// Destructive deviates from the outdated iOS spec: filled negative colour
// instead of outline, with a reduced-alpha fill for disabled.

export type ButtonVariant =
  | "primary"
  | "pro-special"
  | "secondary"
  | "neutral"
  | "tertiary"
  | "ghost"
  | "destructive";

export type ButtonSize = "large" | "small" | "rounded" | "header";

type Props = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "type"> & {
  variant?: ButtonVariant;
  size?: ButtonSize;
  /** Defaults to "button" so it doesn't accidentally submit ancestor forms. */
  type?: "button" | "submit" | "reset";
  leadingIcon?: ReactNode;
  trailingIcon?: ReactNode;
  /**
   * The button's action is in flight. Disables the button (swallowing
   * re-entrant taps) and sets `aria-busy`, keeping the label visible. Pair
   * with the `busy` flag from `useSingleFlight` (`@enode/core`) so a slow
   * async `onClick` can't be double-fired.
   */
  busy?: boolean;
};

// Variant → static class string. Each branch covers the default + disabled
// state. We rely on `disabled:` variants rather than reading the prop in JS
// so the styling matches whatever `disabled` Tailwind sees on the element.
//
// `destructive` is a soft outlined red — light red wash + thin red ring +
// red text — matching iOS's "Delete" affordance. Use anywhere a negative
// action needs to read as dangerous without shouting.
// Every variant also carries an `active:` pressed state. On touch (where
// `hover:` never shows) this is the only immediate acknowledgment a tap gets —
// CSS :active paints even while the main thread is about to be blocked by the
// tap's work, which is what stops users from tapping again on a slow frame.
const variantClasses: Record<ButtonVariant, string> = {
  primary:
    "bg-foreground-red-orange text-white hover:opacity-90 active:opacity-75 disabled:bg-foreground-red-orange/40 disabled:hover:opacity-100",
  "pro-special":
    "bg-foreground-platinum-green text-white hover:opacity-90 active:opacity-75 disabled:bg-foreground-platinum-green-disabled disabled:text-white/70 disabled:hover:opacity-100",
  // The header chrome (header-button.tsx): a page or drawer head's labelled
  // non-primary action.
  secondary: HEADER_CHROME,
  neutral:
    "bg-surface-base-muted text-foreground-default hover:opacity-90 active:opacity-75 disabled:bg-surface-base-muted/50 disabled:text-foreground-muted disabled:hover:opacity-100",
  tertiary:
    "bg-transparent text-foreground-default ring-1 ring-inset ring-foreground-default hover:bg-surface-base-muted active:bg-surface-base-muted disabled:text-foreground-muted disabled:ring-foreground-muted disabled:hover:bg-transparent",
  // Plain text, no border/fill, with a gray pill hover — matches the tracking
  // app's Group/Edit actions in the workout multi-select pill.
  ghost:
    "bg-transparent text-foreground-default hover:bg-surface-base-muted active:bg-surface-base-muted disabled:text-foreground-muted disabled:hover:bg-transparent",
  destructive:
    "bg-feedback-error-surface text-feedback-error ring-1 ring-inset ring-feedback-error/30 hover:opacity-90 active:opacity-75 disabled:opacity-50 disabled:hover:opacity-100",
};

const sizeClasses: Record<ButtonSize, string> = {
  large: "clickable-large w-full rounded-2xl px-6 py-3.5",
  small: "clickable-small w-full rounded-xl px-5 py-2.5",
  rounded: "clickable-small rounded-full px-4 py-2",
  // 40 px tall, level with the head's icon buttons (header-button.tsx).
  header: "clickable-small h-10 shrink-0 whitespace-nowrap rounded-full px-4",
};

/**
 * Design-system button mirroring the iOS button design.
 *
 * @remarks
 * Seven visual {@link ButtonVariant}s crossed with four {@link ButtonSize}s.
 * In a page or drawer head use only `primary` / `secondary` with size
 * `header` (see `header-button.tsx`).
 * `disabled` is styling-only but still forwards the native `disabled` attribute,
 * so disabled buttons are genuinely non-interactive. `busy` marks an in-flight
 * async action: it disables the button (so a second tap can't re-fire the
 * handler) and sets `aria-busy` while keeping the label readable. Defaults to
 * `type="button"` so it never accidentally submits an ancestor form. Extra
 * `<button>` attributes (e.g. `onClick`, `aria-*`) pass straight through.
 * Colours come from design tokens — see the design-system stylesheet.
 */
export function Button({
  type = "button",
  variant = "primary",
  size = "large",
  leadingIcon,
  trailingIcon,
  busy = false,
  className,
  children,
  ...rest
}: Props) {
  return (
    <button
      type={type}
      aria-busy={busy || undefined}
      className={`inline-flex items-center justify-center gap-2 disabled:cursor-not-allowed ${variant === "secondary" ? "" : `transition-opacity ${FOCUS_RING}`} ${variantClasses[variant]} ${sizeClasses[size]} ${className ?? ""}`}
      {...rest}
      disabled={busy || rest.disabled}
    >
      {leadingIcon}
      <span>{children}</span>
      {trailingIcon}
    </button>
  );
}
