"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Menu } from "lucide-react";
import { Logo } from "@/components/common/Logo";
import { ThemeToggle } from "@/components/theme/ThemeToggle";
import { LanguageDropdown } from "@/components/i18n/LanguageDropdown";
import { ButtonLink } from "@/components/common/Button";
import { Container } from "@/components/common/Container";
import { MobileMenu } from "./MobileMenu";
import { NAV_LINKS } from "@/constants/site";
import { useTranslation } from "@/hooks/useTranslation";
import { useAuth } from "@/hooks/useAuth";
import { useAgentAuth } from "@/hooks/useAgentAuth";
import { cn } from "@/lib/utils";

export function Header() {
  const { t, locale } = useTranslation();
  const { user, hydrated } = useAuth();
  const { user: agentUser, hydrated: agentHydrated } = useAgentAuth();
  const pathname = usePathname();
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);

  useEffect(() => {
    function onScroll() {
      setScrolled(window.scrollY > 8);
    }
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    setMobileOpen(false);
  }, [pathname]);

  const isAuthenticated = hydrated && !!user;
  const isAgentAuthenticated = agentHydrated && !!agentUser;

  return (
    <>
      <a href="#main-content" className="skip-link">
        Skip to main content
      </a>

      <header
        className={cn(
          "sticky top-0 z-40 w-full transition-all duration-300 ease-snappy",
          scrolled
            ? "border-b border-slate-200/60 bg-white/70 backdrop-blur-xl dark:border-slate-800/60 dark:bg-slate-950/70"
            : "border-b border-transparent bg-transparent",
        )}
      >
        <Container
          className={cn(
            "grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-4 transition-[height] duration-300 ease-snappy",
            // Spanish nav labels run slightly longer than the other shipped locales —
            // a touch more room here only for "es" keeps every other locale untouched.
            locale === "es" && "max-w-[1360px]",
            scrolled ? "h-14" : "h-[60px]",
          )}
        >
          <Logo className="shrink-0" />

          {/* Flexible middle column — its own grid track, so nav text length (which
              varies a lot by locale) can never push into or overlap the right-side
              controls the way it could in the old flex `justify-between` layout.
              `scrollbar-hide` is a last-resort escape hatch if a locale is ever wide
              enough to exceed the track — it never has to activate at ≥1200px in
              practice, but it's a strictly safer failure mode than overlap. */}
          <nav
            className="hidden min-w-0 items-center gap-0.5 overflow-x-auto scrollbar-hide 2xl:gap-1 xl:flex"
            aria-label="Primary"
          >
            {NAV_LINKS.map((link) => {
              const active =
                link.href === "/"
                  ? pathname === "/"
                  : pathname.startsWith(link.href);
              return (
                <Link
                  key={link.href}
                  href={link.href}
                  aria-current={active ? "page" : undefined}
                  className={cn(
                    "relative px-1.5 py-2 text-[12.5px] 2xl:px-3 2xl:text-[13.5px] font-medium transition-colors duration-200 whitespace-nowrap",
                    active
                      ? "text-slate-900 dark:text-white"
                      : "text-slate-600 hover:text-slate-900 dark:text-slate-400 dark:hover:text-white",
                  )}
                >
                  {t(link.key)}
                  {active && (
                    <span
                      aria-hidden
                      className="absolute bottom-1 left-3 right-3 h-[2px] rounded-full bg-slate-900 dark:bg-white"
                    />
                  )}
                </Link>
              );
            })}
          </nav>

          <div className="flex shrink-0 items-center gap-1 justify-self-end">
            <LanguageDropdown compact />
            <ThemeToggle />

            <div
              aria-hidden
              className="mx-2 h-5 w-px bg-slate-200 dark:bg-slate-800"
            />

            {isAuthenticated ? (
              <ButtonLink
                href="/dashboard"
                variant="primary"
                size="sm"
                className="hidden xl:inline-flex"
              >
                {t("app.nav.dashboard")}
              </ButtonLink>
            ) : isAgentAuthenticated ? (
              <ButtonLink
                href="/agent/dashboard"
                variant="primary"
                size="sm"
                className="hidden xl:inline-flex"
              >
                {t("app.nav.dashboard")}
              </ButtonLink>
            ) : (
              <>
                <Link
                  href="/login"
                  className="hidden rounded-lg px-2 py-2 text-[12.5px] 2xl:px-3 2xl:text-[13.5px] font-medium text-slate-600 transition-colors duration-200 hover:text-slate-900 dark:text-slate-400 dark:hover:text-white xl:inline-flex whitespace-nowrap"
                >
                  {t("nav.signIn")}
                </Link>
                <ButtonLink
                  href="/register"
                  variant="primary"
                  size="sm"
                  className="hidden xl:inline-flex"
                >
                  {t("nav.getStarted")}
                </ButtonLink>
              </>
            )}

            <button
              type="button"
              aria-label="Open menu"
              aria-expanded={mobileOpen}
              onClick={() => setMobileOpen(true)}
              className="inline-flex h-9 w-9 items-center justify-center rounded-lg text-slate-600 transition-colors duration-200 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-400 dark:hover:bg-slate-800/60 dark:hover:text-white xl:hidden"
            >
              <Menu className="h-5 w-5" />
            </button>
          </div>
        </Container>
      </header>
      <MobileMenu open={mobileOpen} onClose={() => setMobileOpen(false)} />
    </>
  );
}
