import Link from "next/link";
import { Suspense } from "react";
import Search from "./Search";
import { SearchSkeleton } from "@/components/common/skeleton/SearchSkeleton";
import LogoIcon from "@components/common/icons/LogoIcon";
import MobileMenuTrigger from "./MobileMenuTrigger";
import { CartAndUserActions } from "./CartAndUserActions";
import { NavigationSkeleton } from "./NavigationSkeleton";
import { ActionsSkeleton } from "./ActionsSkeleton";
import { NavbarErrorBoundary } from "@/components/error/ErrorBoundary";

import { GET_TREE_CATEGORIES } from "@/graphql";
import { cachedGraphQLRequest } from "@utils/hooks/useCache";
import { TreeCategoriesResponse } from "@/types/theme/category-tree";

export default async function Navbar() {

  const {data} = await cachedGraphQLRequest<TreeCategoriesResponse>(
      "category",
      GET_TREE_CATEGORIES,
      { parentId: 1 }
    );
  
  
    const categories = data?.treeCategories || [];
  
    const filteredCategories = categories
      .filter((cat: any) => cat.id !== "1")
      .map((cat: any) => {
        const translation = cat.translation;
        return {
          id: cat.id,
          name: translation?.name || "",
          slug: translation?.slug || "",
        };
      })
      .filter((item: any) => item.name && item.slug);
  
    const menuData = [
      { id: "all", name: "All", slug: "" },
      ...filteredCategories.slice(0, 3),
    ];
  

  return (
    <NavbarErrorBoundary>
      <header className="sticky top-0 z-10">
        <nav className="relative flex flex-col items-center justify-between gap-4 bg-neutral-50 p-4 dark:bg-neutral-900 md:flex-row lg:px-6 lg:py-4">
          <div className="flex w-full items-center justify-between gap-0 sm:gap-4">
            {/* 1. THE STATIC SHELL (Visible Instantly) */}
            <div className="flex max-w-fit gap-2 xl:gap-6">

              {/* 2. STATIC HOLE: Categories (Suspended) */}
              <Suspense fallback={<NavigationSkeleton />}>
                <MobileMenuTrigger menuData={menuData} />
              </Suspense>
              <Link
                className="flex-none h-9 w-36.5"
                href="/"
                aria-label="Go to homepage"
              >
                <LogoIcon />
              </Link>
              
            </div>

            <div className="flex-1 justify-center flex">
              <Suspense fallback={<SearchSkeleton />}>
                <Search search={false} />
              </Suspense>
            </div>

            {/* 3. DYNAMIC HOLE: Auth & Cart (Blocked by Session/Cookies) */}
            <Suspense fallback={<ActionsSkeleton />}>
              <CartAndUserActions />
            </Suspense>
          </div>
        </nav>
      </header>
    </NavbarErrorBoundary>
  );
}
