"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 { SignupModal } from "@/components/ui/SignupModal";

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

  useEffect(() => {
    let ticking = false;
    function handleScroll() {
      if (!ticking) {
        ticking = true;
        requestAnimationFrame(() => {
          setScrolled(window.scrollY > UI_CONFIG.scrollThresholds.header);
          ticking = false;
        });
      }
    }
    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);
  }, []);

  // Filter out nav links whose target section doesn't exist on the page
  const [visibleLinks, setVisibleLinks] = useState(NAV_LINKS);
  useEffect(() => {
    setVisibleLinks(NAV_LINKS.filter((l) => document.getElementById(l.href.replace("#", ""))));
  }, []);

  useEffect(() => {
    const sectionIds = visibleLinks.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());
  }, [visibleLinks]);

  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-3 lg:gap-5 xl:gap-6 lg:flex">
          {visibleLinks.map((link) => {
            const isActive = activeSection === link.href.replace("#", "");
            return (
              <a
                key={link.href}
                href={link.href}
                className={`relative whitespace-nowrap py-1 text-xs lg: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 lg:hidden">
          <button
            onClick={() => setMenuOpen(!menuOpen)}
            aria-label={menuOpen ? "Закрыть меню" : "Открыть меню"}
            aria-expanded={menuOpen}
            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 lg:hidden ${
          menuOpen ? "max-h-[80vh] opacity-100" : "max-h-0 opacity-0"
        }`}
      >
        <nav className="border-t border-white/[0.06] bg-black/40 px-6 py-4 text-center backdrop-blur-xl sm:px-8">
          {visibleLinks.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 inline-block rounded-full bg-gold px-8 py-3 text-sm font-semibold text-black transition-all hover:bg-gold-light cursor-pointer"
          >
            Записаться
          </button>
        </nav>
      </div>


      <SignupModal open={bookingOpen} onClose={() => setBookingOpen(false)} endpoint="/api/group-booking" />
    </header>
  );
}
