import { useState, useEffect, useRef } from "react";
import { Menu, X, ChevronDown } from "lucide-react";
import { Link, NavLink, useLocation } from "react-router-dom";
import { cn } from "@/lib/utils";
import shineLogo from "@/assets/shine-logo.png";
import phoneIcon from "@/assets/phone-icon.png";

type NavItem = { name: string; href: string };

const navigation: NavItem[] = [
  { name: "Home", href: "/" },
  { name: "Services", href: "/glass-restoration" },
  { name: "Portfolio", href: "/portfolio" },
  { name: "FAQ", href: "/faq" },
  { name: "About", href: "/about" },
  { name: "Contact", href: "/contact" },
];

const services = [
  { name: "Glass Scratch Repair", href: "/glass-scratch-repair-service" },
  { name: "Fix Scratched Glass", href: "/fix-scratched-glass" },
  { name: "Professional Glass Restoration", href: "/professional-glass-scratch-removal" },
  { name: "Glass Scratch Removal", href: "/glass-scratch-removal-service" },
  { name: "Scratched Glass Repair Company", href: "/scratched-glass-repair-company" },
  { name: "Commercial Glass Restoration", href: "/glass-restoration" },
  { name: "Nationwide Glass Repair", href: "/nationwide-glass-repair" },
  { name: "Local Glass Repair Service Areas", href: "/local-glass-repair-service-areas" },
];

const PHONE_DISPLAY = "(312) 569-0248";
const PHONE_TEL = "tel:+13125690248";
const CTA_HREF = "/#final-cta";
const LOGO_SRC = shineLogo;

// Drop shadow applied to all nav text (orange active link + white
// inactive links + phone number) only when header is transparent
// (homepage, scroll-top) so the text reads against the busy hero photo.
// When scrolled, header has bg-ink and the shadow would be unnecessary.
// Bigger + darker than the Hero's white-text shadow because nav text
// is much smaller (text-[15px]) and needs more contrast to define.
const NAV_SHADOW: React.CSSProperties = { textShadow: "0 3px 6px rgba(0,0,0,1)" };

