"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { Menu, X } from "lucide-react";
import { createPortal } from "react-dom";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

const NAV_LINKS = [
  { href: "/", label: "صفحه اصلی" },
  { href: "/blog", label: "وبلاگ" },
  { href: "/about", label: "درباره ما" },
  { href: "/faq", label: "سوالات متداول" },
] as const;

export function SiteHeaderNav({
  isLoggedIn,
  variant = "default",
}: {
  isLoggedIn: boolean;
  variant?: "default" | "overlay" | "select";
}) {
  const pathname = usePathname();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [mounted, setMounted] = useState(false);
  const isOverlay = variant === "overlay";
  const isSelect = variant === "select";

  const isActive = (href: string) => {
    if (href === "/") return pathname === "/";
    return pathname === href || pathname.startsWith(href + "/");
  };

  const navBase =
    "relative px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 active:scale-[0.98] md:px-4";
  const navLink = (href: string) =>
    `${navBase} ${
      isOverlay
        ? isActive(href)
          ? "font-semibold text-amber-200 underline decoration-amber-300/80 decoration-2 underline-offset-4"
          : "text-white/90 hover:bg-white/10 hover:text-white"
        : isActive(href)
          ? "font-semibold bg-primary/10 text-primary text-foreground underline decoration-2 decoration-primary underline-offset-4"
          : "text-muted-foreground hover:bg-muted/80 hover:text-foreground"
    }`;
  const mobileNavLink = (href: string) =>
    cn(
      "block rounded-xl px-4 py-3 text-base font-medium transition-colors active:scale-[0.98]",
      isActive(href)
        ? "bg-primary/10 font-semibold text-primary"
        : "text-foreground hover:bg-muted/80"
    );
  const ctaBase =
    "relative rounded-full text-sm font-semibold transition-all duration-200 active:scale-[0.98] md:px-5 md:py-2 md:text-sm";
  const ctaLink = (href: string) =>
    `${ctaBase} px-3.5 py-2 ${
      isSelect
        ? isActive(href)
          ? "bg-[#243824] text-white shadow-card-hover ring-2 ring-[#1a2e1a] ring-offset-2 ring-offset-background"
          : "bg-[#1a2e1a] text-white shadow-soft hover:bg-[#243824] hover:shadow-card-hover"
        : isOverlay
          ? "gradient-primary text-white shadow-[0_0_20px_rgba(139,92,246,0.4)] hover:shadow-[0_0_28px_rgba(168,85,247,0.55)]"
          : isActive(href)
            ? "bg-primary text-primary-foreground shadow-card-hover ring-2 ring-primary ring-offset-2 ring-offset-background"
            : "bg-primary text-primary-foreground shadow-soft hover:bg-primary/90 hover:shadow-card-hover"
    }`;

  const panelHref = isLoggedIn ? "/panel" : "/login";
  const panelLabel = isLoggedIn ? "پنل کاربری" : "ورود";

  useEffect(() => {
    setMobileOpen(false);
  }, [pathname]);

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!mobileOpen) return;

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") setMobileOpen(false);
    };

    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKeyDown);

    return () => {
      document.body.style.overflow = previousOverflow;
      window.removeEventListener("keydown", onKeyDown);
    };
  }, [mobileOpen]);

  return (
    <>
      <nav className="hidden items-center gap-1 md:flex">
        {NAV_LINKS.map(({ href, label }) => (
          <Link key={href} href={href} className={navLink(href)}>
            {label}
          </Link>
        ))}
        <Link href={panelHref} className={ctaLink(panelHref)}>
          {panelLabel}
        </Link>
      </nav>

      <div className="flex items-center gap-2 md:hidden">
        <Link href={panelHref} className={ctaLink(panelHref)}>
          {panelLabel}
        </Link>
        <Button
          type="button"
          variant="ghost"
          size="icon"
          aria-label={mobileOpen ? "بستن منو" : "باز کردن منو"}
          aria-expanded={mobileOpen}
          aria-controls="mobile-site-nav"
          onClick={() => setMobileOpen((open) => !open)}
          className={cn(
            "shrink-0",
            isOverlay
              ? "text-white hover:bg-white/10 hover:text-white"
              : "text-foreground hover:bg-muted/80"
          )}
        >
          {mobileOpen ? <X className="size-5" /> : <Menu className="size-5" />}
        </Button>
      </div>

      {mounted &&
        mobileOpen &&
        createPortal(
          <>
            <button
              type="button"
              aria-label="بستن منو"
              className="fixed inset-0 z-[9998] bg-black/40 md:hidden"
              onClick={() => setMobileOpen(false)}
            />
            <nav
              id="mobile-site-nav"
              className="fixed inset-y-0 right-0 z-[9999] flex w-[min(85vw,18rem)] flex-col border-l border-border/80 bg-[#fbf7f5] p-4 shadow-card-hover backdrop-blur-md supports-[backdrop-filter]:bg-[#fbf7f5]/95 md:hidden"
            >
              <div className="mb-4 flex items-center justify-between">
                <span className="text-sm font-semibold text-muted-foreground">
                  منو
                </span>
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  aria-label="بستن منو"
                  onClick={() => setMobileOpen(false)}
                >
                  <X className="size-5" />
                </Button>
              </div>
              <div className="flex flex-col gap-1">
                {NAV_LINKS.map(({ href, label }) => (
                  <Link
                    key={href}
                    href={href}
                    className={mobileNavLink(href)}
                    onClick={() => setMobileOpen(false)}
                  >
                    {label}
                  </Link>
                ))}
              </div>
            </nav>
          </>,
          document.body
        )}
    </>
  );
}
