import { useEffect, useState } from 'react'
import { NavLink, useSearchParams } from 'react-router-dom'
import { fetchCategories } from '../../api/endpoints'

/** Horizontally scrollable pill row of categories. Sticks below the top bar. */
export default function CategoryBar() {
  const [categories, setCategories] = useState([])
  const [params] = useSearchParams()
  const active = params.get('category')

  useEffect(() => {
    fetchCategories().then(setCategories).catch(() => {})
  }, [])

  if (!categories.length) return null

  const pill =
    'shrink-0 rounded-full px-4 py-1.5 text-[13px] font-semibold transition-all duration-200 whitespace-nowrap '
  const activeCls =
    'bg-[var(--brand)] text-white shadow-md shadow-[var(--brand)]/30'
  const idleCls =
    'bg-white text-gray-600 ring-1 ring-gray-200 hover:bg-gray-50 hover:text-gray-900 hover:ring-gray-300 dark:bg-gray-900 dark:text-gray-300 dark:ring-gray-800 dark:hover:bg-gray-800 dark:hover:text-white'

  return (
    <div className="sticky top-14 z-30 border-b border-gray-200/70 bg-white/85 backdrop-blur-xl dark:border-gray-800/70 dark:bg-gray-950/85 sm:top-16">
      <div className="no-scrollbar mx-auto flex max-w-7xl gap-2 overflow-x-auto px-3 py-2.5 sm:px-4">
        <NavLink to="/" className={pill + (!active ? activeCls : idleCls)}>
          All
        </NavLink>
        {categories.map((c) => (
          <NavLink
            key={c.id}
            to={`/?category=${c.slug}`}
            className={pill + (active === c.slug ? activeCls : idleCls)}
          >
            {c.name}
          </NavLink>
        ))}
      </div>
    </div>
  )
}
