<template>
	<view ref="gameWebRef" class="game-web-container" id="game-web-container"
		:style="{ 'padding-top': appStore.headerStyle.height + 'px', height: appStore.systemInfo.screenHeight + 'px' }">
		<!-- <web-view :src="pageData.url"
			:webview-styles="{ width: pageData.webviewWidth + 'px', height: pageData.webviewHeight + 'px' }"></web-view> -->
		<MobileGameHeader @back="onBack">
			<template #right>
				<view class="flex-acenter ft12 pr8" @click.stop="handleNavRightClick">
					<theme-image src="@/static/icon-deposit.png" mode="aspectFit"
						style="width: 30px; height: 30px"></theme-image>
				</view>
			</template>
			<template #title>
				<view class="pr30" style="width: 60vw;">
					<HomeNotice :speed="1" />
				</view>
			</template>
		</MobileGameHeader>
		<!-- #ifdef H5 -->
		<view class="game-view"
			:style="{ height: (appStore.systemInfo.screenHeight - appStore.headerStyle.height) + 'px' }">
			<iframe :src="pageData.url" class="iframe-view"
				:style="{ 'top': appStore.headerStyle.height + 'px', 'height': pageData.webviewHeight + 'px' }" />
			<theme-image v-if="pageData.loading" src="@/static/img-game-loading.png" mode="aspectFill"
				class="iframe-view-loading" />
		</view>
		<!-- #endif -->
	</view>
</template>

<script setup>
import { onLoad, onUnload, onShow } from '@dcloudio/uni-app'
import { computed, nextTick, onMounted, onUnmounted, reactive, ref } from 'vue'
import MobileGameHeader from '@/components/header/MobileGameHeader.vue'
import HomeNotice from '@/pages/home/components/HomeNotice.vue'
import { useAppStore } from '@/store/useAppStore.js'
import { useUserStore } from '@/store/useUserStore'
import { enterFullscreen, exitFullscreen } from '@/module/fullscreen/fullscreen-handler'
import { gameOutApi, requestGetGameUrlByGame, requestJiliLogout } from '@/api/game.js'

const appStore = useAppStore()
const userStore = useUserStore()

const gameWebRef = ref(null)
const pageData = reactive({
	gameId: '',
	url: '',
	webviewHeight: 600,
	webviewWidth: 300,
	loading: true,
	reportInterval: null,
})
const gameId = ref('')
const gameName = ref('Game')
let webviewInstance = null
onLoad(async (option) => {
	const pages = getCurrentPages()
	const pagesStr = pages.map(page => page.route).join('--')
	console.log("page stack:", pagesStr);
	
	gameId.value = option.gameId
	gameName.value = option.name
	pageData.gameId = option.gameId
	const windowInfo = uni.getWindowInfo()
	await getGameData()
	uni.hideLoading()
	// #ifdef APP-PLUS
	const webview = plus.webview.create(pageData.url, 'game-web', {
		top: appStore.headerStyle.height,
		left: 0,
		width: windowInfo.windowWidth + 'px',
		height: (windowInfo.screenHeight - windowInfo.statusBarHeight - 50) + 'px',
		fullScreen: false
	})
	webviewInstance = webview
	webviewInstance.show()
	// webview.addEventListener('fullscreen', () => {
	// 	webview.nativeInstanceObject().plusSetAttribute('fullscreen', false)
	// })
	// #endif
	// let gameUrl = uni.getStorageSync('GAME_URL_KEY')
	// if (!gameUrl) {
	// 	if (option.url) {
	// 		gameUrl = decodeURIComponent(option.url)
	// 	}
	// }
})
const onBack = () => {
	// reportGameOut()
	// #ifdef APP-PLUS
	plus.webview.close(webviewInstance)
	// #endif
}
const getGameData = async () => {
	const { data } = await requestGetGameUrlByGame({
		gameId: gameId.value
	})
	pageData.loading = false
	pageData.url = data
	startReport()
}
const preventFullscreenScript = `
(function() {
  // Override fullscreen-related methods
  const preventFullscreen = function(e) {
    e.preventDefault();
    e.stopPropagation();
    return false;
  };

  // Block standard fullscreen methods
  document.documentElement.requestFullscreen = preventFullscreen;
  document.documentElement.mozRequestFullScreen = preventFullscreen;
  document.documentElement.webkitRequestFullscreen = preventFullscreen;
  document.documentElement.msRequestFullscreen = preventFullscreen;

  // Block fullscreen change events
  document.addEventListener('fullscreenchange', preventFullscreen, true);
  document.addEventListener('webkitfullscreenchange', preventFullscreen, true);
  document.addEventListener('mozfullscreenchange', preventFullscreen, true);
  document.addEventListener('MSFullscreenChange', preventFullscreen, true);

  // Override fullscreen properties
  Object.defineProperties(document, {
    fullscreen: { value: false, writable: false },
    fullscreenEnabled: { value: false, writable: false }
  });

  // Block video and other element fullscreen attempts
  const originalRequestFullscreen = Element.prototype.requestFullscreen;
  Element.prototype.requestFullscreen = function() {
    console.log('Fullscreen request blocked');
    return Promise.reject(new Error('Fullscreen is disabled'));
  };

  // Optionally log blocked attempts
  console.log('Fullscreen prevention script injected');
})();
`

