"use client";
import Link from "next/link";
import { useRef, useEffect, useState } from "react";

export default function StickyCategoryBar({
  categories,
  activeSlug,
}: {
  categories: { id: string; slug: string; name: string }[];
  activeSlug?: string;
}) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [showLeft, setShowLeft] = useState(false);
  const [showRight, setShowRight] = useState(false);
  const isDragging = useRef(false);
  const startX = useRef(0);
  const scrollLeft = useRef(0);

  function checkFades() {
    const el = scrollRef.current;
    if (!el) return;
    setShowLeft(el.scrollLeft > 8);
    setShowRight(el.scrollLeft < el.scrollWidth - el.clientWidth - 8);
  }

  useEffect(() => {
    checkFades();
    const el = scrollRef.current;
    el?.addEventListener("scroll", checkFades, { passive: true });
    window.addEventListener("resize", checkFades);
    return () => {
      el?.removeEventListener("scroll", checkFades);
      window.removeEventListener("resize", checkFades);
    };
  }, [categories]);

  function onMouseDown(e: React.MouseEvent) {
    isDragging.current = true;
    startX.current = e.pageX - (scrollRef.current?.offsetLeft || 0);
    scrollLeft.current = scrollRef.current?.scrollLeft || 0;
    scrollRef.current!.style.cursor = "grabbing";
  }
  function onMouseMove(e: React.MouseEvent) {
    if (!isDragging.current) return;
    e.preventDefault();
    const x = e.pageX - (scrollRef.current?.offsetLeft || 0);
    scrollRef.current!.scrollLeft = scrollLeft.current - (x - startX.current);
  }
  function stopDrag() {
    isDragging.current = false;
    if (scrollRef.current) scrollRef.current.style.cursor = "";
  }

  return (
    <div
      className="sticky z-[5] border-b border-neutral-900 bg-[#0f0f0f]"
      style={{
        top: "var(--header-h, 48px)",
        marginLeft: "calc(-1rem)",
        marginRight: "calc(-1rem)",
        marginTop: "-1rem",
        marginBottom: "1.25rem",
      }}
    >
      <div className="relative">
        {showLeft && (
          <div className="pointer-events-none absolute left-0 top-0 bottom-0 w-10 z-10 bg-gradient-to-r from-[#0f0f0f] to-transparent" />
        )}
        {showRight && (
          <div className="pointer-events-none absolute right-0 top-0 bottom-0 w-10 z-10 bg-gradient-to-l from-[#0f0f0f] to-transparent" />
        )}
        <div
          ref={scrollRef}
          className="flex gap-2 overflow-x-auto overflow-y-hidden no-scrollbar py-2.5 px-4 md:px-6 cursor-grab select-none"
          style={{ touchAction: "pan-x" }}
          onMouseDown={onMouseDown}
          onMouseMove={onMouseMove}
          onMouseUp={stopDrag}
          onMouseLeave={stopDrag}
        >
          <Link
            href="/"
            className={`px-4 py-1.5 rounded-full text-sm font-semibold whitespace-nowrap shrink-0 transition-colors ${
              !activeSlug
                ? "bg-red-600 text-white"
                : "bg-neutral-800 text-neutral-400 hover:bg-neutral-700 hover:text-white"
            }`}
          >
            All
          </Link>
          {categories.map((c) => (
            <Link
              key={c.id}
              href={`/categories/${c.slug}`}
              className={`px-4 py-1.5 rounded-full text-sm whitespace-nowrap shrink-0 transition-colors ${
                activeSlug === c.slug
                  ? "bg-red-600 text-white font-semibold"
                  : "bg-neutral-800 text-neutral-400 hover:bg-neutral-700 hover:text-white"
              }`}
            >
              {c.name}
            </Link>
          ))}
        </div>
      </div>
    </div>
  );
}
