/**
 * Pure helpers for HowTo supplies / tools string lists.
 */

/**
 * Normalize a string list (trim, drop empties, preserve order).
 *
 * @param {Array<mixed>} list Raw list.
 * @return {string[]} Normalized.
 */
export function normalizeStringList(list) {
	if (!Array.isArray(list)) {
		return [];
	}
	return list
		.map((item) => String(item ?? '').trim())
		.filter((item) => item !== '');
}

/**
 * @param {Array<mixed>} list Current list.
 * @return {string[]} List with one empty draft row appended (editor keeps blanks).
 */
export function appendStringItem(list) {
	const next = Array.isArray(list) ? list.map((item) => String(item ?? '')) : [];
	next.push('');
	return next;
}

/**
 * @param {Array<mixed>} list  Current list.
 * @param {number}       index Index.
 * @param {string}       value New value.
 * @return {string[]} Updated list.
 */
export function updateStringAt(list, index, value) {
	const next = Array.isArray(list) ? list.map((item) => String(item ?? '')) : [];
	if (index < 0 || index >= next.length) {
		return next;
	}
	next[index] = String(value ?? '');
	return next;
}

/**
 * @param {Array<mixed>} list  Current list.
 * @param {number}       index Index to remove.
 * @return {string[]} Updated list.
 */
export function removeStringAt(list, index) {
	const next = Array.isArray(list) ? list.map((item) => String(item ?? '')) : [];
	if (index < 0 || index >= next.length) {
		return next;
	}
	return next.filter((_, i) => i !== index);
}
