import { Link, NavLink, useLocation } from "react-router-dom";
import { ChevronDown, Menu, X } from "lucide-react";
import { useEffect, useState } from "react";
import { useLocale } from "@/i18n/LocaleContext";
import { siteSettings } from "@/content/site-settings";
import { UI } from "@/i18n/translations";
import { getPath, type PageKey } from "@/i18n/routes";
import { cn } from "@/lib/utils";

/** Menu structure: top-level entries with optional dropdown children. */
type NavEntry = { key: PageKey; children?: PageKey[] };

const NAV_TREE: NavEntry[] = [
  { key: "municipality", children: ["mayor", "council", "services", "documents"] },
  { key: "community", children: ["communityPhotos", "activitiesPhotos", "developmentPlan", "townMap"] },
  { key: "businesses" },
  { key: "events" },
  { key: "publicNotices", children: ["minutes", "newsletters"] },
];

export function Header() {
  const { t, locale } = useLocale();
  const location = useLocation();
  const [open, setOpen] = useState(false);
  const [openSub, setOpenSub] = useState<PageKey | null>(null);
  const logo = (window as any).__CASCA_SITE__?.logo?.src || "";

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

  return (
    <header className="bg-background border-b border-border">
      <div className="container flex items-center justify-between gap-6 py-5">
        <Link reloadDocument to={getPath("home", locale)} className="flex items-center gap-3 group">
          {logo && (
            <img
              src={logo}
              alt=""
              width={56}
              height={56}
              className="h-12 w-12 sm:h-14 sm:w-14 object-contain"
            />
          )}
          <span className="font-display italic text-primary leading-tight text-xl sm:text-2xl md:text-[1.7rem]">
            <span className="block">
              {locale === "fr" ? "Municipalité de" : "Municipality of"}
            </span>
            <span className="block">{t(siteSettings.municipality.shortName)}</span>
          </span>
        </Link>

        {/* Desktop nav */}
        <nav aria-label="Primary" className="hidden lg:block">
          <ul className="flex items-center gap-1 text-[0.95rem]">
            {NAV_TREE.map((entry) => {
              const path = getPath(entry.key, locale);
              const hasChildren = !!entry.children?.length;
              if (!hasChildren) {
                return (
                  <li key={entry.key}>
                    <NavLink
                      reloadDocument
                      to={path}
                      end={entry.key === "home"}
                      className={({ isActive }) =>
                        cn(
                          "px-4 py-2 inline-block transition-colors",
                          "text-foreground/85 hover:text-primary",
                          "border-b-2 border-transparent",
                          isActive && "text-primary border-primary",
                        )
                      }
                    >
                      {t(UI.nav[entry.key])}
                    </NavLink>
                  </li>
                );
              }
              return (
                <li
                  key={entry.key}
                  className="relative"
                  onMouseEnter={() => setOpenSub(entry.key)}
                  onMouseLeave={() => setOpenSub(null)}
                >
                  <NavLink
                    reloadDocument
                    to={path}
                    className={({ isActive }) =>
                      cn(
                        "px-4 py-2 inline-flex items-center gap-1 transition-colors",
                        "text-foreground/85 hover:text-primary",
                        "border-b-2 border-transparent",
                        isActive && "text-primary border-primary",
                      )
                    }
                    onFocus={() => setOpenSub(entry.key)}
                  >
                    {t(UI.nav[entry.key])}
                    <ChevronDown className="h-3.5 w-3.5" aria-hidden />
                  </NavLink>
                  {openSub === entry.key && (
                    <ul className="absolute left-0 top-full z-50 min-w-[260px] bg-background border border-border shadow-lg py-2">
                      {entry.children!.map((childKey) => (
                        <li key={childKey}>
                          <NavLink
                            reloadDocument
                            to={getPath(childKey, locale)}
                            className={({ isActive }) =>
                              cn(
                                "block px-4 py-2 text-sm transition-colors",
                                isActive
                                  ? "text-primary bg-band-cream font-medium"
                                  : "text-foreground/85 hover:text-primary hover:bg-band-cream/60",
                              )
                            }
                          >
                            {t(UI.nav[childKey])}
                          </NavLink>
                        </li>
                      ))}
                    </ul>
                  )}
                </li>
              );
            })}
          </ul>
        </nav>

        <button
          type="button"
          aria-label="Menu"
          aria-expanded={open}
          onClick={() => setOpen((v) => !v)}
          className="lg:hidden inline-flex items-center justify-center rounded-sm border border-border p-2 text-primary"
        >
          {open ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
        </button>
      </div>

      {/* Mobile nav */}
      {open && (
        <nav aria-label="Primary mobile" className="lg:hidden border-t border-border bg-background">
          <ul className="container py-2">
            {NAV_TREE.map((entry) => (
              <li key={entry.key}>
                <NavLink
                  reloadDocument
                  to={getPath(entry.key, locale)}
                  end={entry.key === "home"}
                  className={({ isActive }) =>
                    cn(
                      "block px-2 py-3 border-b border-border/60 text-base",
                      isActive ? "text-primary font-semibold" : "text-foreground/85",
                    )
                  }
                >
                  {t(UI.nav[entry.key])}
                </NavLink>
                {entry.children && (
                  <ul className="pl-4 border-b border-border/60">
                    {entry.children.map((childKey) => (
                      <li key={childKey}>
                        <NavLink
                          reloadDocument
                          to={getPath(childKey, locale)}
                          className={({ isActive }) =>
                            cn(
                              "block px-2 py-2.5 text-sm text-foreground/75",
                              isActive && "text-primary font-medium",
                            )
                          }
                        >
                          {t(UI.nav[childKey])}
                        </NavLink>
                      </li>
                    ))}
                  </ul>
                )}
              </li>
            ))}
          </ul>
        </nav>
      )}
    </header>
  );
}