"use client"

import { useState } from "react"
import { NavColorPicker } from "@/components/gmail/nav/nav-color-picker"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { cn } from "@/lib/utils"
import { normalizeNavColorClass } from "@/lib/nav-color"

export function NavColorPickerTrigger({
  value,
  onChange,
  rounded = "full",
  className,
  "aria-label": ariaLabel = "Couleur",
}: {
  value: string
  onChange: (swatch: string) => void
  rounded?: "sm" | "full"
  className?: string
  "aria-label"?: string
}) {
  const [open, setOpen] = useState(false)
  const colorClass = normalizeNavColorClass(value)
  const isFull = rounded === "full"

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <button
          type="button"
          aria-label={ariaLabel}
          className={cn(
            "flex shrink-0 items-center justify-center border border-black/10 outline-none ring-offset-1 hover:ring-2 hover:ring-muted-foreground focus-visible:ring-2 focus-visible:ring-ring",
            isFull ? "size-7 rounded-full p-0.5" : "size-7 rounded-sm bg-background hover:bg-muted",
            className
          )}
          onClick={(e) => e.stopPropagation()}
        >
          <span
            className={cn(
              "block border border-black/10",
              isFull ? "size-full rounded-full" : "size-4 rounded-sm",
              colorClass
            )}
            aria-hidden
          />
        </button>
      </PopoverTrigger>
      <PopoverContent className="w-auto p-2" align="start" sideOffset={6}>
        <NavColorPicker
          variant="menu"
          value={value}
          onChange={(sw) => {
            onChange(sw)
            setOpen(false)
          }}
        />
      </PopoverContent>
    </Popover>
  )
}
