const IDS_KEY = 'hl88live:room_queue_ids'
const THUMBS_KEY = 'hl88live:room_queue_thumbs'
const INDEX_KEY = 'hl88live:room_queue_index'
const META_KEY = 'hl88live:room_queue_meta'

function normalizeMetaList(metas, len) {
	const list = Array.isArray(metas) ? metas.slice() : []
	while (list.length < len) list.push({})
	return list.slice(0, len)
}

export function saveRoomQueue(ids, thumbs, activeIndex = 0, metas) {
	const idList = ids.map(String)
	const prevMetas = normalizeMetaList(uni.getStorageSync(META_KEY), idList.length)
	const metaList = metas !== undefined ? normalizeMetaList(metas, idList.length) : prevMetas
	uni.setStorageSync(IDS_KEY, idList)
	uni.setStorageSync(THUMBS_KEY, thumbs.map((t) => String(t || '')))
	uni.setStorageSync(INDEX_KEY, activeIndex)
	uni.setStorageSync(META_KEY, metaList)
}

export function readRoomQueue(currentId) {
	const ids = uni.getStorageSync(IDS_KEY)
	if (!Array.isArray(ids) || !ids.length) {
		return { ids: [], thumbs: [], index: 0, meta: {}, metas: [] }
	}
	const thumbs = uni.getStorageSync(THUMBS_KEY) || []
	const metas = normalizeMetaList(uni.getStorageSync(META_KEY), ids.length)
	const found = ids.indexOf(String(currentId))
	const storedIndex = uni.getStorageSync(INDEX_KEY)
	const index = found >= 0 ? found : Number(storedIndex) || 0
	return {
		ids: ids.map(String),
		thumbs: Array.isArray(thumbs) ? thumbs.map(String) : [],
		index,
		metas,
		meta: metas[index] || {}
	}
}

export function patchRoomMeta(roomId, patch) {
	const ids = uni.getStorageSync(IDS_KEY)
	if (!Array.isArray(ids) || !ids.length) return
	const idx = ids.indexOf(String(roomId))
	if (idx < 0) return
	const metas = normalizeMetaList(uni.getStorageSync(META_KEY), ids.length)
	metas[idx] = { ...(metas[idx] || {}), ...(patch || {}) }
	uni.setStorageSync(META_KEY, metas)
}

export function neighborRoom(queue, offset) {
	const next = queue.index + offset
	if (next < 0 || next >= queue.ids.length) return null
	return {
		id: queue.ids[next],
		thumb: queue.thumbs[next] || '',
		meta: (queue.metas && queue.metas[next]) || {},
		index: next
	}
}
