/**
 * 合辑播放页数据交接：列表太大不宜放 URL，走内存 + storage 双写。
 * navigateTo 前 stash，目标页 onLoad/onReady take（只取一次）。
 */

const MEM_KEY = '__series_reel_handoff__'
const STORE_KEY = 'hl88app:series_reel_handoff'

/**
 * @param {{
 *   seriesId?: string|number,
 *   startId?: string|number,
 *   seriesList?: Array,
 *   user?: object|null,
 *   isFollow?: number|boolean,
 *   anchor?: object|null
 * }} pack
 */
export function stashSeriesHandoff(pack) {
	const payload = pack && typeof pack === 'object' ? pack : null
	try {
		const app = getApp()
		if (app) {
			app.globalData = app.globalData || {}
			app.globalData[MEM_KEY] = payload
		}
	} catch (_) {}
	try {
		if (payload) uni.setStorageSync(STORE_KEY, payload)
		else uni.removeStorageSync(STORE_KEY)
	} catch (_) {}
}

/** @returns {object|null} */
export function takeSeriesHandoff() {
	let pack = null
	try {
		const app = getApp()
		if (app && app.globalData && app.globalData[MEM_KEY]) {
			pack = app.globalData[MEM_KEY]
			delete app.globalData[MEM_KEY]
		}
	} catch (_) {}
	if (!pack) {
		try {
			pack = uni.getStorageSync(STORE_KEY) || null
			uni.removeStorageSync(STORE_KEY)
		} catch (_) {}
	}
	return pack && typeof pack === 'object' ? pack : null
}

/** 把 series_list 项规整成 vertical-reel 可播的 clip */
export function normalizeSeriesClip(raw = {}, extras = {}) {
	const video = raw.video || {}
	const seriesId =
		extras.seriesId != null && extras.seriesId !== ''
			? extras.seriesId
			: raw.pid != null
				? raw.pid
				: raw.series_id
	const seriesList = Array.isArray(extras.seriesList)
		? extras.seriesList
		: Array.isArray(raw.series_list)
			? raw.series_list
			: []
	const paid =
		video.paid_money != null && video.paid_money !== ''
			? video.paid_money
			: raw.paid_money != null
				? raw.paid_money
				: 0
	return {
		...raw,
		id: raw.id,
		series_item_id: raw.series_item_id != null && raw.series_item_id !== '' ? raw.series_item_id : raw.id,
		series_id: seriesId,
		content: raw.title || raw.content || '',
		user: extras.user != null ? extras.user : raw.user || null,
		isFollow: extras.isFollow != null ? extras.isFollow : raw.isFollow || 0,
		isLike: raw.isLike || 0,
		likes: raw.likes || 0,
		comments: raw.comments || 0,
		series_list: seriesList,
		play: false,
		initialTime: 0,
		userPaused: false,
		_captionExpanded: false,
		_localSrc: '',
		video: {
			id: video.id || '',
			video_id: video.video_id || raw.video_id || '',
			url: video.url || '',
			cover_url: video.cover_url || video.snapshots || '',
			width: video.width || 0,
			height: video.height || 0,
			fit: video.fit || 'cover',
			duration: video.duration,
			paid_money: paid
		}
	}
}
