"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Menu, X } from "lucide-react";
import type { Dictionary, Locale } from "@/content/types";
import { Button } from "@/components/ui/Button";
import { LanguageSwitcher } from "@/components/layout/LanguageSwitcher";

export function Header({ dict, locale }: { dict: Dictionary; locale: Locale }) {
  const pathname = usePathname();
  const isHome = pathname === `/${locale}`;
  const [scrolled, setScrolled] = useState(!isHome);
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    if (!isHome) {
      setScrolled(true);
      return;
    }
    function onScroll() {
      setScrolled(window.scrollY > 40);
    }
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [isHome]);

  useEffect(() => {
    if (!menuOpen) return;
    // Jump to the top and lock the page in place so the in-flow panel below
    // is what the user sees, with nothing to scroll past it.
    window.scrollTo(0, 0);
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = previousOverflow;
    };
  }, [menuOpen]);

  useEffect(() => {
    const query = window.matchMedia("(min-width: 1024px)");
    function handleChange(e: MediaQueryListEvent) {
      if (e.matches) setMenuOpen(false);
    }
    query.addEventListener("change", handleChange);
    return () => query.removeEventListener("change", handleChange);
  }, []);

  const transparent = isHome && !scrolled && !menuOpen;

  const navItems = [
    { href: `/${locale}#about`, label: dict.nav.about },
    { href: `/${locale}#destinations`, label: dict.nav.destinations },
    { href: `/${locale}#experiences`, label: dict.nav.experiences },
    { href: `/${locale}/offers`, label: dict.nav.offers },
    { href: `/${locale}/gallery`, label: dict.nav.gallery },
    { href: `/${locale}#services`, label: dict.nav.services },
    { href: `/${locale}#contact`, label: dict.nav.contact },
  ];

  // Deliberately not using `position: fixed` for the mobile panel. On this
  // project it has proven unreliable on real iOS Safari/WebKit specifically
  // in RTL (multiple different fixed-positioning approaches all failed the
  // same way on-device despite working in every automated/desktop test).
  // Instead, the panel is a plain block element in normal document flow,
  // sized to the full device height, with the page scrolled to top and
  // body scroll locked while it's open — same full-screen takeover effect,
  // zero reliance on `position: fixed`.
  if (menuOpen) {
    return (
      <div className="relative z-50 flex min-h-dvh flex-col bg-white lg:hidden">
        <div className="flex items-center justify-between gap-4 px-4 py-3 sm:px-6">
          <Image
            src="/logo/full-logo-color.png"
            alt="Visit Chinguitti — Experience Mauritania"
            width={2000}
            height={467}
            className="h-12 w-auto sm:h-14"
          />
          <button
            type="button"
            onClick={() => setMenuOpen(false)}
            className="inline-flex shrink-0 items-center justify-center rounded-full p-2 text-charcoal-950"
            aria-label="Close menu"
          >
            <X size={24} />
          </button>
        </div>

        <nav className="flex flex-1 flex-col gap-1 px-4 py-4 sm:px-6">
          {navItems.map((item) => (
            <Link
              key={item.href}
              href={item.href}
              onClick={() => setMenuOpen(false)}
              className="rounded-lg py-3 text-base font-semibold text-charcoal-700 transition-colors hover:bg-charcoal-50/60 hover:text-charcoal-950"
            >
              {item.label}
            </Link>
          ))}
        </nav>

        <div className="flex items-center justify-between gap-4 border-t border-charcoal-950/10 px-4 py-4 sm:px-6">
          <LanguageSwitcher locale={locale} />
          <Button href={`/${locale}#booking`} variant="primary" onClick={() => setMenuOpen(false)}>
            {dict.nav.bookNow}
          </Button>
        </div>
      </div>
    );
  }

  return (
    <header
      className={`fixed inset-x-0 top-0 z-50 transition-colors duration-300 ${
        transparent
          ? "bg-transparent"
          : "bg-white/95 shadow-sm shadow-charcoal-950/5 backdrop-blur"
      }`}
    >
      <div className="mx-auto flex max-w-7xl items-center justify-between gap-4 px-4 py-3 sm:px-6 lg:px-8">
        <Link href={`/${locale}`} className="flex min-w-0 items-center gap-2">
          <Image
            src={transparent ? "/logo/full-logo-white.png" : "/logo/full-logo-color.png"}
            alt="Visit Chinguitti — Experience Mauritania"
            width={2000}
            height={467}
            priority
            className="h-12 w-auto sm:h-14"
          />
        </Link>

        <nav className="hidden items-center gap-7 lg:flex">
          {navItems.map((item) => (
            <Link
              key={item.href}
              href={item.href}
              className={`text-sm font-semibold tracking-wide transition-colors ${
                transparent ? "text-white/90 hover:text-white" : "text-charcoal-700 hover:text-charcoal-950"
              }`}
            >
              {item.label}
            </Link>
          ))}
        </nav>

        <div className="hidden items-center gap-4 lg:flex">
          <LanguageSwitcher locale={locale} light={transparent} />
          <Button href={`/${locale}#booking`} variant="primary" className="!px-5 !py-2.5 text-xs">
            {dict.nav.bookNow}
          </Button>
        </div>

        <button
          type="button"
          onClick={() => setMenuOpen((v) => !v)}
          className={`inline-flex shrink-0 items-center justify-center rounded-full p-2 lg:hidden ${
            transparent ? "text-white" : "text-charcoal-950"
          }`}
          aria-label="Toggle menu"
          aria-expanded={menuOpen}
        >
          <Menu size={24} />
        </button>
      </div>
    </header>
  );
}
