"use client";

import { useState, useRef, useEffect } from "react";
import { createPortal } from "react-dom";
import Link from "next/link";
import {
  navCategories,
  navCategoryOrder,
  navCategoryLabels,
} from "@/lib/shop/navCategories";

/** Nav items from single source: navCategories.ts */
const navItems = navCategoryOrder.map((key) => ({
  key,
  label: navCategoryLabels[key],
  href: `/shop/${navCategories[key].slug}`,
  subcategories: navCategories[key].subcategories,
}));

function ChevronDown({ open }: { open?: boolean }) {
  return (
    <svg
      width="12"
      height="12"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      className={`shrink-0 transition-transform duration-200 ${open ? "rotate-180" : ""}`}
      aria-hidden
    >
      <polyline points="6 9 12 15 18 9" />
    </svg>
  );
}

export function MobileNavButtons() {
  const [openLabel, setOpenLabel] = useState<string | null>(null);
  const [dropdownTop, setDropdownTop] = useState<number | null>(null);
  const triggerRefs = useRef<Record<string, HTMLButtonElement | null>>({});
  const containerRef = useRef<HTMLDivElement>(null);

  const openItem = openLabel ? navItems.find((i) => i.label === openLabel) : null;

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        const target = e.target as HTMLElement;
        if (!target.closest("[role='menu']")) setOpenLabel(null);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    if (!openLabel) {
      setDropdownTop(null);
      return;
    }
    const el = triggerRefs.current[openLabel];
    if (el) {
      const r = el.getBoundingClientRect();
      setDropdownTop(r.bottom + 4);
    }
  }, [openLabel]);

  return (
    <div ref={containerRef} className="border-b border-[#e8f7f6] bg-white">
      <div className="scrollbar-hide flex items-center gap-2 overflow-x-auto px-4 py-3">
        {navItems.map((item) => {
          const isOpen = openLabel === item.label;
          return (
            <button
              key={item.label}
              ref={(el) => {
                triggerRefs.current[item.label] = el;
              }}
              type="button"
              onClick={() => setOpenLabel(isOpen ? null : item.label)}
              className={`shrink-0 flex items-center gap-1.5 rounded-full border px-4 py-2 font-sans text-xs font-medium transition-colors ${
                isOpen
                  ? "border-[#38a99f]/30 bg-[#e8f7f6] text-[#236f6b]"
                  : "border-transparent text-[#3d5554] hover:bg-[#e8f7f6] hover:text-[#236f6b]"
              }`}
              aria-expanded={isOpen}
              aria-haspopup="true"
              aria-controls={isOpen ? `nav-dropdown-${item.label}` : undefined}
              id={`nav-trigger-${item.label}`}
            >
              {item.label}
              <ChevronDown open={isOpen} />
            </button>
          );
        })}
      </div>

          {openItem &&
        dropdownTop != null &&
        typeof document !== "undefined" &&
        createPortal(
          <div
            id={`nav-dropdown-${openItem.label}`}
            role="menu"
            className="fixed z-[100] max-h-[60vh] overflow-y-auto rounded-xl border border-[#e8f7f6] bg-white py-2 shadow-lg"
            style={{
              top: dropdownTop,
              left: 16,
              right: 16,
            }}
          >
            {openItem.subcategories.map((sub) => (
              <Link
                key={sub.slug}
                href={`/shop/${navCategories[openItem.key].slug}/${sub.slug}`}
                role="menuitem"
                className="block px-4 py-2.5 font-sans text-sm text-[#3d5554] no-underline transition-colors hover:bg-[#e8f7f6] hover:text-[#236f6b]"
                onClick={() => setOpenLabel(null)}
              >
                {sub.name}
              </Link>
            ))}
            <div className="mt-2 border-t border-[#e8f7f6] pt-2">
              <Link
                href={openItem.href}
                className="block px-4 py-2 font-sans text-sm font-medium text-[#236f6b] no-underline transition-colors hover:bg-[#e8f7f6]"
                onClick={() => setOpenLabel(null)}
              >
                Browse all {openItem.label} →
              </Link>
            </div>
          </div>,
          document.body
        )}
    </div>
  );
}
