"use client"

import * as React from "react"
import { cn } from "@/lib/utils"

function DropdownMenu({ children }: { children: React.ReactNode }) {
  const [open, setOpen] = React.useState(false)
  const ref = React.useRef<HTMLDivElement>(null)

  React.useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false)
    }
    if (open) document.addEventListener("mousedown", handleClick)
    return () => document.removeEventListener("mousedown", handleClick)
  }, [open])

  return (
    <div ref={ref} className="relative inline-block">
      {React.Children.map(children, (child) => {
        if (React.isValidElement<{ onClick?: () => void }>(child) && (child.type as { displayName?: string }).displayName === "DropdownMenuTrigger") {
          return React.cloneElement(child, { onClick: () => setOpen(!open) })
        }
        if (React.isValidElement<{ className?: string }>(child) && (child.type as { displayName?: string }).displayName === "DropdownMenuContent") {
          return open ? React.cloneElement(child, { className: cn(child.props.className) }) : null
        }
        return child
      })}
    </div>
  )
}

const DropdownMenuTrigger = React.forwardRef<HTMLButtonElement, React.ButtonHTMLAttributes<HTMLButtonElement>>(
  ({ children, ...props }, ref) => (
    <button ref={ref} type="button" {...props}>{children}</button>
  )
)
DropdownMenuTrigger.displayName = "DropdownMenuTrigger"

function DropdownMenuContent({ children, className, align = "end" }: { children: React.ReactNode; className?: string; align?: "start" | "end" }) {
  return (
    <div className={cn(
      "absolute z-50 min-w-[180px] overflow-hidden rounded-lg border bg-white p-1.5 shadow-lg animate-scale-in",
      align === "end" ? "right-0" : "left-0",
      "top-full mt-1",
      className
    )}>
      {children}
    </div>
  )
}
DropdownMenuContent.displayName = "DropdownMenuContent"

function DropdownMenuItem({ children, className, onClick, destructive }: { children: React.ReactNode; className?: string; onClick?: () => void; destructive?: boolean }) {
  return (
    <button
      onClick={onClick}
      className={cn(
        "flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium transition-colors",
        destructive ? "text-danger-red hover:bg-danger-red/10" : "text-foreground hover:bg-muted",
        className
      )}
    >
      {children}
    </button>
  )
}

function DropdownMenuSeparator() {
  return <div className="my-1 h-px bg-border" />
}

export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator }
