import { useEffect, useRef, useState } from 'react';
import { cn } from '@/lib/cn';

export interface MenuItem {
  label: string;
  description?: string;
  icon?: React.ReactNode;
  onSelect: () => void;
  disabled?: boolean;
}

/**
 * Lightweight click-to-open menu anchored below a trigger button.
 * Closes on outside click + Escape. Use for split-action buttons.
 */
export function Menu({
  trigger,
  items,
  align = 'right',
  className,
}: {
  trigger: (open: boolean, toggle: () => void) => React.ReactNode;
  items: MenuItem[];
  align?: 'left' | 'right';
  className?: string;
}) {
  const [open, setOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => { document.removeEventListener('mousedown', onDown); document.removeEventListener('keydown', onKey); };
  }, [open]);

  return (
    <div ref={rootRef} className={cn('relative inline-block', className)}>
      {trigger(open, () => setOpen((o) => !o))}
      {open && (
        <div className={cn(
          'absolute mt-1.5 z-50 min-w-[220px] rounded-xl border border-ink-200 bg-white shadow-pop overflow-hidden',
          'animate-[backreload-slide-in_120ms_ease-out]',
          align === 'right' ? 'right-0' : 'left-0',
        )}>
          <ul className="py-1" role="menu">
            {items.map((it, i) => (
              <li key={i}>
                <button
                  type="button"
                  disabled={it.disabled}
                  onClick={() => { if (!it.disabled) { it.onSelect(); setOpen(false); } }}
                  className={cn(
                    'w-full !justify-start flex items-start gap-2.5 px-3 py-2 text-left',
                    'hover:bg-ink-50 disabled:opacity-40 disabled:hover:bg-transparent disabled:cursor-not-allowed',
                  )}
                >
                  {it.icon && <span className="h-5 w-5 grid place-items-center rounded-md bg-brand-50 text-brand-700 mt-0.5 shrink-0">{it.icon}</span>}
                  <span className="flex-1 min-w-0">
                    <span className="block text-sm font-medium text-ink-900">{it.label}</span>
                    {it.description && <span className="block text-[11px] text-ink-500 mt-0.5">{it.description}</span>}
                  </span>
                </button>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}
