'use client'
import React from 'react'

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

interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: ButtonVariant
  size?: ButtonSize
  loading?: boolean
  children: React.ReactNode
}

const variantStyles: Record<ButtonVariant, React.CSSProperties> = {
  primary: {
    background: 'var(--accent)',
    color: 'var(--paper)',
    border: 'none',
  },
  secondary: {
    background: 'var(--bg-warm)',
    color: 'var(--fg)',
    border: '1.5px solid var(--cream)',
  },
  danger: {
    background: '#c0392b',
    color: 'var(--paper)',
    border: 'none',
  },
  ghost: {
    background: 'transparent',
    color: 'var(--fg)',
    border: '1.5px solid var(--cream)',
  },
}

const sizeStyles: Record<ButtonSize, React.CSSProperties> = {
  sm: {
    fontSize: 'var(--t-small)',
    padding: 'var(--s-2) var(--s-3)',
    minHeight: '36px',
    borderRadius: 'var(--r-sm)',
  },
  md: {
    fontSize: 'var(--t-body)',
    padding: 'var(--s-2) var(--s-5)',
    minHeight: '44px',
    borderRadius: 'var(--r-md)',
  },
  lg: {
    fontSize: 'var(--t-lead)',
    padding: 'var(--s-3) var(--s-6)',
    minHeight: '52px',
    borderRadius: 'var(--r-lg)',
  },
}

export function Button({
  variant = 'primary',
  size = 'md',
  loading = false,
  disabled,
  children,
  style,
  ...rest
}: ButtonProps) {
  return (
    <button
      disabled={disabled ?? loading}
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        gap: 'var(--s-2)',
        fontFamily: 'var(--font-sans)',
        fontWeight: 500,
        cursor: disabled ?? loading ? 'not-allowed' : 'pointer',
        opacity: disabled ?? loading ? 0.6 : 1,
        transition: 'opacity 150ms, transform 100ms',
        ...variantStyles[variant],
        ...sizeStyles[size],
        ...style,
      }}
      {...rest}
    >
      {loading ? (
        <>
          <Spinner />
          {children}
        </>
      ) : (
        children
      )}
    </button>
  )
}

function Spinner() {
  return (
    <span
      style={{
        width: '16px',
        height: '16px',
        border: '2px solid currentColor',
        borderTopColor: 'transparent',
        borderRadius: '50%',
        display: 'inline-block',
        animation: 'spin 0.7s linear infinite',
      }}
    />
  )
}
