/*
  DESIGN: "Global Nexus" — Sticky navigation with search integration
  Deep navy palette, teal accents, Outfit + IBM Plex Sans typography
*/
import { useState, useEffect, useRef } from "react";
import { Link, useLocation } from "wouter";
import { Menu, X, Phone, Mail, ChevronDown, Globe, Search } from "lucide-react";
import { useLanguage } from "@/contexts/LanguageContext";
import SearchDialog from "@/components/SearchDialog";

const LOGO_URL = "/images/kHSmOkFIzSbmDqbQ.png";

export default function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [industriesOpen, setIndustriesOpen] = useState(false);
  const [mobileIndustriesOpen, setMobileIndustriesOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const dropdownRef = useRef<HTMLLIElement>(null);
  const { lang, setLang, t } = useLanguage();
  const [location] = useLocation();

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

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        setIndustriesOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // Ctrl+K / Cmd+K keyboard shortcut for search
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "k") {
        e.preventDefault();
        setSearchOpen(true);
      }
    };
    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, []);

  // Prevent body scroll when search is open
  useEffect(() => {
    if (searchOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [searchOpen]);

  const industries = [
    { label: t("nav.ceramics"), href: "/industries/ceramics" },
    { label: t("nav.glass"), href: "/industries/glass" },
    { label: t("nav.cement"), href: "/industries/cement" },
    { label: t("nav.machinery"), href: "/industries/machinery" },
  ];

  const navLinks = [
    { label: t("nav.home"), href: "/" },
    { label: t("nav.about"), href: "/about" },
    { label: t("nav.industries"), href: "#", isDropdown: true },
    { label: t("nav.partners"), href: "/partners" },
    { label: t("nav.contact"), href: "/contact" },
  ];

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

  return (
    <>
      {/* Top bar */}
      <div className="hidden lg:block bg-navy text-white/80 text-sm">
        <div className="container flex justify-between items-center py-2">
          <div className="flex items-center gap-6">
            <a href="mailto:info@alzarfze.com" className="flex items-center gap-2 hover:text-teal transition-colors">
              <Mail className="w-3.5 h-3.5" />
              <span dir="ltr">info@alzarfze.com</span>
            </a>
            <a href="tel:+97148814928" className="flex items-center gap-2 hover:text-teal transition-colors">
              <Phone className="w-3.5 h-3.5" />
              <span dir="ltr">+971 4 881 4928</span>
            </a>
          </div>
          <div className="flex items-center gap-4">
            <span className="text-white/60">{lang === "ar" ? "المنطقة الحرة بجبل علي، دبي، الإمارات" : "Jebel Ali Free Zone, Dubai, UAE"}</span>
            <button
              onClick={() => setLang(lang === "en" ? "ar" : "en")}
              className="flex items-center gap-1.5 bg-white/10 hover:bg-white/20 px-3 py-1 rounded text-xs font-medium transition-colors"
            >
              <Globe className="w-3 h-3" />
              {lang === "en" ? "العربية" : "English"}
            </button>
          </div>
        </div>
      </div>

      {/* Main nav */}
      <nav
        className={`sticky top-0 z-50 transition-all duration-300 ${
          scrolled
            ? "bg-navy/95 backdrop-blur-md shadow-lg shadow-navy/20"
            : "bg-navy"
        }`}
      >
        <div className="container flex items-center justify-between h-16 lg:h-[72px]">
          {/* Logo */}
          <Link href="/" className="flex items-center gap-3 shrink-0">
            <img src={LOGO_URL} alt="Alzar FZE Logo" className="h-10 lg:h-12 w-auto" />
          </Link>

          {/* Desktop links */}
          <ul className="hidden lg:flex items-center gap-1">
            {navLinks.map((link) =>
              link.isDropdown ? (
                <li key="industries" className="relative" ref={dropdownRef}>
                  <button
                    onClick={() => setIndustriesOpen(!industriesOpen)}
                    className={`flex items-center gap-1 px-4 py-2 text-sm font-medium transition-colors rounded-md hover:bg-white/5 ${
                      location.startsWith("/industries") ? "text-teal" : "text-white/80 hover:text-teal"
                    }`}
                  >
                    {link.label}
                    <ChevronDown className={`w-3.5 h-3.5 transition-transform ${industriesOpen ? "rotate-180" : ""}`} />
                  </button>
                  {industriesOpen && (
                    <div className="absolute top-full left-0 mt-1 bg-navy-light border border-white/10 rounded-lg shadow-xl py-2 min-w-[200px]">
                      {industries.map((ind) => (
                        <Link
                          key={ind.href}
                          href={ind.href}
                          onClick={() => setIndustriesOpen(false)}
                          className={`block px-4 py-2.5 text-sm transition-colors hover:bg-white/5 ${
                            isActive(ind.href) ? "text-teal" : "text-white/70 hover:text-teal"
                          }`}
                        >
                          {ind.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </li>
              ) : (
                <li key={link.href}>
                  <Link
                    href={link.href}
                    className={`px-4 py-2 text-sm font-medium transition-colors rounded-md hover:bg-white/5 ${
                      isActive(link.href) ? "text-teal" : "text-white/80 hover:text-teal"
                    }`}
                  >
                    {link.label}
                  </Link>
                </li>
              )
            )}
          </ul>

          {/* Search + CTA + Language */}
          <div className="hidden lg:flex items-center gap-3">
            {/* Search trigger */}
            <button
              onClick={() => setSearchOpen(true)}
              className="flex items-center gap-2 bg-white/5 hover:bg-white/10 text-white/60 hover:text-white/80 px-3 py-2 rounded-md transition-all text-sm"
              aria-label="Search"
            >
              <Search className="w-4 h-4" />
              <span className="text-white/40">{lang === "ar" ? "بحث..." : "Search..."}</span>
              <kbd className="hidden xl:inline-flex ml-2 px-1.5 py-0.5 text-[10px] font-mono text-white/30 bg-white/5 rounded border border-white/10">
                ⌘K
              </kbd>
            </button>

            <Link
              href="/contact"
              className="inline-flex items-center gap-2 bg-teal hover:bg-teal-dark text-white text-sm font-semibold px-5 py-2.5 rounded-md transition-all duration-200 hover:shadow-lg hover:shadow-teal/20"
            >
              {t("nav.getInTouch")}
            </Link>
          </div>

          {/* Mobile toggle */}
          <div className="flex items-center gap-2 lg:hidden">
            {/* Mobile search button */}
            <button
              onClick={() => setSearchOpen(true)}
              className="text-white/70 p-2 hover:text-teal transition-colors"
              aria-label="Search"
            >
              <Search className="w-5 h-5" />
            </button>
            <button
              onClick={() => setLang(lang === "en" ? "ar" : "en")}
              className="text-white/70 p-2"
              aria-label="Toggle language"
            >
              <Globe className="w-5 h-5" />
            </button>
            <button
              onClick={() => setMobileOpen(!mobileOpen)}
              className="text-white p-2"
              aria-label="Toggle menu"
            >
              {mobileOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
            </button>
          </div>
        </div>

        {/* Mobile menu */}
        {mobileOpen && (
          <div className="lg:hidden bg-navy border-t border-white/10 pb-4">
            <ul className="container flex flex-col gap-1 pt-2">
              <li>
                <Link href="/" onClick={() => setMobileOpen(false)} className="block px-4 py-3 text-white/80 hover:text-teal hover:bg-white/5 rounded-md transition-colors">
                  {t("nav.home")}
                </Link>
              </li>
              <li>
                <Link href="/about" onClick={() => setMobileOpen(false)} className="block px-4 py-3 text-white/80 hover:text-teal hover:bg-white/5 rounded-md transition-colors">
                  {t("nav.about")}
                </Link>
              </li>
              <li>
                <button
                  onClick={() => setMobileIndustriesOpen(!mobileIndustriesOpen)}
                  className="flex items-center justify-between w-full px-4 py-3 text-white/80 hover:text-teal hover:bg-white/5 rounded-md transition-colors"
                >
                  {t("nav.industries")}
                  <ChevronDown className={`w-4 h-4 transition-transform ${mobileIndustriesOpen ? "rotate-180" : ""}`} />
                </button>
                {mobileIndustriesOpen && (
                  <ul className="ml-4 border-l border-white/10">
                    {industries.map((ind) => (
                      <li key={ind.href}>
                        <Link href={ind.href} onClick={() => setMobileOpen(false)} className="block px-4 py-2.5 text-sm text-white/60 hover:text-teal transition-colors">
                          {ind.label}
                        </Link>
                      </li>
                    ))}
                  </ul>
                )}
              </li>
              <li>
                <Link href="/partners" onClick={() => setMobileOpen(false)} className="block px-4 py-3 text-white/80 hover:text-teal hover:bg-white/5 rounded-md transition-colors">
                  {t("nav.partners")}
                </Link>
              </li>
              <li>
                <Link href="/contact" onClick={() => setMobileOpen(false)} className="block px-4 py-3 text-white/80 hover:text-teal hover:bg-white/5 rounded-md transition-colors">
                  {t("nav.contact")}
                </Link>
              </li>
              <li className="mt-2 px-4">
                <Link href="/contact" onClick={() => setMobileOpen(false)} className="block text-center bg-teal hover:bg-teal-dark text-white font-semibold py-3 rounded-md transition-colors">
                  {t("nav.getInTouch")}
                </Link>
              </li>
            </ul>
          </div>
        )}
      </nav>

      {/* Search Dialog */}
      <SearchDialog open={searchOpen} onClose={() => setSearchOpen(false)} />
    </>
  );
}
