import {
  SIGN_LANGUAGE_CATEGORY_FILTERS,
  SIGN_LANGUAGE_YOUTUBE_QUERY_PREFIX,
  SIGN_LANGUAGE_YOUTUBE_QUERY_SUFFIX,
  SIGN_LANGUAGE_YOUTUBE_SEARCH_URL,
} from '@/shared/constants/signLanguage';
import type { SignLanguageCategoryFilter } from '@/shared/constants/signLanguage';
import type { SignItem } from '@/shared/types/app';
import type {
  SignLanguageCategoryOption,
  SignLanguageFilters,
} from '@/business/sign-language/types';

export function buildSignLanguageCategories(
  signs: readonly SignItem[],
): readonly SignLanguageCategoryOption[] {
  return SIGN_LANGUAGE_CATEGORY_FILTERS.map((filter) => ({
    ...filter,
    count: filter.value === 'all'
      ? signs.length
      : signs.filter((sign) => sign.category === filter.value).length,
  }));
}

export function filterSignLanguageItems(
  signs: readonly SignItem[],
  filters: SignLanguageFilters,
): readonly SignItem[] {
  const normalizedSearchQuery = filters.searchQuery.trim().toLowerCase();

  return signs.filter((sign) => {
    const matchesSearch = normalizedSearchQuery.length === 0
      || sign.word.toLowerCase().includes(normalizedSearchQuery);
    const matchesCategory = filters.categoryFilter === 'all'
      || sign.category === filters.categoryFilter;

    return matchesSearch && matchesCategory;
  });
}

export function getSignLanguageProgressPercent(
  signs: readonly SignItem[],
  learnedSignIds: ReadonlySet<string>,
): number {
  if (signs.length === 0) {
    return 0;
  }

  return (learnedSignIds.size / signs.length) * 100;
}

export function getSignLanguageVideoDurationSeconds(sign: SignItem): number {
  const firstStepDuration = sign.videoSteps[0]?.duration ?? 3;

  return sign.videoSteps.length * firstStepDuration;
}

export function toSignLanguageCategoryFilter(value: string): SignLanguageCategoryFilter {
  const category = SIGN_LANGUAGE_CATEGORY_FILTERS.find((filter) => filter.value === value);

  return category?.value ?? 'all';
}

export function buildSignLanguageYoutubeSearchUrl(word: string): string {
  const searchQuery = `${SIGN_LANGUAGE_YOUTUBE_QUERY_PREFIX} ${word} ${SIGN_LANGUAGE_YOUTUBE_QUERY_SUFFIX}`;

  return `${SIGN_LANGUAGE_YOUTUBE_SEARCH_URL}?search_query=${encodeURIComponent(searchQuery)}`;
}
