"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import {
  Menu,
  X,
  Home,
  Box,
  Briefcase,
  Newspaper,
  Search,
  Globe,
  LogIn,
  ChevronDown,
  Video,
  Music,
  Image as ImageIcon,
  FileText,
} from "lucide-react";

const LANDING_SECTION_IDS = new Set(["products", "services"]);

function scrollToSectionId(id: string) {
  document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });
}

export type LandingSiteNavProps = {
  /** GET form target for navbar search (e.g. `/news-services`). If omitted, search is display-only. */
  searchFormAction?: string;
  searchDefaultValue?: string;
  searchPlaceholder?: string;
  /** News hub pages: “Home” → `/news-services`, plus Konten submenu in drawer */
  newsHub?: boolean;
};

export default function LandingSiteNav({
  searchFormAction,
  searchDefaultValue = "",
  searchPlaceholder = "Search",
  newsHub = false,
}: LandingSiteNavProps) {
  const pathname = usePathname();
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [openKonten, setOpenKonten] = useState(false);

  useEffect(() => {
    if (pathname !== "/") return;
    const syncFromHash = () => {
      const raw = window.location.hash.replace(/^#/, "");
      if (!LANDING_SECTION_IDS.has(raw)) return;
      const el = document.getElementById(raw);
      if (!el) return;
      requestAnimationFrame(() =>
        el.scrollIntoView({ behavior: "smooth", block: "start" }),
      );
    };
    const t = window.setTimeout(syncFromHash, 0);
    window.addEventListener("hashchange", syncFromHash);
    return () => {
      window.clearTimeout(t);
      window.removeEventListener("hashchange", syncFromHash);
    };
  }, [pathname]);

  const homePath = newsHub ? "/news-services" : "/";

  const goHome = () => {
    setOpen(false);
    if (pathname === homePath) {
      window.scrollTo({ top: 0, behavior: "smooth" });
    } else {
      router.push(homePath);
    }
  };

  const searchField = (
    <div className="relative min-w-0 max-w-[min(100%,11rem)] flex-1 sm:max-w-none sm:flex-initial md:w-56 lg:w-64">
      <Search
        className="pointer-events-none absolute left-3.5 top-1/2 size-[18px] -translate-y-1/2 text-gray-400"
        aria-hidden
      />
      <input
        type="search"
        name="q"
        defaultValue={searchDefaultValue}
        placeholder={searchPlaceholder}
        className="w-full rounded-full border border-[#966314]/55 bg-white py-2 pl-10 pr-4 text-sm text-gray-900 placeholder:text-gray-400 outline-none focus-visible:ring-2 focus-visible:ring-[#966314]/30"
      />
    </div>
  );

  return (
    <>
      <nav
        className="fixed top-0 left-0 right-0 z-30 w-full border-b border-gray-100 bg-white/95 shadow-sm backdrop-blur-sm supports-[backdrop-filter]:bg-white/80"
        aria-label="Main"
      >
        <div className="container mx-auto flex items-center justify-between gap-4 px-4 py-4 md:px-6">
          <Link href="/" className="shrink-0">
            <Image
              src="/image/qudo1.png"
              alt="Qudoco"
              width={140}
              height={56}
              className="h-12 w-auto md:h-14"
              priority
            />
          </Link>

          <div className="flex min-w-0 flex-1 items-center justify-end gap-3 md:gap-5">
            {searchFormAction ? (
              <form
                method="get"
                action={searchFormAction}
                className="contents"
              >
                {searchField}
              </form>
            ) : (
              searchField
            )}

            <button
              type="button"
              className="hidden items-center gap-2 text-sm text-gray-800 sm:flex"
            >
              <Globe className="size-[18px] text-gray-600" strokeWidth={1.75} />
              English
            </button>

            <span
              className="hidden h-5 w-px shrink-0 bg-gray-300 sm:block"
              aria-hidden
            />

            <button
              type="button"
              onClick={() => setOpen(true)}
              className="flex items-center gap-2 text-sm font-semibold text-gray-900"
            >
              <Menu className="size-5 text-gray-900" strokeWidth={2} />
              Menu
            </button>
          </div>
        </div>
      </nav>

      {open ? (
        <button
          type="button"
          aria-label="Close menu"
          className="fixed inset-0 z-[90] bg-black/40"
          onClick={() => setOpen(false)}
        />
      ) : null}

      <aside
        className={`fixed top-0 right-0 z-[100] h-full w-[280px] bg-[#966314] text-white transition-transform duration-300 ${
          open ? "translate-x-0" : "translate-x-full"
        }`}
      >
        <div className="flex items-center justify-between border-b border-white/20 p-6">
          <div className="flex rounded-full bg-white text-sm font-semibold text-[#966314]">
            <button type="button" className="rounded-full bg-white px-3 py-1">
              ID
            </button>
            <button type="button" className="px-3 py-1">
              EN
            </button>
          </div>

          <button type="button" onClick={() => setOpen(false)}>
            <X />
          </button>
        </div>

        <nav className="flex flex-col gap-6 overflow-y-auto p-6 text-sm font-medium">
          <button
            type="button"
            className="w-full border-0 bg-transparent p-0 text-left text-inherit"
            onClick={goHome}
          >
            <MenuItem icon={<Home size={18} />} label="Home" />
          </button>

          {newsHub ? (
            <div className="-mt-2 border-b border-white/20 pb-2">
              <button
                type="button"
                className="flex w-full items-center justify-between border-0 bg-transparent py-1 text-left text-inherit"
                onClick={() => setOpenKonten((v) => !v)}
              >
                <span>Konten</span>
                <ChevronDown
                  size={18}
                  className={`transition-transform ${openKonten ? "rotate-180" : ""}`}
                />
              </button>
              <div
                className={`mt-2 space-y-1 overflow-hidden pl-2 transition-all ${
                  openKonten ? "max-h-60 opacity-100" : "max-h-0 opacity-0"
                }`}
              >
                <Link
                  href="/video/filter"
                  className="block rounded-md px-2 py-2 hover:bg-white/10"
                  onClick={() => setOpen(false)}
                >
                  <span className="flex items-center justify-between text-sm">
                    Audio Visual <Video size={16} />
                  </span>
                </Link>
                <Link
                  href="/audio/filter"
                  className="block rounded-md px-2 py-2 hover:bg-white/10"
                  onClick={() => setOpen(false)}
                >
                  <span className="flex items-center justify-between text-sm">
                    Audio <Music size={16} />
                  </span>
                </Link>
                <Link
                  href="/image/filter"
                  className="block rounded-md px-2 py-2 hover:bg-white/10"
                  onClick={() => setOpen(false)}
                >
                  <span className="flex items-center justify-between text-sm">
                    Foto <ImageIcon size={16} />
                  </span>
                </Link>
                <Link
                  href="/document/filter"
                  className="block rounded-md px-2 py-2 hover:bg-white/10"
                  onClick={() => setOpen(false)}
                >
                  <span className="flex items-center justify-between text-sm">
                    Teks <FileText size={16} />
                  </span>
                </Link>
              </div>
            </div>
          ) : null}

          <button
            type="button"
            className="w-full border-0 bg-transparent p-0 text-left text-inherit"
            onClick={() => {
              setOpen(false);
              if (pathname === "/") {
                scrollToSectionId("products");
              } else {
                router.push("/#products");
              }
            }}
          >
            <MenuItem icon={<Box size={18} />} label="Product" />
          </button>
          <button
            type="button"
            className="w-full border-0 bg-transparent p-0 text-left text-inherit"
            onClick={() => {
              setOpen(false);
              if (pathname === "/") {
                scrollToSectionId("services");
              } else {
                router.push("/#services");
              }
            }}
          >
            <MenuItem icon={<Briefcase size={18} />} label="Services" />
          </button>
          <Link href="/news-services?highlight=1" onClick={() => setOpen(false)}>
            <MenuItem
              icon={<Newspaper size={18} />}
              label="News and Services"
            />
          </Link>
          <Link href="/auth" onClick={() => setOpen(false)}>
            <MenuItem icon={<LogIn size={18} />} label="Login" />
          </Link>
        </nav>
      </aside>
    </>
  );
}

function MenuItem({ icon, label }: { icon: React.ReactNode; label: string }) {
  return (
    <div className="flex cursor-pointer items-center justify-between border-b border-white/20 pb-3">
      <span>{label}</span>
      {icon}
    </div>
  );
}
