"use client";

import classNames from "classnames";
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { UI, type Lang, LANGS, SITE } from "@/lib/config";
import { NAVIGATION } from "@/lib/config/content/navigation";
import LangSwitcher from "./LangSwitcher";
import ThemeToggle from "./ThemeToggle";

export default function Nav({ lang }: { lang: Lang }) {
  const currentLang = LANGS.includes(lang) ? lang : SITE.defaultLang;
  const dict = UI[currentLang];
  const t = dict.t;
  const isRTL = dict.dir === "rtl";
  const linkTo = (path: string) =>
    path === "/" ? `/${lang}` : `/${lang}${path}`;

  const navLinks = NAVIGATION[currentLang].navLinks.map((link) => ({
    ...link,
    href: linkTo(link.href),
  }));

  const featureLinks = NAVIGATION[currentLang].featureLinks.map((link) => ({
    ...link,
    href: linkTo(link.href),
    subLinks: link.subLinks.map((subLink) => ({
      ...subLink,
      href: subLink.href ? linkTo(subLink.href) : undefined,
    })),
  }));

  const sectorLinks = NAVIGATION[currentLang].sectorLinks.map((link) => ({
    ...link,
    href: linkTo(link.href),
    subPages: link.subPages?.map((subPage) => ({
      ...subPage,
      href: linkTo(subPage.href),
    })),
  }));

  const [mobileOpen, setMobileOpen] = useState(false);
  const [desktopFeaturesOpen, setDesktopFeaturesOpen] = useState(false);
  const [mobileFeaturesOpen, setMobileFeaturesOpen] = useState(false);
  const [desktopSectorsOpen, setDesktopSectorsOpen] = useState(false);
  const [mobileSectorsOpen, setMobileSectorsOpen] = useState(false);
  const dropdownRef = useRef<HTMLLIElement | null>(null);
  const sectorsDropdownRef = useRef<HTMLLIElement | null>(null);
  const hoverTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
  const sectorsHoverTimeout = useRef<ReturnType<typeof setTimeout> | null>(
    null,
  );

  const closeMobile = () => {
    setMobileOpen(false);
    setMobileFeaturesOpen(false);
    setMobileSectorsOpen(false);
  };

  const openFeatures = () => {
    if (hoverTimeout.current) {
      clearTimeout(hoverTimeout.current);
      hoverTimeout.current = null;
    }
    setDesktopFeaturesOpen(true);
  };

  const scheduleCloseFeatures = () => {
    if (hoverTimeout.current) {
      clearTimeout(hoverTimeout.current);
    }
    hoverTimeout.current = setTimeout(() => {
      setDesktopFeaturesOpen(false);
    }, 120);
  };

  const openSectors = () => {
    if (sectorsHoverTimeout.current) {
      clearTimeout(sectorsHoverTimeout.current);
      sectorsHoverTimeout.current = null;
    }
    setDesktopSectorsOpen(true);
  };

  const scheduleCloseSectors = () => {
    if (sectorsHoverTimeout.current) {
      clearTimeout(sectorsHoverTimeout.current);
    }
    sectorsHoverTimeout.current = setTimeout(() => {
      setDesktopSectorsOpen(false);
    }, 120);
  };

  useEffect(() => {
    const handleClick = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setDesktopFeaturesOpen(false);
      }
      if (
        sectorsDropdownRef.current &&
        !sectorsDropdownRef.current.contains(event.target as Node)
      ) {
        setDesktopSectorsOpen(false);
      }
    };
    const handleKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setDesktopFeaturesOpen(false);
        setMobileFeaturesOpen(false);
        setDesktopSectorsOpen(false);
        setMobileSectorsOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClick);
    document.addEventListener("keydown", handleKey);
    return () => {
      document.removeEventListener("mousedown", handleClick);
      document.removeEventListener("keydown", handleKey);
      if (hoverTimeout.current) {
        clearTimeout(hoverTimeout.current);
      }
      if (sectorsHoverTimeout.current) {
        clearTimeout(sectorsHoverTimeout.current);
      }
    };
  }, []);

  return (
    <header className="sticky top-0 z-50 border-b border-slate-200 bg-white/85 backdrop-blur transition-colors dark:border-slate-800 dark:bg-slate-900/80">
      <nav
        dir={isRTL ? "rtl" : "ltr"}
        className={classNames(
          "mx-auto flex max-w-6xl items-center gap-4 px-4 py-3",
          isRTL ? "flex-row-reverse" : "flex-row",
        )}
      >
        <Link
          href={linkTo("/")}
          prefetch={true}
          className="flex shrink-0 items-center gap-2"
        >
          <img
            src="/mawidi-icon.svg"
            alt="Mawidi"
            className="h-10 w-auto md:h-12"
            width={48}
            height={48}
          />
        </Link>
        <button
          type="button"
          onClick={() => setMobileOpen((prev) => !prev)}
          className={classNames(
            "rounded-md border border-slate-200 bg-white p-2 text-xl shadow-sm transition-colors hover:border-brand-green hover:text-brand-green dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 md:hidden",
            isRTL ? "mr-auto" : "ml-auto",
          )}
          aria-expanded={mobileOpen}
          aria-controls="mobile-nav"
        >
          {mobileOpen ? "✕" : "☰"}
          <span className="sr-only">
            {mobileOpen ? "Close menu" : "Open menu"}
          </span>
        </button>
        <ul
          className={classNames(
            "hidden flex-1 items-center gap-4 md:flex",
            isRTL
              ? "flex-row-reverse justify-center text-right"
              : "flex-row justify-center text-left",
          )}
        >
          {/* IMPORTANT: All desktop nav items MUST use "inline-flex items-center h-9"
              so regular links and dropdown buttons share the same box model/baseline.
              Do NOT remove these classes — they fix the Features/Sectors alignment. */}
          {navLinks.slice(0, 2).map((item) => (
            <li key={item.href}>
              <Link
                href={item.href}
                prefetch={true}
                className="inline-flex items-center h-9 text-sm font-semibold text-brand-ink/80 transition-colors hover:text-brand-green dark:text-slate-200 dark:hover:text-brand-green"
              >
                {item.label}
              </Link>
            </li>
          ))}
          <li
            ref={dropdownRef}
            className={classNames(
              "relative",
              isRTL ? "text-right" : "text-left",
            )}
            onMouseEnter={openFeatures}
            onMouseLeave={scheduleCloseFeatures}
            onFocus={openFeatures}
            onBlur={(event) => {
              if (!dropdownRef.current?.contains(event.relatedTarget as Node)) {
                setDesktopFeaturesOpen(false);
              }
            }}
          >
            <button
              type="button"
              onClick={() => setDesktopFeaturesOpen((prev) => !prev)}
              className="inline-flex items-center gap-1 h-9 border-0 bg-transparent p-0 text-sm font-semibold text-brand-ink/80 transition-colors hover:text-brand-green focus:outline-none dark:text-slate-200 dark:hover:text-brand-green"
              aria-expanded={desktopFeaturesOpen}
              aria-haspopup="true"
            >
              {t.features}
              <span className="text-[10px] leading-none opacity-60" aria-hidden>
                {desktopFeaturesOpen ? "▴" : "▾"}
              </span>
            </button>
            {desktopFeaturesOpen && (
              <div
                className={classNames(
                  "absolute top-full z-30 translate-y-2 rounded-2xl border border-slate-200 bg-white shadow-2xl dark:border-slate-700 dark:bg-slate-900",
                  isRTL ? "right-0" : "left-0",
                )}
                onMouseEnter={openFeatures}
                onMouseLeave={scheduleCloseFeatures}
              >
                <div
                  className="grid grid-cols-1 gap-2 p-4 md:grid-cols-2 md:gap-4 md:p-5"
                  style={{ minWidth: "720px" }}
                >
                  {/* Left column - Feature items with descriptions */}
                  <div className="space-y-1">
                    <h3
                      className={classNames(
                        "px-3 py-2 text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400",
                        isRTL ? "text-right" : "text-left",
                      )}
                    >
                      {lang === "ar" ? "المميزات" : "Features"}
                    </h3>
                    <ul className="flex flex-col gap-1">
                      {featureLinks.map((item) => (
                        <li key={item.href}>
                          <Link
                            href={item.href}
                            prefetch={true}
                            className="group flex items-start gap-3 rounded-lg px-3 py-2.5 transition-all hover:bg-slate-100 hover:shadow-sm dark:hover:bg-slate-800"
                            onClick={() => setDesktopFeaturesOpen(false)}
                          >
                            <span className="text-xl leading-tight" aria-hidden>
                              {item.icon}
                            </span>
                            <div className="flex-1 space-y-0.5">
                              <div className="text-sm font-semibold text-gray-900 group-hover:text-brand-green dark:text-gray-100">
                                {item.label}
                              </div>
                              <div className="text-xs leading-relaxed text-gray-600 dark:text-gray-400">
                                {item.description}
                              </div>
                            </div>
                          </Link>
                        </li>
                      ))}
                    </ul>
                  </div>

                  {/* Right column - Quick links (dynamic based on hover) */}
                  <div className="hidden border-l border-slate-200 pl-4 dark:border-slate-700 md:block">
                    <h3
                      className={classNames(
                        "px-3 py-2 text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400",
                        isRTL ? "text-right" : "text-left",
                      )}
                    >
                      {lang === "ar" ? "روابط سريعة" : "Quick Links"}
                    </h3>
                    <div className="space-y-4">
                      {featureLinks.slice(0, 3).map((feature) => (
                        <div key={feature.href} className="space-y-1.5">
                          <p className="px-3 text-xs font-medium text-gray-700 dark:text-gray-300">
                            {feature.label}
                          </p>
                          <ul className="space-y-0.5">
                            {feature.subLinks
                              .filter((subLink) => subLink.href) // Only render subLinks with href
                              .slice(0, 2)
                              .map((subLink, idx) => (
                                <li key={idx}>
                                  <Link
                                    href={subLink.href!} // Safe to use ! because we filtered
                                    className="block rounded px-3 py-1 text-xs text-gray-600 hover:text-brand-green hover:bg-slate-50 dark:text-gray-400 dark:hover:text-brand-green dark:hover:bg-slate-800/50"
                                    onClick={() =>
                                      setDesktopFeaturesOpen(false)
                                    }
                                  >
                                    {subLink.label}
                                  </Link>
                                </li>
                              ))}
                          </ul>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            )}
          </li>
          <li
            ref={sectorsDropdownRef}
            className={classNames(
              "relative",
              isRTL ? "text-right" : "text-left",
            )}
            onMouseEnter={openSectors}
            onMouseLeave={scheduleCloseSectors}
            onFocus={openSectors}
            onBlur={(event) => {
              if (
                !sectorsDropdownRef.current?.contains(
                  event.relatedTarget as Node,
                )
              ) {
                setDesktopSectorsOpen(false);
              }
            }}
          >
            <button
              type="button"
              onClick={() => setDesktopSectorsOpen((prev) => !prev)}
              className="inline-flex items-center gap-1 h-9 border-0 bg-transparent p-0 text-sm font-semibold text-brand-ink/80 transition-colors hover:text-brand-green focus:outline-none dark:text-slate-200 dark:hover:text-brand-green"
              aria-expanded={desktopSectorsOpen}
              aria-haspopup="true"
            >
              {lang === "ar" ? "القطاعات" : "Sectors"}
              <span className="text-[10px] leading-none opacity-60" aria-hidden>
                {desktopSectorsOpen ? "▴" : "▾"}
              </span>
            </button>
            {desktopSectorsOpen && (
              <div
                className={classNames(
                  "absolute top-full z-30 translate-y-2 rounded-2xl border border-slate-200 bg-white shadow-2xl dark:border-slate-700 dark:bg-slate-900",
                  isRTL ? "right-0" : "left-0",
                )}
                onMouseEnter={openSectors}
                onMouseLeave={scheduleCloseSectors}
                style={{ width: sectorLinks.length > 8 ? "860px" : "420px" }}
              >
                <div
                  className={classNames(
                    "grid gap-1 p-3",
                    sectorLinks.length > 8 ? "grid-cols-2" : "grid-cols-1",
                  )}
                >
                  {sectorLinks.map((item) => (
                    <div key={item.href} className="flex flex-col">
                      <Link
                        href={item.href}
                        className="group flex items-start gap-3 rounded-xl px-3 py-2 text-base font-medium text-brand-ink/80 transition-colors hover:bg-slate-100 hover:text-brand-green dark:text-slate-200 dark:hover:bg-slate-800"
                        onClick={() => setDesktopSectorsOpen(false)}
                      >
                        <span
                          className="text-xl flex-shrink-0 mt-1"
                          aria-hidden
                        >
                          {item.icon}
                        </span>
                        <div className="flex-1">
                          <div className="font-semibold group-hover:text-brand-green">
                            {item.label}
                          </div>
                          {item.description && (
                            <div className="text-xs text-slate-600 dark:text-slate-400 mt-0.5 line-clamp-2">
                              {item.description}
                            </div>
                          )}
                        </div>
                      </Link>
                      {item.subPages && (
                        <div className="ml-11 mt-1 space-y-0.5">
                          {item.subPages.map((sub) => (
                            <Link
                              key={sub.href}
                              href={sub.href}
                              className="block px-3 py-1 text-xs text-slate-600 hover:text-brand-green hover:bg-slate-50 dark:text-slate-400 dark:hover:text-brand-green dark:hover:bg-slate-800/50 rounded"
                              onClick={() => setDesktopSectorsOpen(false)}
                            >
                              → {sub.label}
                            </Link>
                          ))}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </li>
          {navLinks.slice(2).map((item) => (
            <li key={item.href}>
              <Link
                href={item.href}
                className="inline-flex items-center h-9 text-sm font-semibold text-brand-ink/80 transition-colors hover:text-brand-green dark:text-slate-200 dark:hover:text-brand-green"
              >
                {item.label}
              </Link>
            </li>
          ))}
        </ul>
        <div
          className={classNames(
            "hidden shrink-0 items-center gap-3 md:flex",
            isRTL ? "flex-row-reverse ml-6" : "ml-auto flex-row",
          )}
        >
          <LangSwitcher lang={lang} />
          <ThemeToggle />
          <span
            className="hidden h-5 w-px bg-slate-200 dark:bg-slate-700 md:inline"
            aria-hidden
          />
          <Link
            href={linkTo("/login")}
            className="text-base font-medium text-brand-ink/70 transition-colors hover:text-brand-green dark:text-slate-300 dark:hover:text-brand-green md:px-4 md:py-3"
          >
            {isRTL ? t.login : "Login"}
          </Link>
          <Link
            href={linkTo("/signup")}
            className="rounded-lg bg-brand-green px-6 py-3 text-base font-semibold text-white transition-colors hover:bg-brand-greenHover"
          >
            {isRTL ? t.signup : "Sign Up"}
          </Link>
        </div>
      </nav>
      {mobileOpen && (
        <div
          id="mobile-nav"
          className={classNames(
            "md:hidden",
            "border-t border-slate-200 bg-white px-4 pb-6 shadow-sm dark:border-slate-800 dark:bg-slate-900",
          )}
        >
          <ul
            className={classNames(
              "flex flex-col gap-4 pt-4 text-base font-medium",
              isRTL ? "text-right" : "text-left",
            )}
          >
            {navLinks.slice(0, 2).map((item) => (
              <li key={item.href}>
                <Link
                  href={item.href}
                  className="block rounded-lg px-2 py-2 transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
                  onClick={closeMobile}
                >
                  {item.label}
                </Link>
              </li>
            ))}
            <li>
              <button
                type="button"
                onClick={() => setMobileFeaturesOpen((prev) => !prev)}
                className="flex w-full items-center justify-between rounded-lg px-2 py-2 transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
                aria-expanded={mobileFeaturesOpen}
              >
                <span>{t.features}</span>
                <span aria-hidden>{mobileFeaturesOpen ? "▴" : "▾"}</span>
              </button>
              {mobileFeaturesOpen && (
                <ul
                  className={classNames(
                    "mt-2 flex flex-col gap-2 rounded-xl bg-slate-50 p-3 dark:bg-slate-900/60",
                    isRTL ? "text-right" : "text-left",
                  )}
                >
                  {featureLinks.map((item) => (
                    <li key={item.href}>
                      <Link
                        href={item.href}
                        className="flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium text-brand-ink/80 transition-colors hover:bg-slate-100 hover:text-brand-green dark:text-slate-200 dark:hover:bg-slate-800"
                        onClick={closeMobile}
                      >
                        <span className="text-base" aria-hidden>
                          {item.icon}
                        </span>
                        <span>{item.label}</span>
                      </Link>
                    </li>
                  ))}
                </ul>
              )}
            </li>
            <li>
              <button
                type="button"
                onClick={() => setMobileSectorsOpen((prev) => !prev)}
                className="flex w-full items-center justify-between rounded-lg px-2 py-2 transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
                aria-expanded={mobileSectorsOpen}
              >
                <span>{lang === "ar" ? "القطاعات" : "Sectors"}</span>
                <span aria-hidden>{mobileSectorsOpen ? "▴" : "▾"}</span>
              </button>
              {mobileSectorsOpen && (
                <ul
                  className={classNames(
                    "mt-2 flex flex-col gap-2 rounded-xl bg-slate-50 p-3 dark:bg-slate-900/60",
                    isRTL ? "text-right" : "text-left",
                  )}
                >
                  {sectorLinks.map((item) => (
                    <li key={item.href} className="flex flex-col">
                      <Link
                        href={item.href}
                        className="group flex items-start gap-3 rounded-lg px-3 py-2 text-sm font-medium text-brand-ink/80 transition-colors hover:bg-slate-100 hover:text-brand-green dark:text-slate-200 dark:hover:bg-slate-800"
                        onClick={closeMobile}
                      >
                        <span
                          className="text-base flex-shrink-0 mt-0.5"
                          aria-hidden
                        >
                          {item.icon}
                        </span>
                        <div className="flex-1">
                          <div className="font-semibold">{item.label}</div>
                          {item.description && (
                            <div className="text-xs text-slate-600 dark:text-slate-400 mt-0.5">
                              {item.description}
                            </div>
                          )}
                        </div>
                      </Link>
                      {item.subPages && (
                        <div className="ml-9 mt-1 space-y-0.5">
                          {item.subPages.map((sub) => (
                            <Link
                              key={sub.href}
                              href={sub.href}
                              className="block px-3 py-1 text-xs text-slate-600 hover:text-brand-green dark:text-slate-400"
                              onClick={closeMobile}
                            >
                              → {sub.label}
                            </Link>
                          ))}
                        </div>
                      )}
                    </li>
                  ))}
                </ul>
              )}
            </li>
            {navLinks.slice(2).map((item) => (
              <li key={item.href}>
                <Link
                  href={item.href}
                  className="block rounded-lg px-2 py-2 transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
                  onClick={closeMobile}
                >
                  {item.label}
                </Link>
              </li>
            ))}
          </ul>
          <div
            className={classNames(
              "mt-6 flex flex-col gap-3 rounded-xl border border-slate-100 bg-slate-50 p-4 dark:border-slate-800 dark:bg-slate-900/80",
              isRTL ? "text-right" : "text-left",
            )}
          >
            <div className="flex items-center justify-between">
              <LangSwitcher lang={lang} />
              <ThemeToggle />
            </div>
            <Link
              href={linkTo("/login")}
              className="rounded-lg border border-slate-200 px-4 py-3 text-center text-base font-medium text-brand-ink/80 transition-colors hover:border-brand-green hover:text-brand-green dark:border-slate-700 dark:text-slate-200"
              onClick={closeMobile}
            >
              {isRTL ? t.login : "Login"}
            </Link>
            <Link
              href={linkTo("/signup")}
              className="rounded-lg bg-brand-green px-4 py-3 text-center text-base font-semibold text-white transition-colors hover:bg-brand-greenHover"
              onClick={closeMobile}
            >
              {isRTL ? t.signup : "Sign Up"}
            </Link>
          </div>
        </div>
      )}
    </header>
  );
}
