import { useMemo } from 'react';

import { GAMES, type Game } from '@/data/games';

/**
 * Returns the games that match a free-text query, or the popular list when the
 * query is empty. Match is case-insensitive and substring-based on the game
 * name. The popular ordering puts the most popular games first; when the user
 * has typed a query, results are sorted by name length (shortest first) so the
 * closest match surfaces.
 */
export function filterGames(query: string): Game[] {
  const trimmed = query.trim();
  if (trimmed.length === 0) {
    return GAMES.filter((g) => g.popular);
  }
  const needle = trimmed.toLowerCase();
  return GAMES.filter((g) => g.name.toLowerCase().includes(needle)).sort(
    (a, b) => a.name.length - b.name.length,
  );
}

export function useGameSearch(query: string): Game[] {
  return useMemo(() => filterGames(query), [query]);
}
