import type { ReactNode } from 'react';
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';

export type Container = HTMLElement | null | undefined;

export type DropdownMenuRootProps = DropdownMenuPrimitive.MenuContentProps &
  Pick<DropdownMenuPrimitive.DropdownMenuProps, 'onOpenChange' | 'modal'> & {
    children: ReactNode;
    content: ReactNode;
    alignContent?: 'start' | 'center' | 'end';
    disabled?: boolean;
    container?: Container;
  };

export function DropdownMenuRoot({
  children,
  content,
  alignContent = 'center',
  disabled,
  onOpenChange,
  container,
  modal,
  ...delegated
}: DropdownMenuRootProps) {
  const contentProps = {
    align: alignContent,
    sideOffset: 5,
    className: 'c-dropdown-menu-content',
    children: content,
    ...delegated,
  };

  return (
    <DropdownMenuPrimitive.Root onOpenChange={onOpenChange} modal={modal}>
      <DropdownMenuPrimitive.Trigger disabled={disabled} asChild className="c-dropdown-menu-trigger">
        {children}
      </DropdownMenuPrimitive.Trigger>
      {container === null ? (
        <DropdownMenuPrimitive.Content {...contentProps} />
      ) : (
        <DropdownMenuPrimitive.Portal container={container}>
          <DropdownMenuPrimitive.Content {...contentProps} />
        </DropdownMenuPrimitive.Portal>
      )}
    </DropdownMenuPrimitive.Root>
  );
}
