'use client';

import { Plus } from 'lucide-react';

import { MenuBuilder, type MenuItem } from '@djangocfg/ui-core/components';
import { cn } from '@djangocfg/ui-core/lib';

import { BUTTON_SIZE } from './ComposerButton';
import { useResolvedComposerSize } from './size-context';
import type { ComposerSize } from './types';

export interface ComposerMenuButtonProps {
  /** Declarative menu tree (see `MenuBuilder`). */
  items: MenuItem[];
  /** Omit to inherit the composer's size. */
  size?: ComposerSize;
  disabled?: boolean;
  /** Accessible label for the trigger. */
  label?: string;
  /** Trigger icon. Defaults to a `+`. */
  icon?: React.ReactNode;
}

/**
 * The composer's leading menu button — a `+` trigger that opens a
 * declarative `MenuBuilder` (ChatGPT-style: attach, tools, more).
 *
 * Drop it into `composerSlots.inlineStart` so it sits at the start of
 * the action bar. Size inherits from the composer unless set explicitly.
 */
export function ComposerMenuButton({
  items,
  size,
  disabled,
  label = 'Add files and more',
  icon,
}: ComposerMenuButtonProps) {
  const sz = BUTTON_SIZE[useResolvedComposerSize(size)];

  return (
    <MenuBuilder items={items} side="top" align="start">
      <button
        type="button"
        disabled={disabled}
        aria-label={label}
        title={label}
        className={cn(
          'inline-flex shrink-0 cursor-pointer items-center justify-center',
          'text-muted-foreground transition-colors',
          'hover:bg-accent hover:text-accent-foreground',
          'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
          'disabled:pointer-events-none disabled:opacity-50 [&_svg]:shrink-0',
          'data-[state=open]:bg-accent data-[state=open]:text-accent-foreground',
          sz.button,
          sz.icon,
        )}
      >
        {icon ?? <Plus aria-hidden />}
      </button>
    </MenuBuilder>
  );
}
