'use client';

import { useRef, useEffect } from 'react';

const CATEGORIES = [
  'All',
  'CRM',
  'eCommerce',
  'HR',
  'Finance',
  'Marketing',
  'Support',
  'ProjectMgmt',
  'Scheduling',
  'Analytics',
  'DevTools',
  'Social',
  'Communication',
  'Storage',
  'AI/ML',
] as const;

export type Category = (typeof CATEGORIES)[number];

interface CategoryFilterProps {
  selected: string;
  onSelect: (category: string) => void;
  categoryCounts?: Record<string, number>;
}

export function CategoryFilter({
  selected,
  onSelect,
  categoryCounts,
}: CategoryFilterProps) {
  const scrollRef = useRef<HTMLDivElement>(null);

  // Scroll active tab into view
  useEffect(() => {
    if (!scrollRef.current) return;
    const active = scrollRef.current.querySelector('[data-active="true"]');
    if (active) {
      active.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
    }
  }, [selected]);

  return (
    <div
      ref={scrollRef}
      className="flex items-center gap-2 overflow-x-auto pb-2 scrollbar-hide"
      style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
    >
      {CATEGORIES.map((cat) => {
        const isActive = selected === cat || (cat === 'All' && !selected);
        const count = cat === 'All'
          ? categoryCounts
            ? Object.values(categoryCounts).reduce((a, b) => a + b, 0)
            : undefined
          : categoryCounts?.[cat];

        return (
          <button
            key={cat}
            data-active={isActive}
            onClick={() => onSelect(cat === 'All' ? '' : cat)}
            className={`
              flex-shrink-0 px-4 py-1.5 rounded-full text-sm font-medium
              transition-all duration-200 whitespace-nowrap
              ${
                isActive
                  ? 'bg-indigo-500 text-white shadow-lg shadow-indigo-500/25'
                  : 'bg-gray-800 text-gray-400 hover:text-gray-200 hover:bg-gray-700'
              }
            `}
          >
            {cat}
            {count !== undefined && (
              <span className={`ml-1.5 ${isActive ? 'text-indigo-200' : 'text-gray-500'}`}>
                ({count})
              </span>
            )}
          </button>
        );
      })}
    </div>
  );
}
