/**
 * 合辑分集解锁状态本地缓存：
 * 解锁成功后写入，再次打开合辑弹层 / 进入合辑页时合并，避免重复解锁。
 */

const STORE_KEY = 'hl88app:series_unlocked_map'
const MEM_KEY = '__series_unlocked_map__'

function readMap() {
	try {
		const app = getApp()
		if (app && app.globalData && app.globalData[MEM_KEY]) {
			return { ...app.globalData[MEM_KEY] }
		}
	} catch (_) {}
	try {
		const disk = uni.getStorageSync(STORE_KEY)
		if (disk && typeof disk === 'object') return { ...disk }
	} catch (_) {}
	return {}
}

function writeMap(map) {
	const next = map && typeof map === 'object' ? map : {}
	try {
		const app = getApp()
		if (app) {
			app.globalData = app.globalData || {}
			app.globalData[MEM_KEY] = next
		}
	} catch (_) {}
	try {
		uni.setStorageSync(STORE_KEY, next)
	} catch (_) {}
}

function itemKey(itemOrId) {
	if (itemOrId == null) return ''
	if (typeof itemOrId === 'object') {
		const id =
			itemOrId.series_item_id != null && itemOrId.series_item_id !== ''
				? itemOrId.series_item_id
				: itemOrId.id
		return id != null ? String(id) : ''
	}
	return String(itemOrId)
}

/** 标记某合辑分集已解锁（可附带播放地址） */
export function markSeriesItemUnlocked(seriesItemId, extra = {}) {
	const key = itemKey(seriesItemId)
	if (!key) return
	const map = readMap()
	map[key] = {
		at: Date.now(),
		url: (extra && extra.url) || (map[key] && map[key].url) || '',
		videoId: (extra && extra.videoId) || (map[key] && map[key].videoId) || ''
	}
	writeMap(map)
}

export function getSeriesUnlockRecord(seriesItemId) {
	const key = itemKey(seriesItemId)
	if (!key) return null
	const map = readMap()
	return map[key] || null
}

export function isSeriesItemUnlockedCached(seriesItemId) {
	return !!getSeriesUnlockRecord(seriesItemId)
}

/** 合并单条：已缓存解锁 → is_can_play=1，并尽量补 url */
export function applyUnlockCacheToItem(item) {
	if (!item || typeof item !== 'object') return item
	const rec = getSeriesUnlockRecord(item)
	if (!rec) return item
	const next = { ...item, is_can_play: 1 }
	if (rec.url) {
		next.video = { ...(item.video || {}), url: rec.url }
	}
	return next
}

/** 合并整个 series_list */
export function applyUnlockCacheToSeriesList(list) {
	if (!Array.isArray(list)) return []
	return list.map((row) => applyUnlockCacheToItem(row))
}
