import { forwardRef, type ButtonHTMLAttributes, type ReactNode } from 'react';

export type IconButtonVariant = 'ghost' | 'outline' | 'primary' | 'danger';
export type IconButtonSize = 'xs' | 'sm' | 'md';

const VARIANT: Record<IconButtonVariant, string> = {
    ghost: 'text-fg hover:bg-elevated',
    outline: 'border border-border text-fg hover:bg-elevated',
    primary: 'bg-brand text-brand-fg hover:opacity-90',
    danger: 'text-danger hover:bg-elevated',
};

const SIZE: Record<IconButtonSize, string> = {
    xs: 'size-6 rounded-md',
    sm: 'size-8 rounded-md',
    md: 'size-9 rounded-lg',
};

export interface IconButtonProps
    extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'aria-label'> {
    /** Required accessible name — icon-only buttons must announce their action. */
    label: string;
    icon?: ReactNode;
    variant?: IconButtonVariant;
    size?: IconButtonSize;
}

/** Accessible icon-only button. `label` is mandatory and becomes the aria-label. */
export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(function IconButton(
    { label, icon, children, variant = 'ghost', size = 'md', className = '', type = 'button', ...rest },
    ref,
) {
    return (
        <button
            ref={ref}
            type={type}
            aria-label={label}
            className={`inline-flex items-center justify-center transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:opacity-40 disabled:pointer-events-none ${VARIANT[variant]} ${SIZE[size]} ${className}`}
            {...rest}
        >
            {icon ?? children}
        </button>
    );
});
