'use client'

import { forwardRef, type ButtonHTMLAttributes, type ReactNode } from 'react'
import { cn } from '@/lib/utils'
import { Loader2 } from 'lucide-react'

/**
 * Forge Button — implements DESIGN.md §4.Button
 *
 * Variants
 *  - primary : main CTA (indigo)
 *  - secondary : framed neutral
 *  - ghost : minimal, inline action
 *  - danger : destructive outline (coral)
 *
 * Sizes (DESIGN.md heights)
 *  - sm : 32px
 *  - md : 36px (default)
 *  - lg : 40px
 */

export type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger'
export type ButtonSize = 'sm' | 'md' | 'lg'

export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: ButtonVariant
  size?: ButtonSize
  loading?: boolean
  leftIcon?: ReactNode
  rightIcon?: ReactNode
  fullWidth?: boolean
}

const variantClasses: Record<ButtonVariant, string> = {
  primary: cn(
    'bg-brand-primary text-on-primary border border-transparent',
    'hover:bg-brand-primary-hover hover:-translate-y-px active:bg-brand-primary-active active:scale-[0.97]',
    'shadow-minimal',
  ),
  secondary: cn(
    'bg-surface-2 text-ink border border-hairline',
    'hover:bg-surface-3 hover:border-hairline-strong hover:-translate-y-px active:bg-surface-4 active:scale-[0.97]',
  ),
  ghost: cn(
    'bg-transparent text-ink-muted border border-transparent',
    'hover:bg-surface-2 hover:text-ink hover:-translate-y-px active:bg-surface-3 active:scale-[0.97]',
  ),
  danger: cn(
    'bg-transparent text-accent-danger border border-accent-danger/60',
    'hover:bg-accent-danger/10 hover:border-accent-danger hover:-translate-y-px active:bg-accent-danger/20 active:scale-[0.97]',
  ),
}

const sizeClasses: Record<ButtonSize, string> = {
  sm: 'h-8 px-3 text-[12px] gap-1.5 rounded-control',
  md: 'h-9 px-3.5 text-[13px] gap-2 rounded-control',
  lg: 'h-10 px-4 text-[13px] gap-2 rounded-panel',
}

export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button(
  {
    variant = 'secondary',
    size = 'md',
    loading = false,
    leftIcon,
    rightIcon,
    fullWidth = false,
    disabled,
    className,
    children,
    type = 'button',
    ...rest
  },
  ref,
) {
  const isDisabled = disabled || loading
  return (
    <button
      ref={ref}
      type={type}
      disabled={isDisabled}
      className={cn(
        'inline-flex items-center justify-center font-medium select-none',
        'transition-[background-color,transform,box-shadow,opacity] duration-150',
        'focus:outline-none focus-visible:shadow-focus-ring',
        'disabled:opacity-50 disabled:cursor-not-allowed disabled:pointer-events-none',
        variantClasses[variant],
        sizeClasses[size],
        fullWidth && 'w-full',
        className,
      )}
      {...rest}
    >
      {loading ? <Loader2 size={size === 'sm' ? 12 : 14} className="animate-spin" /> : leftIcon}
      {children}
      {!loading && rightIcon}
    </button>
  )
})
