import { useState, useEffect, useRef, useCallback } from "react";
import { Link, useLocation } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Menu, X, ChevronDown, LayoutDashboard } from "lucide-react";
import { cn } from "@/lib/utils";
import sutekiLogo from "@/assets/suteki-logo.png";
import { LanguageSwitcher, MobileLanguageSwitcher } from "@/components/LanguageSwitcher";
import { CategoryDropdown, CategoryMobileAccordion, NavCategory } from "./MegaMenu";
import { getLocalizedPath, allSolutionPaths } from "@/lib/routes";
import { useAuth } from "@/hooks/useAuth";

const CATEGORY_KEYS: NavCategory[] = ["ai", "vr", "hologram"];
const PLAIN_LINKS = ["cases", "news", "about", "contact"] as const;

export function Header() {
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [openDropdown, setOpenDropdown] = useState<NavCategory | null>(null);
  const [scrolled, setScrolled] = useState(false);
  const dropdownRefs = useRef<Record<string, HTMLDivElement | null>>({});
  const location = useLocation();
  const { t, i18n } = useTranslation();
  const lang = i18n.language;
  const { user } = useAuth();

  const hrefs: Record<string, string> = {
    home: getLocalizedPath("home", lang),
    cases: getLocalizedPath("cases", lang),
    news: getLocalizedPath("news", lang),
    about: getLocalizedPath("about", lang),
    contact: getLocalizedPath("contact", lang),
  };

  const isActiveCategory = (cat: NavCategory) => {
    const p = location.pathname;
    if (cat === "ai") return p.startsWith("/ai");
    if (cat === "vr") return p.startsWith("/vr");
    if (cat === "hologram") return allSolutionPaths.some(sp =>
      (sp.includes("hologram") || sp.includes("holobox") || sp.includes("holospin") || sp.includes("holonet") || sp.includes("invisible-screen") || sp.includes("3d-hologram") || sp.includes("magic-mirror"))
      && (p === sp || p.startsWith(sp + "/"))
    );
    return false;
  };

  const isActivePlain = (key: string) => {
    const p = location.pathname;
    if (key === "about") return p === "/about" || p === "/om-oss";
    if (key === "contact") return p === "/contact" || p === "/kontakt";
    if (key === "news") return p.startsWith("/nyheter");
    if (key === "cases") return p === "/cases";
    return false;
  };

  useEffect(() => { setOpenDropdown(null); setMobileMenuOpen(false); }, [location.pathname]);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    if (!openDropdown) return;
    const handler = (e: MouseEvent) => {
      const ref = dropdownRefs.current[openDropdown];
      if (ref && !ref.contains(e.target as Node)) setOpenDropdown(null);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [openDropdown]);

  useEffect(() => {
    if (!openDropdown) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpenDropdown(null);
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [openDropdown]);

  const linkCls = (active: boolean) =>
    cn(
      "text-[13px] font-medium tracking-wide uppercase transition-all duration-300 relative py-1",
      active ? "text-white" : "text-white/60 hover:text-white"
    );

  const navLabels: Record<string, string> = {
    home: t("nav.home"),
    cases: t("nav.cases"),
    news: t("nav.news"),
    about: t("nav.about"),
    contact: t("nav.contact"),
  };

  const catLabels: Record<NavCategory, string> = {
    ai: "AI",
    vr: "VR",
    hologram: "Hologram",
  };

  return (
    <header
      className={cn(
        "fixed top-0 left-0 right-0 z-50 transition-all duration-500",
        scrolled
          ? "bg-[#0B1220]/97 backdrop-blur-xl border-b border-white/[0.06]"
          : "bg-transparent"
      )}
      data-theme="dark"
    >
      <nav className="max-w-7xl w-full mx-auto flex items-center justify-between py-4 px-6 lg:px-8">
        {/* Logo */}
        <Link to={hrefs.home} className="flex items-center group">
          <img
            src={sutekiLogo}
            alt="Suteki Studios"
            width={198}
            height={34}
            loading="eager"
            {...{ fetchpriority: "high" }}
            decoding="async"
            className="h-[28px] w-auto transition-opacity group-hover:opacity-80"
          />
        </Link>

        {/* Desktop Navigation */}
        <div className="hidden md:flex items-center gap-7">
          <Link to={hrefs.home} className={linkCls(location.pathname === "/" || location.pathname === "/en")}>
            {navLabels.home}
          </Link>

          {CATEGORY_KEYS.map((cat) => (
            <div
              key={cat}
              className="relative"
              ref={(el) => { dropdownRefs.current[cat] = el; }}
            >
              <button
                type="button"
                id={`nav-${cat}-trigger`}
                aria-expanded={openDropdown === cat}
                aria-haspopup="true"
                aria-controls={`nav-${cat}-menu`}
                className={cn(
                  "flex items-center gap-1 cursor-pointer select-none bg-transparent border-0 p-0",
                  linkCls(isActiveCategory(cat))
                )}
                onMouseEnter={() => setOpenDropdown(cat)}
                onClick={() => setOpenDropdown(openDropdown === cat ? null : cat)}
                onKeyDown={(e) => {
                  if (e.key === "Enter" || e.key === " " || e.key === "Spacebar") {
                    e.preventDefault();
                    setOpenDropdown(openDropdown === cat ? null : cat);
                  } else if (e.key === "Escape") {
                    setOpenDropdown(null);
                  }
                }}
              >
                <span>{catLabels[cat]}</span>
                <ChevronDown className={cn("h-3 w-3 transition-transform duration-200", openDropdown === cat && "rotate-180")} />
              </button>

              {openDropdown === cat && (
                <div
                  id={`nav-${cat}-menu`}
                  role="menu"
                  aria-labelledby={`nav-${cat}-trigger`}
                  className="absolute left-1/2 -translate-x-1/2 top-full z-50 pt-2"
                  onMouseLeave={() => setOpenDropdown(null)}
                >
                  <div
                    className="rounded-xl overflow-hidden animate-in fade-in slide-in-from-top-2 duration-200"
                    style={{
                      backgroundColor: '#0B1220',
                      border: '1px solid rgba(255,255,255,0.08)',
                      boxShadow: '0 8px 32px rgba(0,0,0,0.45)',
                    }}
                  >
                    <CategoryDropdown category={cat} onLinkClick={() => setOpenDropdown(null)} />
                  </div>
                </div>
              )}
            </div>
          ))}

          {PLAIN_LINKS.map((key) => (
            <Link
              key={key}
              to={hrefs[key]}
              className={linkCls(isActivePlain(key))}
            >
              {navLabels[key]}
            </Link>
          ))}
        </div>

        {/* Desktop CTA */}
        <div className="hidden md:flex items-center gap-4">
          <LanguageSwitcher />
          {user ? (
            <Link
              to="/dashboard/sales"
              className="text-[13px] font-medium flex items-center gap-1.5 text-white/70 hover:text-white transition-colors"
            >
              <LayoutDashboard className="h-4 w-4" />
              Dashboard
            </Link>
          ) : null}
          <a
            href="https://calendly.com/sutekistudios/strategic-project-discussion"
            target="_blank"
            rel="noopener noreferrer"
            className="text-[13px] font-medium px-5 py-2.5 rounded-full bg-white text-[#0B1220] hover:bg-white/90 transition-all duration-300 shadow-sm hover:shadow-md"
          >
            {t("nav.bookMeeting")}
          </a>
        </div>

        {/* Mobile hamburger */}
        <button
          type="button"
          aria-label={mobileMenuOpen ? "Close menu" : "Open menu"}
          aria-expanded={mobileMenuOpen}
          className="md:hidden p-2 text-white/70 hover:text-white transition-colors"
          onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
        >
          {mobileMenuOpen ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
        </button>
      </nav>

      {/* Mobile Navigation */}
      {mobileMenuOpen && (
        <div className="md:hidden" style={{ backgroundColor: '#0B1220', borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
          <div className="container mx-auto px-6 py-6 flex flex-col gap-3">
            <Link to={hrefs.home} className={cn("text-base font-medium py-2", (location.pathname === "/" || location.pathname === "/en") ? "text-white" : "text-white/60")} onClick={() => setMobileMenuOpen(false)}>
              {navLabels.home}
            </Link>

            {CATEGORY_KEYS.map((cat) => (
              <div key={cat} className="flex flex-col gap-1">
                <details className="group">
                  <summary className="flex items-center justify-between cursor-pointer text-base font-medium py-2 transition-colors list-none [&::-webkit-details-marker]:hidden text-white/80 hover:text-white">
                    <span>{catLabels[cat]}</span>
                    <svg className="h-3.5 w-3.5 transition-transform duration-200 group-open:rotate-180" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
                    </svg>
                  </summary>
                  <CategoryMobileAccordion category={cat} onLinkClick={() => setMobileMenuOpen(false)} />
                </details>
              </div>
            ))}

            {PLAIN_LINKS.map((key) => (
              <Link
                key={key}
                to={hrefs[key]}
                className={cn("text-base font-medium py-2", isActivePlain(key) ? "text-white" : "text-white/60")}
                onClick={() => setMobileMenuOpen(false)}
              >
                {navLabels[key]}
              </Link>
            ))}

            <MobileLanguageSwitcher onSelect={() => setMobileMenuOpen(false)} />

            {user ? (
              <Link
                to="/dashboard/sales"
                className="text-base font-medium py-2 text-white/80 hover:text-white"
                onClick={() => setMobileMenuOpen(false)}
              >
                Dashboard
              </Link>
            ) : null}

            <a
              href="https://calendly.com/sutekistudios/strategic-project-discussion"
              target="_blank"
              rel="noopener noreferrer"
              className="mt-4 text-center text-sm font-medium px-5 py-3 rounded-full bg-white text-[#0B1220]"
              onClick={() => setMobileMenuOpen(false)}
            >
              {t("nav.bookMeeting")}
            </a>
          </div>
        </div>
      )}
    </header>
  );
}
