"use client";

import Link from "next/link";
import { Menu, X } from "lucide-react";
import { useState, useEffect } from "react";
import { BRAND, NAV_LINKS } from "@/lib/constants";
import { UI_CONFIG } from "@/lib/config";
import { HeroLogo } from "@/components/ui/HeroLogo";
import { BookingModal } from "@/components/ui/BookingModal";

export function Header() {
  const [menuOpen, setMenuOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [activeSection, setActiveSection] = useState("");
  const [bookingOpen, setBookingOpen] = useState(false);

  useEffect(() => {
    function handleScroll() {
      setScrolled(window.scrollY > UI_CONFIG.scrollThresholds.header);
    }
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  // Listen for booking open events from other components
  useEffect(() => {
    function onOpenBooking() {
      setBookingOpen(true);
    }
    window.addEventListener("open-booking", onOpenBooking);
    return () => window.removeEventListener("open-booking", onOpenBooking);
  }, []);

  useEffect(() => {
    const sectionIds = NAV_LINKS.map((l) => l.href.replace("#", ""));
    const observers: IntersectionObserver[] = [];

    // Observe hero — when visible, clear active section
    const hero = document.querySelector("section:first-of-type");
    if (hero) {
      const heroObserver = new IntersectionObserver(
        ([entry]) => {
          if (entry.isIntersecting) setActiveSection("");
        },
        { rootMargin: "-20% 0px -70% 0px" },
      );
      heroObserver.observe(hero);
      observers.push(heroObserver);
    }

    sectionIds.forEach((id) => {
      const el = document.getElementById(id);
      if (!el) return;

      const observer = new IntersectionObserver(
        ([entry]) => {
          if (entry.isIntersecting) {
            setActiveSection(id);
          }
        },
        { rootMargin: "-40% 0px -55% 0px" },
      );
      observer.observe(el);
      observers.push(observer);
    });

    return () => observers.forEach((o) => o.disconnect());
  }, []);

  return (
    <header
      className={`fixed top-0 z-50 w-full transition-all duration-500 ${
        scrolled
          ? "bg-black/40 shadow-none backdrop-blur-xl"
          : "bg-transparent"
      }`}
    >
      <div className="flex h-16 items-center justify-between px-6 sm:px-10 lg:px-16">
        <Link href="/" className="group flex items-center gap-2.5">
          <div className="relative flex h-8 w-8 items-center justify-center">
            <div
              className="absolute inset-0 rounded-full transition-all duration-300 group-hover:scale-125"
              style={{
                background: "radial-gradient(circle, rgba(201,169,110,0.5) 0%, rgba(201,169,110,0.15) 50%, transparent 70%)",
              }}
            />
            <HeroLogo
              size={24}
              className="relative text-black transition-transform duration-300 drop-shadow-[0_0_3px_rgba(201,169,110,0.5)] group-hover:scale-110"
            />
          </div>
          <span className="font-display text-lg font-bold tracking-tight text-gold">
            {BRAND.shortName}
          </span>
        </Link>

        <nav className="hidden items-center gap-8 md:flex">
          {NAV_LINKS.map((link) => {
            const isActive = activeSection === link.href.replace("#", "");
            return (
              <a
                key={link.href}
                href={link.href}
                className={`relative py-1 text-sm font-medium transition-all duration-300 after:absolute after:bottom-0 after:left-0 after:h-[2px] after:bg-gold after:transition-all after:duration-300 ${
                  isActive
                    ? "text-gold-light after:w-full"
                    : "text-neutral-400 after:w-0 hover:text-white hover:after:w-full"
                }`}
              >
                {link.label}
              </a>
            );
          })}
          <button
            onClick={() => setBookingOpen(true)}
            className="rounded-full bg-gold px-4 py-1.5 text-sm font-semibold text-black transition-all hover:bg-gold-light hover:shadow-lg hover:shadow-gold/20 cursor-pointer"
          >
            Записаться
          </button>
        </nav>

        <div className="flex items-center gap-2 md:hidden">
          <button
            onClick={() => setMenuOpen(!menuOpen)}
            aria-label="Меню"
            className="rounded-lg p-2 text-neutral-400 transition-colors hover:text-white"
          >
            {menuOpen ? <X size={24} /> : <Menu size={24} />}
          </button>
        </div>
      </div>

      {/* Mobile menu */}
      <div
        className={`overflow-hidden transition-all duration-300 md:hidden ${
          menuOpen ? "max-h-80 opacity-100" : "max-h-0 opacity-0"
        }`}
      >
        <nav className="border-t border-white/[0.06] bg-black/40 px-6 py-4 backdrop-blur-xl sm:px-8">
          {NAV_LINKS.map((link) => {
            const isActive = activeSection === link.href.replace("#", "");
            return (
              <a
                key={link.href}
                href={link.href}
                onClick={() => setMenuOpen(false)}
                className={`block py-3 text-base transition-colors ${
                  isActive
                    ? "text-gold-light"
                    : "text-neutral-400 hover:text-white"
                }`}
              >
                {link.label}
              </a>
            );
          })}
          <button
            onClick={() => {
              setMenuOpen(false);
              setBookingOpen(true);
            }}
            className="mt-2 w-full rounded-full bg-gold py-3 text-sm font-semibold text-black transition-all hover:bg-gold-light cursor-pointer"
          >
            Записаться
          </button>
        </nav>
      </div>

      {/* Floating booking button — visible on scroll, mobile */}
      <button
        onClick={() => setBookingOpen(true)}
        className={`fixed bottom-6 right-6 z-40 flex items-center gap-2 rounded-full bg-gold px-5 py-3 text-sm font-semibold text-black shadow-lg shadow-gold/25 transition-all duration-500 hover:bg-gold-light hover:shadow-xl hover:shadow-gold/30 cursor-pointer md:hidden ${
          scrolled ? "translate-y-0 opacity-100" : "translate-y-16 opacity-0 pointer-events-none"
        }`}
      >
        Записаться
      </button>

      <BookingModal open={bookingOpen} onClose={() => setBookingOpen(false)} />
    </header>
  );
}
