"use client"

import Link from "next/link"
import { OptimizedImage } from "@/components/optimized-image"
import { Button } from "@/components/ui/button"
import { Menu } from "lucide-react"
import { useState, useEffect } from "react"
import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "@/components/ui/sheet"
import { motion } from "framer-motion"
import { VisuallyHidden } from "@radix-ui/react-visually-hidden"
import { usePathname } from "next/navigation"
import { BookingDialog } from "@/components/booking-dialog"

export function Header() {
  const pathname = usePathname()
  const [isOpen, setIsOpen] = useState(false)
  const [isScrolled, setIsScrolled] = useState(false)
  const [mounted, setMounted] = useState(false)
  const [isLargeScreen, setIsLargeScreen] = useState(false)
  const [bookingDialogOpen, setBookingDialogOpen] = useState(false)

  useEffect(() => {
    // Set initial scroll state on mount
    setIsScrolled(window.scrollY > 20)
    setMounted(true)

    // Check screen size
    const checkScreenSize = () => {
      setIsLargeScreen(window.innerWidth >= 1024) // lg breakpoint
    }

    checkScreenSize()

    const handleScroll = () => {
      setIsScrolled(window.scrollY > 20)
    }

    window.addEventListener("scroll", handleScroll)
    window.addEventListener("resize", checkScreenSize)
    return () => {
      window.removeEventListener("scroll", handleScroll)
      window.removeEventListener("resize", checkScreenSize)
    }
  }, [])

  // Handle scroll to room section on page load if hash is present
  useEffect(() => {
    if (window.location.hash === '#room') {
      setTimeout(() => {
        const roomSection = document.getElementById('room')
        if (roomSection) {
          roomSection.scrollIntoView({ behavior: 'smooth', block: 'start' })
        }
      }, 100)
    }
  }, [pathname])

  // Handle Book Now click
  const handleBookNowClick = () => {
    if (pathname === '/') {
      // On homepage, scroll to room section
      const roomSection = document.getElementById('room')
      if (roomSection) {
        roomSection.scrollIntoView({ behavior: 'smooth', block: 'start' })
      }
    } else {
      // On other pages, navigate to homepage with hash
      window.location.href = '/#room'
    }
  }

  const navItems = [
    { name: "Home", href: "/" },
    { name: "About Us", href: "/about" },
    { name: "Apartments", href: "/apartments" },
    { name: "Facilities & Experiences", href: "/facilities" },
    { name: "Gallery", href: "/gallery" },
    { name: "Contact", href: "/contact" },
  ]

  // Calculate padding based on screen size and scroll state
  const getPadding = () => {
    if (isLargeScreen) {
      // Large screen: always 1rem
      return "0rem"
    } else {
      // Mobile: 0.5rem not scrolled, 0rem scrolled
      return isScrolled ? "0rem" : "0.7rem"
    }
  }

  return (
    <motion.header
      className="fixed top-0 left-0 right-0 z-50 pt-4"
      initial={{
        paddingLeft: "0.5rem",
        paddingRight: "0.5rem",
        paddingTop: "0.5rem",
      }}
      animate={{
        paddingLeft: getPadding(),
        paddingRight: getPadding(),
        paddingTop: isScrolled ? "0rem" : "0.6rem"
      }}
      transition={mounted ? { duration: 0.3, ease: "easeInOut" } : { duration: 0 }}
    >
      <motion.div
        className="bg-white/95 backdrop-blur-sm shadow-sm mx-auto"
        style={{ boxShadow: "0 1px 3px rgba(0, 0, 0, 0.05)" }}
        initial={{
          borderRadius: "9999px",
          maxWidth: "60rem",
        }}
        animate={{
          borderRadius: isScrolled ? "0px" : "9999px",
          maxWidth: isScrolled ? "100%" : "60rem",
        }}
        transition={mounted ? { duration: 0.3, ease: "easeInOut" } : { duration: 0 }}
      >
        <div className={`flex items-center justify-between h-15 ${isScrolled ? 'px-2 md:px-16' : 'px-3'}`}>
          {/* Logo */}
          <Link href="/" className="flex items-center gap-1">
            <div className="w-11 h-11 relative">
              <OptimizedImage src="/logo.svg" alt="Alegre Farms Logo" fill className="object-contain" />
            </div>
            <div className="flex flex-col">
              <span className="text-lg font-bold leading-tight whitespace-nowrap" style={{ color: "#0D8B4D" }}>
                Alegre Integrated
              </span>
              <span className="text-[0.8rem] font-medium leading-tight whitespace-nowrap" style={{ color: "#F59E0B" }}>
                Farm and Resort
              </span>
            </div>
          </Link>

          {/* Desktop Navigation */}
          <nav className="hidden lg:flex items-center gap-6">
            {navItems.map((item) => {
              const isActive = pathname === item.href
              return (
                <Link
                  key={item.name}
                  href={item.href}
                  className="text-[0.72rem] font-semibold transition-colors hover:text-[#0D8B4D] whitespace-nowrap"
                  style={{ color: isActive ? "#0D8B4D" : "#374151" }}
                >
                  {item.name}
                </Link>
              )
            })}
          </nav>

          {/* CTA Button */}
          <div className="hidden lg:block">
            <Button
              onClick={handleBookNowClick}
              className="rounded-full px-8 py-5 font-semibold hover:opacity-90 transition-opacity text-[0.73rem]"
              style={{ backgroundColor: "#0D8B4D", color: "white" }}
            >
              Book Now
            </Button>
          </div>

          {/* Mobile Menu */}
          <Sheet open={isOpen} onOpenChange={setIsOpen}>
            <SheetTrigger asChild className="lg:hidden">
              <Button variant="ghost" size="icon">
                <Menu className="h-6 w-6" />
              </Button>
            </SheetTrigger>
            <SheetContent>
               <VisuallyHidden>
      <SheetTitle>Mobile Navigation Menu</SheetTitle>
    </VisuallyHidden>
              <nav className="flex flex-col gap-8 mt-8 px-6">
                {navItems.map((item) => {
                  const isActive = pathname === item.href
                  return (
                    <Link
                      key={item.name}
                      href={item.href}
                      onClick={() => setIsOpen(false)}
                      className="text-3xl font-medium transition-colors"
                      style={{ color: isActive ? "#0D8B4D" : "inherit" }}
                    >
                      {item.name}
                    </Link>
                  )
                })}
                <Button
                  onClick={() => {
                    setIsOpen(false)
                    handleBookNowClick()
                  }}
                  className="bg-primary text-primary-foreground hover:bg-primary/90 rounded-full w-full mt-4"
                >
                  Book Now
                </Button>
              </nav>
            </SheetContent>
          </Sheet>
        </div>
      </motion.div>

      {/* Booking Dialog */}
      <BookingDialog open={bookingDialogOpen} onOpenChange={setBookingDialogOpen} />
    </motion.header>
  )
}
