function normalizeGenreKey(value) {
	return String(value || '')
		.trim()
		.toLowerCase()
		.replace(/[^a-z0-9]+/g, '');
}

export function normalizeGenreNames(values) {
	const seen = new Set();
	const names = [];

	for (const value of values || []) {
		const trimmed = String(value || '').trim();
		if (!trimmed) continue;
		const key = normalizeGenreKey(trimmed);
		if (!key || seen.has(key)) continue;
		seen.add(key);
		names.push(trimmed);
	}

	return names;
}

export function pickSuggestedGenre(tmdbGenres, currentGenres = []) {
	const normalizedTmdbGenres = normalizeGenreNames(tmdbGenres);
	if (!normalizedTmdbGenres.length) return '';

	const currentKeys = new Set(normalizeGenreNames(currentGenres).map(normalizeGenreKey));
	const matched = normalizedTmdbGenres.find((genre) => currentKeys.has(normalizeGenreKey(genre)));

	return matched || normalizedTmdbGenres[0];
}

export function buildSingleGenreUpdate(item, genreName) {
	const selectedGenre = String(genreName || '').trim();
	if (!selectedGenre) {
		throw new Error('A genre is required');
	}

	const nextItem = JSON.parse(JSON.stringify(item || {}));
	const existingGenreItems = Array.isArray(item?.GenreItems) ? item.GenreItems : [];
	const matchedGenreItem = existingGenreItems.find(
		(entry) => normalizeGenreKey(entry?.Name) === normalizeGenreKey(selectedGenre)
	);

	nextItem.Genres = [selectedGenre];
	nextItem.GenreItems = [
		matchedGenreItem
			? { ...matchedGenreItem, Name: selectedGenre }
			: { Name: selectedGenre }
	];

	return nextItem;
}
