import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';

export default function ProfileDropdown({ displayName, avatarUrl, initial, onSignOut }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const navigate = useNavigate();

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onClick = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    };
    window.addEventListener('mousedown', onClick);
    return () => window.removeEventListener('mousedown', onClick);
  }, [open]);

  return (
    <div className="profile-dropdown" ref={ref}>
      <button className="profile-dropdown__trigger" onClick={() => setOpen(o => !o)}>
        {avatarUrl
          ? <img className="dash-nav__avatar" src={avatarUrl} alt={displayName} referrerPolicy="no-referrer" />
          : <div className="dash-nav__avatar dash-nav__avatar--fallback">{initial}</div>
        }
        <span className="dash-nav__name">{displayName}</span>
      </button>

      {open && (
        <div className="profile-dropdown__menu">
          <div className="profile-dropdown__user">
            {avatarUrl
              ? <img className="profile-dropdown__avatar" src={avatarUrl} alt={displayName} referrerPolicy="no-referrer" />
              : <div className="profile-dropdown__avatar profile-dropdown__avatar--fallback">{initial}</div>
            }
            <span className="profile-dropdown__name">{displayName}</span>
          </div>
          <div className="profile-dropdown__divider" />
          <button className="profile-dropdown__item" onClick={() => { setOpen(false); navigate('/settings'); }}>
            Settings
          </button>
          <button className="profile-dropdown__item profile-dropdown__item--danger" onClick={onSignOut}>
            Sign out
          </button>
        </div>
      )}
    </div>
  );
}
