import React, { useEffect, useRef } from 'react';

export default function ContextMenu({ x, y, type, data, onClose, onAction }) {
  const menuRef = useRef(null);

  useEffect(() => {
    const handleClickOutside = (e) => {
      if (menuRef.current && !menuRef.current.contains(e.target)) {
        onClose?.();
      }
    };
    const handleEscape = (e) => {
      if (e.key === 'Escape') onClose?.();
    };
    
    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('keydown', handleEscape);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('keydown', handleEscape);
    };
  }, [onClose]);

  const menuItems = {
    message: [
      { id: 'add-reaction', label: 'Add Reaction', icon: '😀' },
      { divider: true },
      { id: 'reply', label: 'Reply', icon: '↩️' },
      { id: 'create-thread', label: 'Create Thread', icon: '🧵' },
      { divider: true },
      { id: 'edit', label: 'Edit Message', icon: '✏️', ownerOnly: true },
      { id: 'pin', label: 'Pin Message', icon: '📌' },
      { id: 'mark-unread', label: 'Mark Unread', icon: '📩' },
      { id: 'copy-text', label: 'Copy Text', icon: '📋' },
      { id: 'copy-link', label: 'Copy Message Link', icon: '🔗' },
      { divider: true },
      { id: 'speak', label: 'Speak Message', icon: '🔊' },
      { divider: true },
      { id: 'delete', label: 'Delete Message', icon: '🗑️', danger: true, ownerOnly: true },
      { id: 'report', label: 'Report Message', icon: '🚩', danger: true },
    ],
    user: [
      { id: 'profile', label: 'Profile', icon: '👤' },
      { id: 'mention', label: 'Mention', icon: '@' },
      { id: 'message', label: 'Message', icon: '💬' },
      { divider: true },
      { id: 'call', label: 'Call', icon: '📞' },
      { id: 'video-call', label: 'Video Call', icon: '📹' },
      { divider: true },
      { id: 'add-note', label: 'Add Note', icon: '📝' },
      { id: 'add-friend', label: 'Add Friend', icon: '👋' },
      { divider: true },
      { id: 'invite', label: 'Invite to Server', icon: '➕', submenu: true },
      { divider: true },
      { id: 'mute', label: 'Mute', icon: '🔇' },
      { id: 'block', label: 'Block', icon: '🚫', danger: true },
      { id: 'report', label: 'Report', icon: '🚩', danger: true },
    ],
    channel: [
      { id: 'mark-read', label: 'Mark As Read', icon: '✓' },
      { divider: true },
      { id: 'mute', label: 'Mute Channel', icon: '🔇', submenu: true },
      { id: 'notification-settings', label: 'Notification Settings', icon: '🔔' },
      { divider: true },
      { id: 'edit', label: 'Edit Channel', icon: '✏️' },
      { id: 'duplicate', label: 'Duplicate Channel', icon: '📋' },
      { id: 'create-invite', label: 'Create Invite', icon: '✉️' },
      { divider: true },
      { id: 'copy-link', label: 'Copy Channel Link', icon: '🔗' },
      { id: 'copy-id', label: 'Copy Channel ID', icon: '#️⃣' },
      { divider: true },
      { id: 'delete', label: 'Delete Channel', icon: '🗑️', danger: true },
    ],
    server: [
      { id: 'mark-read', label: 'Mark As Read', icon: '✓' },
      { divider: true },
      { id: 'invite-people', label: 'Invite People', icon: '👋' },
      { divider: true },
      { id: 'mute', label: 'Mute Server', icon: '🔇', submenu: true },
      { id: 'notification-settings', label: 'Notification Settings', icon: '🔔' },
      { id: 'hide-muted', label: 'Hide Muted Channels', icon: '👁️' },
      { divider: true },
      { id: 'privacy-settings', label: 'Privacy Settings', icon: '🔒' },
      { id: 'edit-nickname', label: 'Edit Server Nickname', icon: '✏️' },
      { divider: true },
      { id: 'server-settings', label: 'Server Settings', icon: '⚙️' },
      { id: 'create-channel', label: 'Create Channel', icon: '➕' },
      { id: 'create-category', label: 'Create Category', icon: '📁' },
      { divider: true },
      { id: 'copy-id', label: 'Copy Server ID', icon: '#️⃣' },
      { divider: true },
      { id: 'leave', label: 'Leave Server', icon: '🚪', danger: true },
    ],
  };

  const items = menuItems[type] || [];
  const isOwn = data?.isOwn;

  // Adjust position to stay within viewport
  const adjustedStyle = {
    position: 'fixed',
    top: y,
    left: x,
    zIndex: 10000,
  };

  return (
    <div className="context-menu" ref={menuRef} style={adjustedStyle}>
      {items.map((item, idx) => {
        if (item.divider) {
          return <div key={`divider-${idx}`} className="context-menu-divider" />;
        }
        
        if (item.ownerOnly && !isOwn) return null;

        return (
          <div
            key={item.id}
            className={`context-menu-item ${item.danger ? 'danger' : ''}`}
            onClick={() => {
              onAction?.(item.id, data);
              onClose?.();
            }}
          >
            <span className="context-menu-icon">{item.icon}</span>
            <span className="context-menu-label">{item.label}</span>
            {item.submenu && <span className="context-menu-arrow">▶</span>}
          </div>
        );
      })}
    </div>
  );
}
