import { useState, useRef, useEffect } from 'react'
import { useAuth } from '../auth/AuthProvider.tsx'
import '../styles/user-menu.css'

interface UserMenuProps {
  onOpenAuth: () => void
  onOpenSecurity: () => void
}

export function UserMenu({ onOpenAuth, onOpenSecurity }: UserMenuProps) {
  const auth = useAuth()
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!open) return
    function handleClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false)
    }
    function handleKey(e: KeyboardEvent) {
      if (e.key === 'Escape') setOpen(false)
    }
    document.addEventListener('mousedown', handleClick)
    document.addEventListener('keydown', handleKey)
    return () => {
      document.removeEventListener('mousedown', handleClick)
      document.removeEventListener('keydown', handleKey)
    }
  }, [open])

  if (!auth.configured) return null

  if (!auth.isAuthenticated) {
    return (
      <button
        className="user-menu-login-btn"
        onClick={onOpenAuth}
        title="Sign in"
      >
        Sign in
      </button>
    )
  }

  const initial = (auth.user?.email?.[0] ?? '?').toUpperCase()

  return (
    <div className="user-menu-container" ref={ref}>
      <button
        className="user-menu-avatar"
        onClick={() => setOpen(p => !p)}
        title={auth.user?.email ?? 'Account'}
        aria-label="Account menu"
        aria-expanded={open}
      >
        {initial}
      </button>

      {open && (
        <div className="user-menu-dropdown" role="menu">
          <div className="user-menu-email">{auth.user?.email}</div>
          <div className="user-menu-separator" />
          <button
            className="user-menu-item"
            onClick={() => { onOpenSecurity(); setOpen(false) }}
            role="menuitem"
          >
            Security Settings
          </button>
          <button
            className="user-menu-item user-menu-signout"
            onClick={() => { auth.signOut(); setOpen(false) }}
            role="menuitem"
          >
            Sign Out
          </button>
        </div>
      )}
    </div>
  )
}
