/**
 * Extracts ALL image Files from a DataTransfer object.
 *
 * Resolution order (most → least reliable across browsers/OS):
 *   1. clipboardData.files  – browser-normalised FileList; Chrome/Linux/Mac/Safari
 *      all populate this for real paste events. Most reliable.
 *   2. clipboardData.items  – DataTransferItemList fallback for edge cases where
 *      files is empty but items contains a "file" kind entry.
 *
 * MIME matching: type.startsWith("image/") intentionally accepts any image
 * subtype, including OS-specific variants like "image/x-png" on Linux that
 * a strict allowlist (["image/png", ...]) would silently reject.
 *
 * The caller (onImagesSelect / handleImagesSelect) still runs validateImageFile
 * on each file, which enforces the app's supported format allowlist — so we
 * stay permissive here and strict at the validation boundary.
 *
 * Returns an array (possibly empty). Never returns null.
 */
export function extractAllImagesFromClipboard(
	clipboardData: DataTransfer | null | undefined,
): File[] {
	if (!clipboardData) return [];

	// ── 1. files array (primary) ──────────────────────────────────────────────
	const { files } = clipboardData;
	if (files?.length) {
		const images: File[] = [];
		for (let i = 0; i < files.length; i++) {
			const file = files[i];
			if (file.type.startsWith("image/")) images.push(file);
		}
		if (images.length > 0) return images;
	}

	// ── 2. items fallback ─────────────────────────────────────────────────────
	const { items } = clipboardData;
	if (items?.length) {
		const images: File[] = [];
		for (let i = 0; i < items.length; i++) {
			const item = items[i];
			if (item.kind === "file" && item.type.startsWith("image/")) {
				const file = item.getAsFile();
				if (file) images.push(file);
			}
		}
		return images;
	}

	return [];
}

/**
 * Backward-compatible single-file extractor.
 * Returns the first image found, or null.
 *
 * @deprecated Prefer extractAllImagesFromClipboard for multi-image support.
 */
export function extractImageFromClipboard(
	clipboardData: DataTransfer | null | undefined,
): File | null {
	return extractAllImagesFromClipboard(clipboardData)[0] ?? null;
}
