import React, { useEffect, useRef, memo, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { getFileUrl } from '../../utils/fileUtils';
import LazyImage from '../common/LazyImage';

const ProfileMenu = memo(function ProfileMenu({ isOpen, onClose, user, onSignOut }) {
    const navigate = useNavigate();
    const menuRef = useRef(null);

    const handleClickOutside = useCallback((event) => {
        if (menuRef.current && !menuRef.current.contains(event.target)) {
            onClose();
        }
    }, [onClose]);

    useEffect(() => {
        if (isOpen) {
            document.addEventListener('mousedown', handleClickOutside);
        }

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

    const handleProfileClick = useCallback(() => {
        navigate(`/profile/${user.login}`);
        onClose();
    }, [navigate, user.login, onClose]);

    const handleSignOut = useCallback(() => {
        onSignOut();
        onClose();
    }, [onSignOut, onClose]);

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-50 flex items-start justify-end p-4">
            <div className="fixed inset-0 bg-black/50" onClick={onClose} />
            <div
                ref={menuRef}
                className="relative bg-campfire-dark border border-campfire-gold/20 rounded-lg shadow-lg w-64 overflow-hidden"
            >
                <div className="p-4 border-b border-campfire-gold/20">
                    <div className="flex items-center space-x-3">
                        <LazyImage
                            src={getFileUrl(user, 'profile_picture', { thumb: '100x100' }) || '/default-avatar.png'}
                            alt={user.username}
                            className="w-10 h-10 rounded-full"
                        />
                        <div>
                            <h3 className="text-campfire-light font-semibold">{user.username}</h3>
                            <p className="text-campfire-ash text-sm">Уровень {user.level}</p>
                        </div>
                    </div>
                </div>
                <div className="py-2">
                    <button
                        onClick={handleProfileClick}
                        className="w-full px-4 py-2 text-left text-campfire-light hover:bg-campfire-gold/10 transition-colors"
                    >
                        Профиль
                    </button>
                    <button
                        onClick={handleSignOut}
                        className="w-full px-4 py-2 text-left text-campfire-light hover:bg-campfire-gold/10 transition-colors"
                    >
                        Выйти
                    </button>
                </div>
            </div>
        </div>
    );
});

export default ProfileMenu; 