import { useState, useEffect, useRef } from "react"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"

export interface NavItem {
  label: string
  href: string
  hasDropdown?: boolean
  dropdownItems?: { label: string; href: string }[]
}

export function FloatingHeader({
  title,
  subtitle,
  navItems,
}: {
  title: string
  subtitle?: string
  navItems: NavItem[]
}) {
  const [scrollY, setScrollY] = useState(0)
  const [openDropdown, setOpenDropdown] = useState<string | null>(null)
  const navContainerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const handleScroll = () => {
      setScrollY(window.scrollY)
    }
    window.addEventListener("scroll", handleScroll, { passive: true })
    return () => window.removeEventListener("scroll", handleScroll)
  }, [])

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (navContainerRef.current && !navContainerRef.current.contains(e.target as Node)) {
        setOpenDropdown(null)
      }
    }
    document.addEventListener("click", handleClickOutside)
    return () => document.removeEventListener("click", handleClickOutside)
  }, [])

  const leftNavItems = navItems.slice(0, 2)
  const rightNavItems = navItems.slice(2)

  const headerCompact = scrollY > 80
  const pillOpacity = Math.max(0, 1 - scrollY / 120)
  const pillScale = Math.max(0.9, 1 - scrollY / 800)
  const pillTranslateY = Math.min(0, -scrollY / 3)
  const flankingOpacity = Math.max(0, Math.min(1, (scrollY - 150) / 100))
  const flankingTranslateX = Math.max(0, 30 - (scrollY - 150) / 3)

  const toggleDropdown = (label: string, e: React.MouseEvent) => {
    e.stopPropagation()
    setOpenDropdown(openDropdown === label ? null : label)
  }

  const renderNavItem = (item: NavItem, position?: "left" | "right", inPill?: boolean) => (
    <div key={`${item.href}-${position || "pill"}`} className="relative">
      {item.hasDropdown ? (
        <div>
          <button
            onClick={(e) => toggleDropdown(item.label, e)}
            className="flex items-center gap-1 text-amber-200/60 hover:text-amber-100 transition-colors text-xs tracking-[0.12em] uppercase font-serif px-3 py-2"
          >
            {item.label}
            <ChevronDown
              className={cn("w-3 h-3 transition-transform duration-300", openDropdown === item.label && "rotate-180")}
            />
          </button>

          <div
            className={cn(
              "absolute top-full pt-3 z-[60]",
              "transition-all duration-300",
              position === "left" ? "left-0" : position === "right" ? "right-0" : "left-1/2 -translate-x-1/2",
              openDropdown === item.label ? "opacity-100 visible translate-y-0" : "opacity-0 invisible -translate-y-2",
            )}
          >
            <div className="bg-[#1a2222]/95 backdrop-blur-md border border-amber-900/30 rounded-lg overflow-hidden shadow-2xl min-w-[200px]">
              {item.dropdownItems?.map((dropItem) => (
                <a
                  key={dropItem.href}
                  href={dropItem.href}
                  className="block px-5 py-3 text-amber-200/60 hover:text-amber-100 hover:bg-amber-900/20 text-xs tracking-[0.1em] transition-all duration-200"
                  onClick={() => setOpenDropdown(null)}
                >
                  {dropItem.label}
                </a>
              ))}
            </div>
          </div>
        </div>
      ) : (
        <a
          href={item.href}
          className="text-amber-200/60 hover:text-amber-100 transition-colors text-xs tracking-[0.12em] uppercase font-serif px-3 py-2"
        >
          {item.label}
        </a>
      )}
    </div>
  )

  return (
    <header
      className={cn(
        "fixed top-0 left-0 right-0 z-50 transition-all duration-700 ease-out",
        headerCompact ? "py-3" : "py-6",
      )}
    >
      <div
        className={cn(
          "absolute top-0 left-0 right-0 bg-[#1f2828] backdrop-blur-md shadow-2xl shadow-black/30 transition-all duration-500 -z-10",
          headerCompact ? "h-full" : "h-0",
        )}
        style={{ opacity: headerCompact ? 1 : 0 }}
      />

      <div ref={navContainerRef} className="max-w-6xl mx-auto px-6">
        <div className="flex items-center justify-center w-full">
          <nav
            className="flex items-center gap-1 transition-all duration-300 ease-out"
            style={{
              opacity: flankingOpacity,
              transform: `translateX(-${flankingTranslateX}px)`,
              pointerEvents: flankingOpacity > 0.5 ? "auto" : "none",
            }}
          >
            {leftNavItems.map((item) => renderNavItem(item, "left"))}
          </nav>

          <div className={cn("text-center transition-all duration-700 ease-out", headerCompact ? "px-6" : "px-0")}>
            <h1
              className={cn(
                "font-serif tracking-[0.35em] text-amber-100/90 uppercase transition-all duration-700 ease-out whitespace-nowrap",
                headerCompact ? "text-lg" : "text-3xl md:text-4xl",
              )}
            >
              {title}
            </h1>
            <p
              className={cn(
                "text-amber-200/40 tracking-[0.25em] uppercase text-xs mt-2 transition-all duration-500 ease-out",
                headerCompact ? "opacity-0 h-0 mt-0 overflow-hidden" : "opacity-100",
              )}
            >
              {subtitle}
            </p>
          </div>

          <nav
            className="flex items-center gap-1 transition-all duration-300 ease-out"
            style={{
              opacity: flankingOpacity,
              transform: `translateX(${flankingTranslateX}px)`,
              pointerEvents: flankingOpacity > 0.5 ? "auto" : "none",
            }}
          >
            {rightNavItems.map((item) => renderNavItem(item, "right"))}
          </nav>
        </div>

        <div
          className="absolute left-1/2 transition-all duration-300 ease-out"
          style={{
            top: "100%",
            marginTop: "1rem",
            opacity: pillOpacity,
            transform: `translateX(-50%) scale(${pillScale}) translateY(${pillTranslateY}px)`,
            pointerEvents: pillOpacity > 0.3 ? "auto" : "none",
          }}
        >
          <nav className="flex items-center gap-2 md:gap-4 px-6 py-3 bg-[#1a2222]/60 backdrop-blur-sm rounded-full border border-amber-900/20">
            {navItems.map((item) => renderNavItem(item, undefined, true))}
          </nav>
        </div>
      </div>
    </header>
  )
}
