"use client";

import Link from "next/link";
import Image from "next/image";
import { useState, useEffect } from "react";
import { ChevronRight, ChevronDown } from "lucide-react";
import { NAV } from "@/lib/navigation";
import { cnMerge } from "@/lib/utils";
import { getBlogs, type Blog } from "@/services/blogs";

export function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [activeTab, setActiveTab] = useState<string>("About Us");

  // Latest blogs for navigation
  const [navBlogs, setNavBlogs] = useState<Blog[]>([]);

  // SCROLL

  useEffect(() => {
    const handleScroll = () => {
      setScrolled(window.scrollY > 50);
    };

    window.addEventListener("scroll", handleScroll, {
  passive: true,
});

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  // LOCK BODY SCROLL WHEN MENU IS OPEN

  useEffect(() => {
    if (isMenuOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }

    return () => {
      document.body.style.overflow = "";
    };
  }, [isMenuOpen]);

  // FETCH LATEST 4 BLOGS
  useEffect(() => {
    if (!isMenuOpen || navBlogs.length > 0) return;

    const loadNavigationBlogs = async () => {
      try {
        const response = await getBlogs({
          sort: "latest",
          limit: 4,
        });

        const latestBlogs = response.data
          .filter(
            (blog) =>
              blog.status === "Published" &&
              Boolean(blog.coverImage) &&
              Boolean(blog.title) &&
              Boolean(blog.excerpt)
          )
          .slice(0, 4);

        setNavBlogs(latestBlogs);
      } catch (error) {
        console.error(
          "Failed to load navigation blogs:",
          error
        );

        setNavBlogs([]);
      }
    };

    loadNavigationBlogs();
  }, [isMenuOpen, navBlogs.length]);

  // CURRENT GROUP
  const currentGroup = NAV.find(
    (group) => group.label === activeTab
  );

  // Remove About from main category list
  const mainNavGroups = NAV;

  const showScrolledBg = scrolled || isMenuOpen;

  const isBlogsTab = activeTab === "Blogs";

  return (
    <>
      {/* NAVBAR */}
      <header
        className={cnMerge(
          "fixed inset-x-0 top-0 z-[1000] border-b transition-all duration-300 ease-in-out",
          showScrolledBg
            ? "bg-ivory/95 backdrop-blur-md border-espresso/10 shadow-md"
            : "bg-transparent border-transparent"
        )}
      >
        <div className="mx-auto px-6 flex h-14 max-w-7xl items-center justify-between">

          {/* LEFT — MENU */}
          <div className="w-1/3 flex justify-start">
            <button
              onClick={() =>
                setIsMenuOpen(!isMenuOpen)
              }
              aria-expanded={isMenuOpen}
              aria-label={
                isMenuOpen
                  ? "Close menu"
                  : "Open menu"
              }
              className="group flex min-h-10 min-w-10 items-center justify-center gap-2 text-[10px] font-sans font-medium uppercase tracking-luxury text-[#d6ad5b] transition-colors hover:text-espresso focus:outline-none sm:min-h-0 sm:min-w-0 sm:justify-start sm:gap-3 sm:text-xs lg:text-sm"
            >
              {/* Animated hamburger */}
              <div className="relative flex h-3 w-4 items-center justify-center sm:h-4 sm:w-5">
                <svg
                  className="h-3 w-4 sm:h-4 sm:w-5"
                  viewBox="0 0 20 16"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                >
                  <line
                    x1="2"
                    y1="3"
                    x2="18"
                    y2="3"
                    className={cnMerge(
                      "transition-all duration-300 origin-center",
                      isMenuOpen
                        ? "rotate-45 translate-y-[5px] stroke-current"
                        : "stroke-[#d6ad5b] group-hover:stroke-espresso"
                    )}
                  />

                  <line
                    x1="2"
                    y1="8"
                    x2="18"
                    y2="8"
                    className={cnMerge(
                      "transition-all duration-300",
                      isMenuOpen
                        ? "opacity-0"
                        : "opacity-100",
                      "stroke-[#d6ad5b] group-hover:stroke-espresso"
                    )}
                  />

                  <line
                    x1="2"
                    y1="13"
                    x2="18"
                    y2="13"
                    className={cnMerge(
                      "transition-all duration-300 origin-center",
                      isMenuOpen
                        ? "-rotate-45 -translate-y-[5px] stroke-current"
                        : "stroke-[#d6ad5b] group-hover:stroke-espresso"
                    )}
                  />
                </svg>
              </div>

              <span className="hidden sm:inline transition-colors duration-300 text-[#d6ad5b] group-hover:text-espresso">
                {isMenuOpen ? "Close" : "Menu"}
              </span>
            </button>
          </div>

          {/* CENTER — LOGO */}
          <div className="flex w-1/3 justify-center items-center mt-2">
            <Link
              href="/"
              title="The Grand Heritage Resorts"
              onClick={() =>
                setIsMenuOpen(false)
              }
              aria-label="The Grand Heritage Resorts — Home"
              className="transition-transform duration-300 hover:scale-105"
            >
              <Image
                src="https://pub-b0bc1a7c71a54576bbf43595e30e6188.r2.dev/images/hero/the-grand-heritage-resorts-logo.png"
                alt="The Grand Heritage Resorts"
                title="The Grand Heritage Resorts"
                width={300}
                height={86}
                priority
                quality={75}
                className="h-[140px] w-auto object-contain transition-all duration-300"
              />
            </Link>
          </div>

          {/* RIGHT — BOOK */}
          <div className="w-1/3 flex justify-end">
            <Link
              href="/enquire-now"
              title="Enquire Now"
              onClick={() =>
                setIsMenuOpen(false)
              }
              className="rounded-full bg-[#d6ad5b] px-3 py-2 text-[10px] font-sans font-medium uppercase tracking-luxury text-ivory shadow-md transition-all hover:bg-espresso hover:shadow-lg active:scale-95 sm:px-5 sm:py-2.5 sm:text-[11px] lg:px-6 lg:text-xs"
            >
              Enquire Now
            </Link>
          </div>
        </div>
      </header>

      {/* FULL SCREEN MENU */}
      {isMenuOpen && (
        <div
          className={cnMerge(
            "fixed inset-0 z-[900] bg-ivory border-b border-espresso/10 transition-all duration-350 ease-in-out overflow-y-auto pt-16 md:pt-24 pb-12",
            isMenuOpen
              ? "opacity-100 translate-y-0"
              : "opacity-0 -translate-y-4 pointer-events-none"
          )}
        >
          <div className="mx-auto max-w-7xl px-6 py-6 grid grid-cols-1 lg:grid-cols-12 gap-12 items-start">

            {/* LEFT — MAIN CATEGORY LIST */}
            <div className="lg:col-span-5 flex flex-col space-y-2 md:space-y-6">

              {mainNavGroups.map((group) => {
                const isActive =
                  activeTab === group.label;

                return (
                  <div
                    key={group.label}
                    className={cnMerge(
                      "relative transition-all duration-300",
                      isMenuOpen
                        ? "opacity-100"
                        : "opacity-0 pointer-events-none"
                    )}
                  >

                    {/* DESKTOP CATEGORY */}
                    <Link
                      href={group.to}
                      title={group.label}
                      onClick={() => {
                        setActiveTab(group.label);
                        setIsMenuOpen(false);
                      }}
                      onMouseEnter={() => {
                        if (window.innerWidth >= 1024) {
                          setActiveTab(group.label);
                        }
                      }}
                      className={cnMerge(
                        "hidden lg:flex",
                        "font-serif text-3xl md:text-5xl font-normal text-left tracking-tight leading-tight focus:outline-none items-center gap-3 transition-all duration-300 hover:pl-3 group/btn",
                        isActive
                          ? "text-[#d6ad5b] italic pl-3"
                          : "text-espresso hover:text-[#d6ad5b]"
                      )}
                    >
                      <span className="relative py-1">
                        {group.label}

                        <span
                          className={cnMerge(
                            "absolute bottom-0 left-0 h-[1.5px] bg-[#d6ad5b] transition-all duration-300",
                            isActive
                              ? "w-full"
                              : "w-0 group-hover/btn:w-2/3"
                          )}
                        />
                      </span>

                      {isActive && (
                        <ChevronRight className="h-6 w-6 text-[#d6ad5b] shrink-0" />
                      )}
                    </Link>

                    {/* MOBILE / TABLET CATEGORY ROW */}
                    <div className="lg:hidden flex items-center justify-start">
                      <Link
                        href={group.to}
                        title={group.label}
                        onClick={() => setIsMenuOpen(false)}
                        className={cnMerge(
                          "group relative py-4",
                          "font-serif text-2xl sm:text-3xl font-normal",
                          "tracking-tight leading-tight",
                          "transition-all duration-300",
                          isActive
                            ? "text-[#d6ad5b] italic pl-3"
                            : "text-espresso hover:text-[#d6ad5b]"
                        )}
                      >
                        <span className="relative">
                          {group.label}

                          <span
                            className={cnMerge(
                              "absolute -bottom-1 left-0 h-[1.5px] bg-[#d6ad5b] transition-all duration-300",
                              isActive
                                ? "w-full"
                                : "w-0 group-hover:w-2/3"
                            )}
                          />
                        </span>
                      </Link>

                      {/* Only show dropdown arrow when the group has children */}
                      {(group.children.length > 0 ||
                      group.label === "Blogs") && (
                        <button
                          type="button"
                          aria-label={
                            isActive
                              ? `Close ${group.label} submenu`
                              : `Open ${group.label} submenu`
                          }
                          aria-expanded={isActive}
                          onClick={() => {
                            setActiveTab(
                              isActive
                                ? ""
                                : group.label
                            );
                          }}
                          className={cnMerge(
                            "ml-2 flex h-10 w-10 shrink-0 items-center justify-center",
                            "text-[#d6ad5b]",
                            "transition-all duration-300",
                            isActive
                              ? "translate-x-1"
                              : "hover:text-espresso"
                          )}
                        >
                          <ChevronDown
                            className={cnMerge(
                              "h-5 w-5 transition-transform duration-300",
                              isActive && "rotate-180"
                            )}
                          />
                        </button>
                      )}
                    </div>

                    {/* =================================================
                        MOBILE CHILDREN / OVERVIEW
                    ================================================= */}
                    {(group.children.length > 0 || group.label === "Blogs") && (
                      <div
                        className={cnMerge(
                          "lg:hidden overflow-hidden transition-all duration-350 ease-in-out",
                          isActive
                            ? "max-h-[3000px] opacity-100"
                            : "max-h-0 opacity-0"
                        )}
                      >
                      <div className="bg-cream/40 px-4 py-5">

                        <span className="font-sans text-[9px] font-normal uppercase tracking-widest-x text-[#d6ad5b] block mb-5">
                          {group.label} Overview
                        </span>

                        {/* =================================================
                            BLOGS
                        ================================================= */}
                        {group.label === "Blogs" ? (
                          navBlogs.length > 0 ? (
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">

                              {navBlogs.map((blog) => (
                                <Link
                                  key={blog._id}
                                  href={`/blogs/${blog.slug}`}
                                  title={blog.title}
                                  onClick={() => {
                                    sessionStorage.setItem(
                                      "tghr-pending-blog-view",
                                      blog.slug
                                    );

                                    setIsMenuOpen(false);
                                  }}
                                  className="group block space-y-2"
                                >
                                  {/* Cover Image */}
                                  <div className="relative aspect-[16/10] w-full overflow-hidden bg-midnight border border-espresso/10 rounded-lg">
                                    <Image
                                      src={blog.coverImage!}
                                      alt={blog.title}
                                      title={blog.title}
                                      fill
                                      sizes="(max-width: 640px) 100vw, 50vw"
                                      quality={75}
                                      className="object-cover transition-transform duration-500 group-hover:scale-105"
                                    />
                                  </div>

                                  {/* Title */}
                                  <div className="pl-3 border-l border-transparent group-hover:border-[#d6ad5b] transition-all duration-300">

                                    <h4 className="font-serif text-base font-medium text-espresso group-hover:text-[#d6ad5b] transition-colors line-clamp-2">
                                      {blog.title}
                                    </h4>

                                    {/* Excerpt */}
                                    <p className="font-sans text-[10px] font-light text-espresso/70 mt-1 leading-relaxed line-clamp-2">
                                      {blog.excerpt}
                                    </p>

                                  </div>
                                </Link>
                              ))}

                            </div>
                          ) : (
                            <p className="font-sans text-xs text-espresso/50">
                              No blogs available.
                            </p>
                          )
                        ) : (
                          /* =================================================
                             NORMAL NAVIGATION CHILDREN
                          ================================================= */
                          <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">

                            {group.children.map(
                              (child) => (
                                <Link
                                  key={child.to}
                                  href={child.to}
                                  title={child.label}
                                  onClick={() =>
                                    setIsMenuOpen(false)
                                  }
                                  className="group block space-y-2"
                                >
                                  {child.image && (
                                    <div className="relative aspect-[16/10] w-full overflow-hidden bg-midnight border border-espresso/10 rounded-lg">
                                      <Image
                                        src={
                                          child.image
                                        }
                                        alt={
                                          child.label
                                        }
                                        title={
                                          child.label
                                        }
                                        fill
                                        sizes="(max-width: 640px) 100vw, 50vw"
                                        quality={75}
                                        className="object-cover transition-transform duration-500 group-hover:scale-105"
                                      />
                                    </div>
                                  )}

                                  <div className="pl-3 border-l border-transparent group-hover:border-[#d6ad5b] transition-all duration-300">

                                    <h4 className="font-serif text-base font-medium text-espresso group-hover:text-[#d6ad5b] transition-colors">
                                      {child.label}
                                    </h4>

                                    {child.description && (
                                      <p className="font-sans text-[10px] font-light text-espresso/70 mt-1 leading-relaxed">
                                        {
                                          child.description
                                        }
                                      </p>
                                    )}

                                  </div>
                                </Link>
                              )
                            )}

                          </div>
                        )}

                      </div>
                    </div>
                    )}
                  </div>
                );
              })}
            </div>

            {/* =====================================================
                RIGHT — DESKTOP OVERVIEW PANEL
            ===================================================== */}
            {(
              isBlogsTab ||
              (currentGroup && currentGroup.children.length > 0)
            ) && (
            <div className="hidden lg:block lg:col-span-7 bg-cream/40 p-8 border border-espresso/5 shadow-inner rounded-2xl">

              <span className="font-sans text-[9px] font-normal uppercase tracking-widest-x text-[#d6ad5b] block mb-6">
                {activeTab} Overview
              </span>

              {/* =================================================
                  BLOG OVERVIEW
              ================================================= */}
              {isBlogsTab ? (
                navBlogs.length > 0 ? (
                  <div className="grid gap-6 grid-cols-1 sm:grid-cols-2">

                    {navBlogs.map((blog) => (
                      <Link
                        key={blog._id}
                        href={`/blogs/${blog.slug}`}
                        title={blog.title}
                        onClick={() => {
                          sessionStorage.setItem(
                            "tghr-pending-blog-view",
                            blog.slug
                          );

                          setIsMenuOpen(false);
                        }}
                        className="group block space-y-3 pl-4 border-l border-transparent hover:border-[#d6ad5b] transition-all duration-300"
                      >
                        {/* Cover Image */}
                        <div className="relative aspect-[16/10] w-full overflow-hidden bg-midnight border border-espresso/10 rounded-lg">
                          <Image
                            src={blog.coverImage!}
                            alt={blog.title}
                            title={blog.title}
                            fill
                            sizes="(max-width: 768px) 50vw"
                            quality={75}
                            className="object-cover will-change-transform transition-transform duration-500 group-hover:scale-105"
                          />
                        </div>

                        {/* Title + Excerpt */}
                        <div>

                          <h4 className="font-serif text-sm font-medium text-espresso group-hover:text-[#d6ad5b] transition-colors line-clamp-2">
                            {blog.title}
                          </h4>

                          <p className="font-sans text-[10px] font-light text-espresso/70 mt-1 leading-relaxed line-clamp-2">
                            {blog.excerpt}
                          </p>

                        </div>
                      </Link>
                    ))}

                  </div>
                ) : (
                  <p className="font-sans text-xs text-espresso/50">
                    No blogs available.
                  </p>
                )
              ) : (
                /* =================================================
                   NORMAL NAVIGATION OVERVIEW
                ================================================= */
                currentGroup && (
                  <div className="grid gap-6 grid-cols-1 sm:grid-cols-2">

                    {currentGroup.children.map(
                      (child) => (
                        <Link
                          key={child.to}
                          href={child.to}
                          title={child.label}
                          onClick={() =>
                            setIsMenuOpen(false)
                          }
                          className="group block space-y-3 pl-4 border-l border-transparent hover:border-[#d6ad5b] transition-all duration-300"
                        >
                          {child.image && (
                            <div className="relative aspect-[16/10] w-full overflow-hidden bg-midnight border border-espresso/10 rounded-lg">
                              <Image
                                src={child.image}
                                alt={child.label}
                                title={child.label}
                                fill
                                sizes="(max-width: 768px) 100vw, 20vw"
                                quality={75}
                                className="object-cover will-change-transform transition-transform duration-500 group-hover:scale-105"
                              />
                            </div>
                          )}

                          <div>
                            <h4 className="font-serif text-sm font-medium text-espresso group-hover:text-[#d6ad5b] transition-colors">
                              {child.label}
                            </h4>

                            {child.description && (
                              <p className="font-sans text-[10px] font-light text-espresso/70 mt-1 leading-relaxed">
                                {child.description}
                              </p>
                            )}
                          </div>
                        </Link>
                      )
                    )}

                  </div>
                )
              )}

            </div>
            )}
          </div>
        </div>
      )}
    </>
  );
}

export default Navbar;