'use client';

import { useRef, useEffect } from 'react';

export interface DropdownMenuItem {
  label: string;
  onClick: () => void;
  danger?: boolean;
}

interface ChatDropdownMenuProps {
  items: DropdownMenuItem[];
  isOpen: boolean;
  onClose: () => void;
}

export function ChatDropdownMenu({ items, isOpen, onClose }: ChatDropdownMenuProps) {
  const menuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!isOpen) return;

    const handleClickOutside = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        onClose();
      }
    };

    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };

    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('keydown', handleEscape);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('keydown', handleEscape);
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  return (
    <div
      ref={menuRef}
      className="absolute right-0 top-full mt-1 bg-white border border-[#00293d]/10 rounded-[10px] shadow-lg z-50 min-w-[200px] py-1 overflow-hidden"
    >
      {items.map((item, index) => (
        <button
          key={index}
          onClick={() => {
            item.onClick();
            onClose();
          }}
          className={`w-full text-left px-4 py-2.5 font-serif font-normal text-[14px] leading-[19px] transition-colors cursor-pointer ${
            item.danger
              ? 'text-red-600 hover:bg-red-50'
              : 'text-[#00293D] hover:bg-[#00293d]/5'
          }`}
        >
          {item.label}
        </button>
      ))}
    </div>
  );
}
