"use client";

import { cn } from "@/app/lib/cn";
import { HamburgerMenu } from "iconsax-reactjs";
import { FC, useEffect, useRef, useState } from "react";
import AllProductsMenu from "./AllProductsMenu";

const menuItems = ["کارت ویزیت", "کاتالوگ", "بروشور", "کارت تبریک", "جعبه", "ساک دستی", "هدایای تبلیغاتی"];

const HeaderMenu: FC = () => {
  const [isAllProductsOpen, setIsAllProductsOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!isAllProductsOpen) return;

    const handlePointerDown = (event: MouseEvent) => {
      if (!containerRef.current?.contains(event.target as Node)) {
        setIsAllProductsOpen(false);
      }
    };

    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setIsAllProductsOpen(false);
      }
    };

    document.addEventListener("mousedown", handlePointerDown);
    document.addEventListener("keydown", handleEscape);

    return () => {
      document.removeEventListener("mousedown", handlePointerDown);
      document.removeEventListener("keydown", handleEscape);
    };
  }, [isAllProductsOpen]);

  return (
    <div ref={containerRef} className="relative h-14 sm:h-[72px] w-full flex-1 px-4 sm:px-8 lg:px-[120px]">
      <div className="flex h-full items-center gap-4 sm:gap-6 lg:gap-8 overflow-x-auto scrollbar-none [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden lg:justify-center">
        <button
          type="button"
          className={cn("flex items-center gap-2 font-bold transition-colors shrink-0 text-sm sm:text-base", isAllProductsOpen && "text-primary")}
          onClick={() => setIsAllProductsOpen((open) => !open)}
          aria-expanded={isAllProductsOpen}
          aria-haspopup="true"
        >
          <HamburgerMenu size={22} color="currentColor" />
          <span>همه محصولات</span>
        </button>

        {menuItems.map((item) => (
          <div key={item} className="font-bold shrink-0 whitespace-nowrap text-sm sm:text-base">
            {item}
          </div>
        ))}
      </div>

      {isAllProductsOpen && <AllProductsMenu />}
    </div>
  );
};

export default HeaderMenu;
