"use client";

import React, { useEffect, useRef } from "react";
import { MenuCategory } from "@/data/menu";

interface CategoryNavProps {
  categories: MenuCategory[];
  activeCategoryId: string;
  icons: Record<string, string>;
}

export function CategoryNav({ categories, activeCategoryId, icons }: CategoryNavProps) {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!activeCategoryId || !containerRef.current) return;
    const el = containerRef.current.querySelector(
      `[data-id="${activeCategoryId}"]`
    ) as HTMLElement | null;
    el?.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center" });
  }, [activeCategoryId]);

  const scrollTo = (id: string) => {
    const el = document.getElementById(id);
    if (!el) return;
    const y = el.getBoundingClientRect().top + window.scrollY - 72;
    window.scrollTo({ top: y, behavior: "smooth" });
  };

  return (
    <div
      className="sticky top-0 z-50 border-b"
      style={{
        background: "rgba(250, 248, 243, 0.93)",
        backdropFilter: "blur(18px)",
        WebkitBackdropFilter: "blur(18px)",
        borderColor: "rgba(140, 108, 72, 0.12)",
      }}
    >
      <div
        ref={containerRef}
        className="flex overflow-x-auto hide-scrollbar px-3 py-2 gap-1.5 items-center"
      >
        {categories.map((cat) => {
          const active = cat.id === activeCategoryId;
          return (
            <button
              key={cat.id}
              data-id={cat.id}
              onClick={() => scrollTo(cat.id)}
              className={`
                flex items-center gap-1.5 whitespace-nowrap px-3 py-1.5 rounded-full
                text-[11px] font-medium font-sans shrink-0
                transition-all duration-200 active:scale-95
                ${active ? "pill-active" : "pill-inactive hover:bg-[rgba(120,90,58,0.14)]"}
              `}
            >
              <span className="text-[13px] leading-none select-none">
                {icons[cat.id] ?? "🍽️"}
              </span>
              <span>{cat.title}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}
