// src/components/ui/Button.jsx
import { forwardRef } from 'react'
import Spinner from '@/components/ui/Spinner'

const Button = forwardRef(function Button(
  {
    variant = 'primary',
    size = 'md',
    loading = false,
    disabled = false,
    icon = null,
    iconRight = null,
    children,
    className = '',
    as: Tag = 'button',
    type = 'button',
    ...props
  },
  ref
) {
  const isDisabled = disabled || loading

  return (
    <Tag
      ref={ref}
      type={Tag === 'button' ? type : undefined}
      disabled={Tag === 'button' ? isDisabled : undefined}
      aria-disabled={isDisabled || undefined}
      aria-busy={loading || undefined}
      className={['btn', `btn-${variant}`, `btn-${size}`, className].filter(Boolean).join(' ')}
      {...props}
    >
      {loading ? (
        <Spinner size={size === 'lg' ? 'md' : 'sm'} />
      ) : icon ? (
        <span className="shrink-0 flex items-center" aria-hidden="true">{icon}</span>
      ) : null}

      {children != null && (
        <span className={loading ? 'opacity-0 absolute' : undefined}>{children}</span>
      )}

      {!loading && iconRight != null && (
        <span className="shrink-0 flex items-center" aria-hidden="true">{iconRight}</span>
      )}
    </Tag>
  )
})

export default Button
