/**
 * MemberContextMenu — right-click menu for a user in the member list.
 * Offers View Profile, Mention, and (for admins) Manage Roles. Matches
 * the new UI's layout, reusing `ChannelListContextMenu.module.css` so
 * both context menus share a consistent visual system.
 */
import { useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
import { At, PencilSimple, ShieldStar, User as UserIcon } from '@phosphor-icons/react';
import styles from '../layout/ChannelListContextMenu.module.css';

interface MemberContextMenuProps {
	x: number;
	y: number;
	onViewProfile: () => void;
	onMention: () => void;
	onChangeNickname?: () => void;
	onManageRoles?: () => void;
	onClose: () => void;
}

export function MemberContextMenu({
	x,
	y,
	onViewProfile,
	onMention,
	onChangeNickname,
	onManageRoles,
	onClose,
}: MemberContextMenuProps) {
	const ref = useRef<HTMLDivElement>(null);

	useEffect(() => {
		const handleClick = (e: MouseEvent) => {
			if (ref.current && !ref.current.contains(e.target as Node)) {
				onClose();
			}
		};
		const handleEscape = (e: KeyboardEvent) => {
			if (e.key === 'Escape') onClose();
		};
		document.addEventListener('mousedown', handleClick);
		document.addEventListener('keydown', handleEscape);
		return () => {
			document.removeEventListener('mousedown', handleClick);
			document.removeEventListener('keydown', handleEscape);
		};
	}, [onClose]);

	const style: React.CSSProperties = {
		top: Math.min(y, window.innerHeight - 140),
		left: Math.min(x, window.innerWidth - 200),
	};

	return createPortal(
		<div className={styles.overlay}>
			<div className={styles.menu} ref={ref} style={style}>
				<button className={styles.menuItem} onClick={onViewProfile}>
					<UserIcon size={18} weight="fill" />
					<span>View Profile</span>
				</button>
				<button className={styles.menuItem} onClick={onMention}>
					<At size={18} weight="bold" />
					<span>Mention</span>
				</button>
				{(onChangeNickname || onManageRoles) && (
					<div className={styles.separator} />
				)}
				{onChangeNickname && (
					<button className={styles.menuItem} onClick={onChangeNickname}>
						<PencilSimple size={18} weight="fill" />
						<span>Change Nickname</span>
					</button>
				)}
				{onManageRoles && (
					<button className={styles.menuItem} onClick={onManageRoles}>
						<ShieldStar size={18} weight="fill" />
						<span>Manage Roles</span>
					</button>
				)}
			</div>
		</div>,
		document.body,
	);
}
