"use client"

import { useRef, useState } from "react"
import { AccountAvatar } from "@/components/suite/account-avatar"
import { AccountSwitcherDropdown } from "@/components/suite/account-switcher-dropdown"
import { Button } from "@/components/ui/button"
import { useChromeIdentity } from "@/lib/hooks/use-chrome-identity"

export function EditorAccountButton() {
  const [open, setOpen] = useState(false)
  const containerRef = useRef<HTMLDivElement>(null)
  const identity = useChromeIdentity()

  return (
    <div className="relative" ref={containerRef}>
      <Button
        variant="ghost"
        size="icon"
        className="size-8 overflow-hidden rounded-full p-0"
        aria-label={`Compte : ${identity?.email ?? "Utilisateur"}`}
        aria-expanded={open}
        aria-haspopup="dialog"
        onClick={() => setOpen((current) => !current)}
      >
        {identity ? (
          <AccountAvatar
            account={{
              name: identity.name,
              email: identity.email,
              avatarUrl: identity.avatarUrl,
            }}
            size="sm"
          />
        ) : (
          <span className="flex size-8 items-center justify-center rounded-full bg-muted text-xs font-medium text-muted-foreground">
            ?
          </span>
        )}
      </Button>
      <AccountSwitcherDropdown
        open={open}
        onOpenChange={setOpen}
        containerRef={containerRef}
      />
    </div>
  )
}
