import appSettings from '@/core/config/app-settings'
import { migrateObsoleteStorage } from '@/core/storage/legacy-migration'
// nativePushEnabled 见 runtime-manifest UI_FLAGS
import { bootstrapLocale } from './locale-bootstrap'
import { bindTabCenterPublisher } from '@/features/tab-center-publish'
import { startNetworkAccessGuard, refreshNetworkAccess } from '@/core/network/network-access-guard'
import {
	startTeenModeGuard,
	onTeenModeForeground,
	onTeenModeBackground
} from '@/features/account/teen-mode-guard'

export function runColdStart(vm) {
	migrateObsoleteStorage()

	const sys = uni.getSystemInfoSync()
	const platform = (sys.platform || '').toLowerCase()
	vm.globalData.isAndroid = platform === 'android'
	vm.globalData._i18n = vm.$i18n
	bootstrapLocale(vm.$i18n, vm.globalData.isAndroid)

	const store = vm.$store
	store.dispatch('user/hydrateFromCache')
	store.dispatch('release/check')
	store.dispatch('shell/bootstrap')
	store.dispatch('cart/sync')
	store.dispatch('stats/hydrate')

	vm.globalData.runtimeConfig = { ...appSettings }
	bindTabCenterPublisher(vm)
	// 仅 App：拦截「系统禁止本应用联网」；H5 由浏览器管理网络，无需守卫
	// #ifdef APP-PLUS
	startNetworkAccessGuard(vm.$i18n)
	// #endif
	startTeenModeGuard(vm.$i18n)

	// #ifdef APP-PLUS
	if (appSettings.nativePushEnabled) {
		if (platform === 'android') {
			setTimeout(() => vm.$pushBridge && vm.$pushBridge.boot(), 400)
		} else if (platform === 'ios') {
			vm.$pushBridge && vm.$pushBridge.boot()
		}
	}
	// #endif
}

export function runForeground(vm) {
	// #ifdef APP-PLUS
	refreshNetworkAccess()
	// #endif
	onTeenModeForeground()
	vm.$store.dispatch('im/resume')
	// #ifdef APP-PLUS
	if (appSettings.nativePushEnabled) {
		try {
			const platform = (uni.getSystemInfoSync().platform || '').toLowerCase()
			if (platform === 'ios' && vm.$pushBridge) {
				setTimeout(() => {
					vm.$pushBridge.pullNativeTokens()
					vm.$pushBridge.queueServerReport('foreground-ios', 200)
				}, 300)
			}
		} catch (_) {}
	}
	// #endif
}

export function runBackground(vm) {
	onTeenModeBackground()
	vm.$store.dispatch('im/pause', false)
}