const Header = () => {
  const [scrolled, setScrolled] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [servicesOpen, setServicesOpen] = useState(false);
  const [mobileServicesOpen, setMobileServicesOpen] = useState(false);
  const location = useLocation();
  const hamburgerRef = useRef<HTMLButtonElement>(null);
  const drawerRef = useRef<HTMLDivElement>(null);
  const servicesTimeout = useRef<number | null>(null);

  // Transparent-header: homepage only, at top of page.
  // When transparent: NO background bar — logo + nav float over the hero photo.
  // When scrolled (or non-homepage): solid Ink bar for readability.
  const isHomepage = location.pathname === "/";
  const isTransparent = isHomepage && !scrolled;

  useEffect(() => {
    // Threshold: 60px — snappy transition right after scrolling begins
    const onScroll = () => setScrolled(window.scrollY > 60);
    onScroll(); // run immediately so initial state is correct
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Close drawer on route change
  useEffect(() => {
    setDrawerOpen(false);
    setMobileServicesOpen(false);
  }, [location.pathname, location.hash]);

  // Body scroll lock + focus management for drawer
  useEffect(() => {
    if (drawerOpen) {
      document.body.style.overflow = "hidden";
      const onKey = (e: KeyboardEvent) => {
        if (e.key === "Escape") setDrawerOpen(false);
      };
      document.addEventListener("keydown", onKey);
      window.setTimeout(() => {
        const first = drawerRef.current?.querySelector<HTMLElement>(
          'a, button, [tabindex]:not([tabindex="-1"])'
        );
        first?.focus();
      }, 50);
      return () => {
        document.body.style.overflow = "";
        document.removeEventListener("keydown", onKey);
        hamburgerRef.current?.focus();
      };
    }
  }, [drawerOpen]);

  const openServices = () => {
    if (servicesTimeout.current) window.clearTimeout(servicesTimeout.current);
    setServicesOpen(true);
  };
  const closeServicesDelayed = () => {
    if (servicesTimeout.current) window.clearTimeout(servicesTimeout.current);
    servicesTimeout.current = window.setTimeout(() => setServicesOpen(false), 120);
  };

  // Clicking the logo: navigates to / via Link, AND scrolls to top.
  // Without the explicit scroll, clicking the logo while already on /
  // does nothing visible (Link's no-op when destination matches current path).
  const onLogoClick = () => {
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  // Same-page NavLink click: clicking Home (or any nav link) while
  // already on that page is a no-op for react-router — no route
  // change, no ScrollToTop fire. This handler covers that case by
  // smooth-scrolling to top when href matches current pathname.
  // For real navigations, ScrollToTop handles the post-navigation
  // scroll on its own.
  const onNavClick = (href: string) => {
    if (location.pathname === href) {
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  };

  const headerHeight = scrolled ? "h-16" : "h-20";

  const isActive = (href: string) => {
    if (href === "/") return location.pathname === "/";
    return location.pathname === href || location.pathname.startsWith(href + "/");
  };

  return (
    <>
      {/* Skip link */}
      <a
        href="#main-content"
        className="sr-only focus:not-sr-only focus:fixed focus:top-2 focus:left-2 focus:z-[60] focus:bg-white focus:text-ink focus:px-3 focus:py-2 focus:rounded-md focus:shadow-soft focus:ring-2 focus:ring-logo-orange"
      >
        Skip to content
      </a>

      {/*
        isTransparent = true  → bg-transparent: no bar visible, logo/nav float over hero photo
        isTransparent = false → bg-ink shadow-soft: solid dark bar, always readable
      */}
      <header
        className={cn(
          "fixed top-0 inset-x-0 z-50 transition-all duration-300",
          isTransparent ? "bg-transparent" : "bg-ink shadow-soft"
        )}
      >
        <div className="mx-auto max-w-7xl pr-4 sm:pr-6 lg:pr-8">
          <div
            className={cn(
              "flex items-center justify-between transition-all duration-200",
              headerHeight,
              "md:" + headerHeight,
              "max-md:h-14"
            )}
          >
            {/* Logo */}
            <Link
              to="/"
              onClick={onLogoClick}
              className="flex-shrink-0 self-stretch flex items-center focus:outline-none focus-visible:ring-2 focus-visible:ring-logo-orange"
              aria-label="Shine Glass Renewal — Home"
            >
              <img
                src={LOGO_SRC}
                alt="Shine Glass Renewal"
                className="block h-full w-auto transition-all duration-200"
                width={250}
                height={160}
                loading="eager"
                decoding="async"
                fetchPriority="high"
              />
            </Link>

            {/* Center nav */}
            <nav
              aria-label="Primary"
              className="hidden lg:flex items-center gap-1"
            >
              {navigation.map((item) =>
                item.name === "Services" ? (
                  <div
                    key={item.name}
                    className="relative"
                    onMouseEnter={openServices}
                    onMouseLeave={closeServicesDelayed}
                    onFocus={openServices}
                    onBlur={closeServicesDelayed}
                  >
                    <Link
                      to="/glass-restoration"
                      onClick={() => onNavClick("/glass-restoration")}
                      aria-haspopup="true"
                      aria-expanded={servicesOpen}
                      aria-current={isActive("/glass-restoration") ? "page" : undefined}
                      style={isTransparent ? NAV_SHADOW : undefined}
                      className={cn(
                        "inline-flex items-center gap-1 px-3 py-2 text-[15px] font-medium rounded-md transition-colors",
                        "focus:outline-none focus-visible:ring-2 focus-visible:ring-logo-orange",
                        isActive("/glass-restoration")
                          ? "text-logo-orange"
                          : "text-white/90 hover:text-white"
                      )}
                    >
                      Services
                      <ChevronDown
                        className={cn(
                          "h-4 w-4 transition-transform",
                          servicesOpen && "rotate-180"
                        )}
                      />
                    </Link>

                    {servicesOpen && (
                      <div
                        role="menu"
                        className={cn(
                          "absolute left-0 top-full mt-2",
                          "w-[320px] bg-white border border-[color:var(--border)] rounded-md shadow-soft p-2",
                          "animate-in fade-in slide-in-from-top-2 duration-200"
                        )}
                      >
                        <div className="grid gap-0.5">
                          {services.map((s) => (
                            <Link
                              key={s.href}
                              to={s.href}
                              onClick={() => onNavClick(s.href)}
                              role="menuitem"
                              className={cn(
                                "block rounded-md px-3 py-2 transition-colors font-medium text-ink",
                                "hover:bg-porcelain focus:bg-porcelain focus:outline-none focus-visible:ring-2 focus-visible:ring-logo-orange"
                              )}
                            >
                              {s.name}
                            </Link>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                ) : (
                  <NavLink
                    key={item.name}
                    to={item.href}
                    end={item.href === "/"}
                    onClick={() => onNavClick(item.href)}
                    aria-current={isActive(item.href) ? "page" : undefined}
                    style={isTransparent ? NAV_SHADOW : undefined}
                    className={({ isActive: active }) =>
                      cn(
                        "relative inline-flex items-center px-3 py-2 text-[15px] font-medium rounded-md transition-colors",
                        "focus:outline-none focus-visible:ring-2 focus-visible:ring-logo-orange",
                        active
                          ? "text-logo-orange after:absolute after:left-3 after:right-3 after:-bottom-0.5 after:h-0.5 after:bg-logo-orange after:rounded-full"
                          : "text-white/90 hover:text-white"
                      )
                    }
                  >
                    {item.name}
                  </NavLink>
                )
              )}
            </nav>

            {/* Right side */}
            <div className="flex items-center gap-2 md:gap-4">
              {/* Phone */}
              <a
                href={PHONE_TEL}
                aria-label={`Call Shine Glass Renewal at ${PHONE_DISPLAY}`}
                style={isTransparent ? NAV_SHADOW : undefined}
                className={cn(
                  "inline-flex items-center gap-2 rounded-md px-2 py-2 transition-colors",
                  "text-white/90 hover:text-white",
                  "focus:outline-none focus-visible:ring-2 focus-visible:ring-logo-orange"
                )}
              >
                <img src={phoneIcon} alt="" aria-hidden="true" className="h-7 w-7 object-contain" />
                <span className="hidden md:inline text-[15px] font-medium">
                  {PHONE_DISPLAY}
                </span>
              </a>

              {/* CTA */}
              <Link
                to={CTA_HREF}
                className={cn(
                  "hidden sm:inline-flex items-center justify-center rounded-md",
                  "bg-cta-orange hover:bg-cta-orange-hv text-white",
                  "h-10 px-5 font-medium text-[15px] transition-colors",
                  "focus:outline-none focus-visible:ring-2 focus-visible:ring-logo-orange focus-visible:ring-offset-2"
                )}
              >
                Discuss a Project
              </Link>

              {/* Hamburger */}
              <button
                ref={hamburgerRef}
                type="button"
                onClick={() => setDrawerOpen(true)}
                aria-label="Open menu"
                aria-expanded={drawerOpen}
                aria-controls="mobile-drawer"
                className={cn(
                  "lg:hidden inline-flex items-center justify-center h-10 w-10 rounded-md",
                  "text-white hover:bg-white/10",
                  "transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-logo-orange"
                )}
              >
                <Menu className="h-6 w-6" />
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* Spacer — collapses on homepage so hero bleeds to the top edge */}
      <div
        aria-hidden="true"
        className={cn(
          "w-full transition-all duration-300",
          isTransparent
            ? "h-0"
            : cn(scrolled ? "h-16" : "h-20", "max-md:h-14")
        )}
      />

      {/* Mobile Drawer */}
      {drawerOpen && (
        <div className="fixed inset-0 z-[60] lg:hidden" role="dialog" aria-modal="true" aria-label="Site menu">
          {/* Overlay */}
          <button
            type="button"
            aria-label="Close menu overlay"
            onClick={() => setDrawerOpen(false)}
            className="absolute inset-0 bg-ink/40 animate-in fade-in duration-200"
          />
          {/* Panel */}
          <div
            ref={drawerRef}
            id="mobile-drawer"
            className={cn(
              "absolute right-0 top-0 h-full w-[88%] max-w-sm bg-ink shadow-soft",
              "flex flex-col animate-in slide-in-from-right duration-200"
            )}
          >
            <div className="flex items-center justify-between h-14 px-4 border-b border-white/10">
              <img src={LOGO_SRC} alt="Shine Glass Renewal" className="h-7 w-auto" />
              <button
                type="button"
                onClick={() => setDrawerOpen(false)}
                aria-label="Close menu"
                className="inline-flex items-center justify-center h-10 w-10 rounded-md text-white hover:bg-white/10 focus:outline-none focus-visible:ring-2 focus-visible:ring-logo-orange"
              >
                <X className="h-6 w-6" />
              </button>
            </div>

            <nav aria-label="Mobile" className="flex-1 overflow-y-auto px-2 py-2">
              {navigation.map((item) =>
                item.name === "Services" ? (
                  <div key={item.name} className="border-b border-white/10">
                    <button
                      type="button"
                      onClick={() => setMobileServicesOpen((v) => !v)}
                      aria-expanded={mobileServicesOpen}
                      className={cn(
                        "w-full flex items-center justify-between min-h-[48px] px-3 text-left text-white font-medium",
                        "focus:outline-none focus-visible:ring-2 focus-visible:ring-logo-orange rounded-md"
                      )}
                    >
                      <span>Services</span>
                      <ChevronDown
                        className={cn(
                          "h-5 w-5 text-white/60 transition-transform",
                          mobileServicesOpen && "rotate-180"
                        )}
                      />
                    </button>
                    {mobileServicesOpen && (
                      <div className="pb-2">
                        {services.map((s) => (
                          <Link
                            key={s.href}
                            to={s.href}
                            onClick={() => {
                              setDrawerOpen(false);
                              onNavClick(s.href);
                            }}
                            className="block px-3 py-3 rounded-md font-medium text-white hover:bg-white/10 focus:bg-white/10 focus:outline-none focus-visible:ring-2 focus-visible:ring-logo-orange"
                          >
                            {s.name}
                          </Link>
                        ))}
                      </div>
                    )}
                  </div>
                ) : (
                  <NavLink
                    key={item.name}
                    to={item.href}
                    end={item.href === "/"}
                    onClick={() => {
                      setDrawerOpen(false);
                      onNavClick(item.href);
                    }}
                    aria-current={isActive(item.href) ? "page" : undefined}
                    className={({ isActive: active }) =>
                      cn(
                        "flex items-center min-h-[48px] px-3 border-b border-white/10 text-[16px] font-medium rounded-md",
                        "focus:outline-none focus-visible:ring-2 focus-visible:ring-logo-orange",
                        active ? "text-logo-orange" : "text-white hover:bg-white/10"
                      )
                    }
                  >
                    {item.name}
                  </NavLink>
                )
              )}
            </nav>

            <div className="p-4 border-t border-white/10 space-y-3">
              <a
                href={PHONE_TEL}
                className="flex items-center justify-center gap-2 h-12 w-full rounded-md border border-white/20 text-white font-medium hover:bg-white/10 focus:outline-none focus-visible:ring-2 focus-visible:ring-logo-orange"
              >
                <img src={phoneIcon} alt="" aria-hidden="true" className="h-8 w-8 object-contain" />
                {PHONE_DISPLAY}
              </a>
              <Link
                to={CTA_HREF}
                onClick={() => setDrawerOpen(false)}
                className="flex items-center justify-center h-12 w-full rounded-md bg-cta-orange hover:bg-cta-orange-hv text-white font-medium focus:outline-none focus-visible:ring-2 focus-visible:ring-logo-orange focus-visible:ring-offset-2"
              >
                Discuss a Project
              </Link>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default Header;
