// Leonard's Farm: Button component

const pad = { sm: '10px 16px', md: '13px 22px', lg: '16px 30px' };
const fs = { sm: '0.9375rem', md: '1.0625rem', lg: '1.15rem' };

const variants = {
  primary: {
    background: 'var(--brand-primary)',
    color: 'var(--text-inverse)',
    border: '1px solid transparent',
    boxShadow: 'var(--shadow-sm)',
  },
  secondary: {
    background: 'var(--surface-card)',
    color: 'var(--brand-primary-dark)',
    border: '1px solid var(--border-strong)',
  },
  accent: {
    background: 'var(--brand-accent)',
    color: 'var(--green-900)',
    border: '1px solid transparent',
  },
  water: {
    background: 'var(--brand-water)',
    color: 'var(--text-inverse)',
    border: '1px solid transparent',
  },
  ghost: {
    background: 'transparent',
    color: 'var(--brand-primary-dark)',
    border: '1px solid transparent',
  },
};

// Leonard's Farm primary action button. Renders as <button> or, with href, <a>.
function Button({
  children,
  variant = 'primary',
  size = 'md',
  href,
  icon,
  iconRight,
  fullWidth = false,
  disabled = false,
  onClick,
  type = 'button',
  ...rest
}) {
  const Tag = href ? 'a' : 'button';
  const style = {
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    gap: '0.6em',
    padding: pad[size],
    fontFamily: 'var(--font-body)',
    fontSize: fs[size],
    fontWeight: 'var(--fw-semibold)',
    lineHeight: 1.1,
    whiteSpace: 'nowrap',
    borderRadius: 'var(--radius-pill)',
    cursor: disabled ? 'not-allowed' : 'pointer',
    width: fullWidth ? '100%' : 'auto',
    opacity: disabled ? 0.5 : 1,
    textDecoration: 'none',
    transition: 'transform var(--dur-fast) var(--ease-out), filter var(--dur-fast) var(--ease-out), background var(--dur-fast) var(--ease-out)',
    ...variants[variant],
  };
  const onEnter = (e) => { if (!disabled) e.currentTarget.style.filter = 'brightness(0.95)'; };
  const onLeave = (e) => { e.currentTarget.style.filter = 'none'; };
  const onDown = (e) => { if (!disabled) e.currentTarget.style.transform = 'scale(0.97)'; };
  const onUp = (e) => { e.currentTarget.style.transform = 'none'; };

  return (
    <Tag
      href={href}
      type={href ? undefined : type}
      onClick={disabled ? undefined : onClick}
      aria-disabled={disabled || undefined}
      style={style}
      onMouseEnter={onEnter}
      onMouseLeave={(e) => { onLeave(e); onUp(e); }}
      onMouseDown={onDown}
      onMouseUp={onUp}
      {...rest}
    >
      {icon && <span aria-hidden="true" style={{ display: 'inline-flex' }}>{icon}</span>}
      {children}
      {iconRight && <span aria-hidden="true" style={{ display: 'inline-flex' }}>{iconRight}</span>}
    </Tag>
  );
}

window.Button = Button;
