/** 将发现页视频列表接口数据规整为播放器可用结构 */

function ensureArray(value) {
	if (Array.isArray(value)) return value
	if (typeof value === 'string' && value.trim()) {
		try {
			const parsed = JSON.parse(value)
			if (Array.isArray(parsed)) return parsed
			if (parsed && typeof parsed === 'object') {
				return Object.keys(parsed)
					.filter((k) => /^\d+$/.test(k))
					.sort((a, b) => Number(a) - Number(b))
					.map((k) => parsed[k])
					.filter(Boolean)
			}
		} catch (_) {}
		return value.split(',').map((s) => s.trim()).filter(Boolean)
	}
	if (value && typeof value === 'object') {
		return Object.keys(value)
			.filter((k) => /^\d+$/.test(k))
			.sort((a, b) => Number(a) - Number(b))
			.map((k) => value[k])
			.filter(Boolean)
	}
	return []
}

/** 兼容 wanlshop 分页接口多种 envelope */
function unwrapFeedRows(payload) {
	if (!payload) return []
	if (Array.isArray(payload)) return payload
	if (typeof payload !== 'object') return []

	if (Array.isArray(payload.data)) return payload.data
	if (Array.isArray(payload.list)) return payload.list

	const inner = payload.data
	if (inner && typeof inner === 'object') {
		if (Array.isArray(inner.data)) return inner.data
		if (Array.isArray(inner.list)) return inner.list
	}
	return []
}

function unwrapFeedMeta(payload) {
	if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
		return { current_page: 1, last_page: 1 }
	}
	const inner = payload.data && typeof payload.data === 'object' && !Array.isArray(payload.data)
		? payload.data
		: payload
	return {
		current_page: inner.current_page || payload.current_page || 1,
		last_page: inner.last_page || payload.last_page || inner.current_page || payload.current_page || 1
	}
}

export function extractFeedPage(payload) {
	const rows = unwrapFeedRows(payload)
	const meta = unwrapFeedMeta(payload)
	return {
		rows: rows.map(normalizeClip),
		currentPage: Number(meta.current_page || 1),
		lastPage: Number(meta.last_page || meta.current_page || 1)
	}
}

export function normalizeClip(raw = {}) {
	const video = raw.video || {}
	const seriesList = ensureArray(raw.series_list)
	return {
		...raw,
		images: ensureArray(raw.images),
		goods: ensureArray(raw.goods),
		series_list: seriesList,
		series_id: raw.series_id != null ? raw.series_id : (raw.seriesId != null ? raw.seriesId : ''),
		play: false,
		initialTime: raw.initialTime ?? 0,
		video: {
			id: video.id || '',
			video_id: video.video_id || raw.video_id || '',
			url: video.url || '',
			cover_url: video.cover_url || '',
			width: video.width || 0,
			height: video.height || 0,
			fit: video.fit || 'cover',
			duration: video.duration,
			// 合辑付费：video.paid_money 或顶层 paid_money
			paid_money: video.paid_money != null ? video.paid_money : (raw.paid_money != null ? raw.paid_money : 0)
		}
	}
}

export function stripHtml(content) {
	if (!content) return ''
	return String(content)
		.replace(/<[^>]+>/g, '')
		.replace(/&nbsp;/g, ' ')
		.trim()
}
