import { useEffect, useRef } from "react";
import { useI18n } from "../../i18n";
import { typeFilterLabel } from "../../resourceTypeLabels";

const TYPE_FILTERS = [
  "all",
  "image",
  "video",
  "music",
  "ppt",
  "pdf",
  "text",
  "link",
  "archive",
] as const;

export type FilterChipsProps = {
  type: string;
  onTypeChange: (next: string) => void;
};

export function FilterChips({ type, onTypeChange }: FilterChipsProps) {
  const { t } = useI18n();
  const scrollRef = useRef<HTMLDivElement>(null);

  // Let a mouse wheel scroll the row horizontally when it overflows — desktop
  // mice have no horizontal wheel and the scrollbar is hidden, so otherwise the
  // last filters are unreachable. Touch/trackpad scroll natively.
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const onWheel = (e: WheelEvent) => {
      if (e.deltaY === 0 || el.scrollWidth <= el.clientWidth) return;
      e.preventDefault();
      el.scrollLeft += e.deltaY;
    };
    el.addEventListener("wheel", onWheel, { passive: false });
    return () => el.removeEventListener("wheel", onWheel);
  }, []);

  const tabClass = (active: boolean) =>
    [
      "relative flex h-[52px] shrink-0 items-center whitespace-nowrap px-3 pb-4 pt-3 text-[15px] leading-6 outline-none transition-colors md:h-auto md:px-1 md:py-3 md:leading-none",
      "border-b-0 md:border-b-2",
      active
        ? "border-ark-gold font-medium text-ark-gold"
        : "border-transparent text-[#97989A] hover:text-ark-gold/80 md:text-neutral-400",
    ].join(" ");

  return (
    <div className="bg-ark-bg/95 backdrop-blur md:rounded-t-xl">
      <div
        ref={scrollRef}
        className="flex items-end gap-2 overflow-x-auto overflow-y-hidden px-4 pr-10 [-ms-overflow-style:none] [scrollbar-width:none] md:gap-5 md:px-1 md:pr-1 [&::-webkit-scrollbar]:hidden"
        role="tablist"
      >
        {TYPE_FILTERS.map((tp) => {
          const active = type === tp;
          return (
            <button
              key={tp}
              type="button"
              role="tab"
              aria-selected={active}
              onClick={() => onTypeChange(tp)}
              className={tabClass(active)}
            >
              {typeFilterLabel(t, tp)}
            </button>
          );
        })}
      </div>
      <div
        className="pointer-events-none absolute right-0 top-0 hidden h-[52px] w-10 bg-gradient-to-l from-ark-bg via-ark-bg/80 to-transparent max-md:block"
        aria-hidden
      />
    </div>
  );
}