const injectPreventFullscreen = () => {
  // #ifdef APP-PLUS
  if (webviewInstance) {
    webviewInstance.evalJS(preventFullscreenScript)
  }
  // #endif
}
const reportGameOut = () => {
	gameOutApi()
}
onMounted(() => {
	enterFullscreen()
	injectPreventFullscreen()
	computeWebviewHeight()
	// setTimeout(() => {
	// 	computeWebviewHeight()
	// }, 100)
	// setTimeout(() => {
	// 	pageData.loading = false
	// }, 2000)
	uni.onWindowResize(computeWebviewHeight)
})

onUnmounted(() => {
	// #ifdef APP-PLUS
	plus.webview.close(webviewInstance)
	// #endif
	exitFullscreen()
	uni.offWindowResize(computeWebviewHeight)
	stopReport()
	requestJiliLogout()
})

const startReport = () => {
	if (pageData.reportInterval) {
		stopReport()
	}
	userStore.reportOnline(pageData.gameId)
	pageData.reportInterval = setInterval(() => {
		userStore.reportOnline(pageData.gameId)
	}, 3 * 60 * 1000)
}

const stopReport = () => {
	if (!pageData.reportInterval) {
		return
	}
	clearInterval(pageData.reportInterval)
	pageData.reportInterval = null
}

const computeWebviewHeight = () => {
	nextTick(() => {
		const windowInfo = uni.getWindowInfo()
		pageData.webviewHeight = windowInfo.windowHeight - appStore.headerStyle.height
		pageData.webviewWidth = windowInfo.windowWidth
		console.log('window size', pageData.webviewHeight, pageData.webviewWidth)
		// uni.createSelectorQuery().select('#game-web-container').boundingClientRect((element) => {
		// 	console.log(111, element.height, appStore.headerStyle.height)
		// 	pageData.webviewHeight = element.height - appStore.headerStyle.height
		// }).exec()
	})
}

const handleNavRightClick = () => {
	// #ifdef APP-PLUS
	plus.webview.hide(webviewInstance)
	// #endif
	uni.navigateTo({
		url: '/pages/wallet/Deposit'
	})
}
onShow(() => {
	// #ifdef APP-PLUS
	if(webviewInstance) {
		plus.webview.show(webviewInstance)
	}
	// #endif
})

onUnload(() => {
	// #ifdef APP-PLUS
	plus.webview.close(webviewInstance)
	// #endif
})
</script>

<style lang="scss" scoped>
.game-web-container {
	// height: 100vh;
	position: relative;
	background-color: black;
	overflow: hidden;

	.game-view {
		position: relative;
	}

	.iframe-view {
		width: 100%;
		border: 0px;
	}

	.iframe-view-loading {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 1;
	}
}
</style>