"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Menu } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
  SheetClose,
} from "@/components/ui/sheet";
import { LocaleSwitcher } from "./locale-switcher";
import { SanityImage } from "./sanity-image";
import type { Dictionary } from "@/i18n";

export function Navbar({
  locale,
  dict,
  settings,
}: {
  locale: string;
  dict: Dictionary;
  settings?: { logo?: { asset?: unknown; lqip?: string } | null } | null;
}) {
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const pathname = usePathname();

  useEffect(() => {
    document.documentElement.lang = locale;
  }, [locale]);

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

  useEffect(() => {
    setOpen(false);
  }, [pathname]);

  const logo = settings?.logo;
  const base = `/${locale}`;
  const isHome = pathname === base || pathname === `${base}/`;
  // Transparent over the home hero at the top; solid maroon everywhere else.
  const transparent = isHome && !scrolled;

  const links = [
    { href: `${base}/`, label: dict.nav.home },
    { href: `${base}/about/`, label: dict.nav.about },
    { href: `${base}/ministries/`, label: dict.nav.ministries },
    { href: `${base}/events/`, label: dict.nav.events },
    { href: `${base}/sermons/`, label: dict.nav.sermons },
    { href: `${base}/blog/`, label: dict.nav.blog },
    { href: `${base}/leadership/`, label: dict.nav.leadership },
    { href: `${base}/contact/`, label: dict.nav.contact },
  ];

  const isActive = (href: string) =>
    href === `${base}/` ? isHome : pathname?.startsWith(href);

  const logoMark = (
    <span className="relative grid h-12 w-12 shrink-0 place-items-center overflow-hidden rounded-md bg-white p-1 shadow-sm">
      {logo ? (
        <SanityImage
          image={logo}
          alt={dict.brand.name}
          widths={[96, 144, 192]}
          sizes="48px"
          className="h-full w-full object-contain"
        />
      ) : (
        <span className="grid h-full w-full place-items-center font-display text-base font-bold text-brand">
          CT
        </span>
      )}
    </span>
  );

  return (
    <header
      className={`fixed inset-x-0 top-0 z-50 text-white transition-all duration-300 ${
        transparent
          ? "bg-transparent"
          : "bg-brand/95 shadow-sm backdrop-blur-md supports-backdrop-filter:bg-brand/85"
      }`}
    >
      <div className="mx-auto flex h-20 max-w-7xl items-center justify-between gap-4 px-5 sm:px-8">
        <Link href={`${base}/`} className="group flex items-center gap-3">
          {logoMark}
          <span className="leading-tight">
            <span className="block font-display text-sm font-bold tracking-tight">
              {dict.brand.name}
            </span>
            <span className="mt-1.5 block text-xs font-medium uppercase tracking-tight text-white/70">
              {dict.brand.sub}
            </span>
          </span>
        </Link>

        <nav className="hidden items-center gap-6 xl:flex">
          {links.slice(1).map((l) => (
            <Link
              key={l.href}
              href={l.href}
              className={`relative text-sm inline-block font-medium tracking-tight transition animate-link`}
            >
              {l.label}
              {isActive(l.href) && (
                <span
                  className={`absolute -bottom-1.5 left-0 h-1 w-full rounded-full bg-white transition-all duration-300 `}
                />
              )}
            </Link>
          ))}
        </nav>

        <div className="flex items-center gap-3">
          <LocaleSwitcher locale={locale} />
          <Button
            asChild
            variant="light"
            size="sm"
            className="hidden sm:inline-flex"
          >
            <Link href={`${base}/contact/`}>{dict.hero.primary}</Link>
          </Button>

          <Sheet open={open} onOpenChange={setOpen}>
            <SheetTrigger asChild>
              <button
                aria-label="Menu"
                className="grid h-10 w-10 place-items-center rounded-sm border border-white/40 text-white transition hover:bg-white/10 xl:hidden"
              >
                <Menu className="size-4" />
              </button>
            </SheetTrigger>
            <SheetContent side="right" className="p-0 text-ink">
              <SheetHeader className="border-b border-line">
                <SheetTitle className="flex items-center gap-3">
                  {logoMark}
                  <span className="leading-tight">
                    <span className="block font-display text-[15px] font-bold tracking-tight text-ink">
                      {dict.brand.name}
                    </span>
                    <span className="block text-[10px] font-medium tracking-[0.16em] text-muted">
                      {dict.brand.sub}
                    </span>
                  </span>
                </SheetTitle>
              </SheetHeader>
              <nav className="flex flex-col gap-1 px-4 py-4">
                {links.map((l) => (
                  <SheetClose asChild key={l.href}>
                    <Link
                      href={l.href}
                      className={`rounded-sm px-4 py-3 text-sm font-medium tracking-[0.04em] transition hover:bg-brand/5 hover:text-brand ${
                        isActive(l.href) ? "bg-brand/5 text-brand" : "text-ink"
                      }`}
                    >
                      {l.label}
                    </Link>
                  </SheetClose>
                ))}
              </nav>
              <div className="mt-auto p-4">
                <SheetClose asChild>
                  <Button asChild className="w-full">
                    <Link href={`${base}/contact/`}>{dict.hero.primary}</Link>
                  </Button>
                </SheetClose>
              </div>
            </SheetContent>
          </Sheet>
        </div>
      </div>
    </header>
  );
}
