'use client';

import { cn } from '@djangocfg/ui-core/lib';

import type { ComposerAction, ComposerSize } from './types';

/** Per-size geometry for action-bar buttons + their icons.
 *  ChatGPT/Gemini-style — fully round, slightly larger glyphs. */
export const BUTTON_SIZE: Record<ComposerSize, { button: string; icon: string }> = {
  sm: { button: 'h-7 w-7 rounded-full', icon: '[&_svg]:size-4' },
  md: { button: 'h-9 w-9 rounded-full', icon: '[&_svg]:size-[1.125rem]' },
  lg: { button: 'h-11 w-11 rounded-full', icon: '[&_svg]:size-5' },
};

const VARIANT_CLASSES: Record<NonNullable<ComposerAction['variant']>, string> = {
  ghost: 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
  secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
  primary: 'bg-primary text-primary-foreground hover:bg-primary/90',
  // The send button is the composer's primary CTA — brand `primary`
  // token, cohesive with accent surfaces (e.g. the user bubble).
  // Disabled stays a dimmed `primary` (not neutral grey) so the button
  // is still recognisable as send against the composer surface.
  send: 'bg-primary text-primary-foreground hover:bg-primary/90 disabled:bg-primary/30 disabled:text-primary-foreground/60',
};

export interface ComposerButtonProps {
  action: ComposerAction;
  size: ComposerSize;
}

/**
 * Renders a single declarative `ComposerAction` as an icon button.
 * Centralises size, variant, aria-label, and `aria-pressed` so hosts
 * cannot misalign or under-label an action.
 */
export function ComposerButton({ action, size }: ComposerButtonProps) {
  const variant = action.variant ?? 'ghost';
  const sz = BUTTON_SIZE[size];
  const isToggle = action.pressed !== undefined;
  return (
    <button
      type="button"
      onClick={action.onClick}
      disabled={action.disabled}
      aria-label={action.label}
      title={action.label}
      aria-pressed={isToggle ? action.pressed : undefined}
      className={cn(
        'inline-flex shrink-0 cursor-pointer items-center justify-center',
        'transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
        'disabled:pointer-events-none [&_svg]:shrink-0',
        // The send variant carries its own muted disabled fill, so it
        // skips the generic opacity dim that the other variants use.
        variant === 'send' ? 'disabled:cursor-default' : 'disabled:opacity-50',
        sz.button,
        sz.icon,
        VARIANT_CLASSES[variant],
        isToggle && action.pressed && variant === 'ghost' && 'bg-accent text-accent-foreground',
      )}
    >
      {action.icon}
    </button>
  );
}
