const TAB_ROOTS = ['pages/index/index', 'pages/feed/index', 'pages/live/hall', 'pages/dynamics/index', 'pages/mine/index']

function extractCustomUrl(payload) {
	if (!payload || typeof payload !== 'object') return ''
	const pick = (obj) => {
		const bag = obj.custom_data || obj.customData
		if (!bag || typeof bag !== 'object') return ''
		const target = bag.url || bag.path || bag.page
		return typeof target === 'string' ? target.trim() : ''
	}
	return pick(payload.data) || pick(payload)
}

export function openPushTarget(payload, prefs) {
	if (!prefs?.pushs) return
	const raw = extractCustomUrl(payload)
	if (!raw) return

	const full = raw.startsWith('/') ? raw : `/${raw}`
	const qPos = full.indexOf('?')
	const pathOnly = qPos >= 0 ? full.slice(0, qPos) : full
	const query = qPos >= 0 ? full.slice(qPos + 1) : ''
	const normalized = pathOnly.replace(/^\//, '')
	const isTab = TAB_ROOTS.includes(normalized)

	const navigate = () => {
		if (isTab) {
			uni.switchTab({
				url: pathOnly,
				fail: (e) => console.warn('[push-nav] switchTab fail', pathOnly, e)
			})
			return
		}
		const target = query ? `${pathOnly}?${query}` : full
		uni.navigateTo({
			url: target,
			fail: () => uni.reLaunch({ url: target })
		})
	}

	setTimeout(navigate, 100)
}
