import { useState, useRef, useEffect } from 'react';
import { Link, NavLink, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext.jsx';
import { useConfirm } from '../context/ConfirmContext.jsx';

export default function Navbar() {
  const { isAuthenticated, isAdmin, user, logout } = useAuth();
  const confirm = useConfirm();
  const navigate = useNavigate();
  const [open, setOpen] = useState(false);
  const menuRef = useRef(null);

  // Close the dropdown on outside click or Escape.
  useEffect(() => {
    if (!open) return undefined;
    const onClick = (e) => {
      if (menuRef.current && !menuRef.current.contains(e.target)) setOpen(false);
    };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onClick);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onClick);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  const handleLogout = async () => {
    setOpen(false);
    const ok = await confirm({
      title: 'Log out?',
      message: 'You will need to sign in again to continue practicing.',
      confirmLabel: 'Log out',
      icon: '👋',
    });
    if (!ok) return;
    await logout();
    navigate('/');
  };

  const initial = (user?.name || '?').trim().charAt(0).toUpperCase();

  return (
    <nav className="navbar">
      <div className="container">
        <Link to="/" className="brand">
          <span className="brand-mark"><span>CN</span></span>
          CertsNexus
        </Link>

        <div className="nav-links">
          <NavLink to="/vendors" className="nav-link">Vendors</NavLink>
          {isAuthenticated && (
            <NavLink to="/dashboard" className="nav-link hide-sm">My Exams</NavLink>
          )}
          {isAuthenticated && !isAdmin && (
            <NavLink to="/contribute" className="nav-link hide-sm">Contribute</NavLink>
          )}
          {isAdmin && (
            <NavLink to="/admin" className="nav-link">Admin</NavLink>
          )}

          {isAuthenticated ? (
            <div className="user-menu" ref={menuRef}>
              <button
                type="button"
                className="user-trigger"
                aria-haspopup="menu"
                aria-expanded={open}
                onClick={() => setOpen((v) => !v)}
              >
                <span className="user-avatar">{initial}</span>
                <span className="hide-sm">{user.name.split(' ')[0]}</span>
                <svg className="chev" width="14" height="14" viewBox="0 0 24 24" fill="none"
                  stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="6 9 12 15 18 9" />
                </svg>
              </button>

              {open && (
                <div className="menu" role="menu">
                  <div className="menu-head">
                    <div className="nm">{user.name}</div>
                    <div className="em">{user.email}</div>
                  </div>
                  <Link to="/account" className="menu-item" role="menuitem" onClick={() => setOpen(false)}>
                    <span className="ic">👤</span> Profile
                  </Link>
                  <Link to="/account#password" className="menu-item" role="menuitem" onClick={() => setOpen(false)}>
                    <span className="ic">🔒</span> Change password
                  </Link>
                  <div className="menu-sep" />
                  <button type="button" className="menu-item danger" role="menuitem" onClick={handleLogout}>
                    <span className="ic">⏏</span> Log out
                  </button>
                </div>
              )}
            </div>
          ) : (
            <>
              <NavLink to="/login" className="nav-link">Login</NavLink>
              <Link to="/register" className="btn btn-sm">Sign up</Link>
            </>
          )}
        </div>
      </div>
    </nav>
  );
}
