"use client"

import { useEffect, useRef, type RefObject } from "react"
import { useChromeIdentity } from "@/lib/hooks/use-chrome-identity"
import { AccountSwitcherPanel } from "@/components/suite/account-switcher-panel"
import { cn } from "@/lib/utils"

interface AccountSwitcherDropdownProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  containerRef: RefObject<HTMLElement | null>
}

export function AccountSwitcherDropdown({
  open,
  onOpenChange,
  containerRef,
}: AccountSwitcherDropdownProps) {
  const panelRef = useRef<HTMLDivElement>(null)
  const identity = useChromeIdentity()

  useEffect(() => {
    if (!open) return
    function handleClickOutside(event: MouseEvent) {
      if (
        containerRef.current &&
        !containerRef.current.contains(event.target as Node)
      ) {
        onOpenChange(false)
      }
    }
    function handleEscape(event: KeyboardEvent) {
      if (event.key === "Escape") onOpenChange(false)
    }
    document.addEventListener("mousedown", handleClickOutside)
    document.addEventListener("keydown", handleEscape)
    return () => {
      document.removeEventListener("mousedown", handleClickOutside)
      document.removeEventListener("keydown", handleEscape)
    }
  }, [open, onOpenChange, containerRef])

  if (!open || !identity) return null

  return (
    <div
      ref={panelRef}
      role="dialog"
      aria-label="Comptes connectés"
      className={cn(
        "absolute right-0 top-12 z-50 w-[min(100vw-1rem,356px)] overflow-hidden rounded-[28px] border border-border bg-[var(--suite-surface-elevated)] text-foreground shadow-[0_4px_16px_rgba(0,0,0,0.35)]",
      )}
    >
      <AccountSwitcherPanel onClose={() => onOpenChange(false)} />
    </div>
  )
}
