<script setup>
import { computed, onMounted, onUnmounted, provide, ref } from "vue"
import GisMap from "../components/GisMap.vue"
import ScreenNavBar from "../components/ScreenNavBar.vue"
import { bindScreenScale, DESIGN_HEIGHT, DESIGN_WIDTH } from "../utils/screenFit.js"

const viewportRef = ref(null)
const gisMapRef = ref(null)
const stageScale = ref(1)
provide("screenGisMap", gisMapRef)

const stageWidth = computed(() => Math.round(DESIGN_WIDTH * stageScale.value))
const stageHeight = computed(() => Math.round(DESIGN_HEIGHT * stageScale.value))

let unbindScale = null

function resizeGisMap() {
  gisMapRef.value?.resizeMap?.()
}

function onScreenScaleChange(scale) {
  stageScale.value = scale
  resizeGisMap()
}

onMounted(() => {
  unbindScale = bindScreenScale(viewportRef.value, onScreenScaleChange)
  window.addEventListener("resize", resizeGisMap)
})

onUnmounted(() => {
  window.removeEventListener("resize", resizeGisMap)
  if (typeof unbindScale === "function") {
    unbindScale()
  }
})
</script>

<template>
  <div ref="viewportRef" class="screen-viewport">
    <!-- 舞台用真实像素尺寸，不用 CSS scale，避免 WebGL 地图在 transform 下放大时整屏发黑 -->
    <div
      class="screen-stage"
      :style="{ width: stageWidth + 'px', height: stageHeight + 'px' }"
    >
      <div class="screen-map-layer">
        <GisMap ref="gisMapRef" :interactive="true" />
      </div>
      <div class="screen-chrome">
        <div
          class="screen-chrome-inner"
          :style="{
            width: DESIGN_WIDTH + 'px',
            height: DESIGN_HEIGHT + 'px',
            transform: `scale(${stageScale})`,
          }"
        >
          <ScreenNavBar />
          <div class="screen-body">
            <router-view />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.screen-viewport {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}

.screen-stage {
  position: relative;
  flex-shrink: 0;
  box-sizing: border-box;
  overflow: hidden;
}

.screen-map-layer {
  position: absolute;
  inset: 0;
  z-index: 0;
}

.screen-chrome {
  position: absolute;
  inset: 0;
  z-index: 1;
  overflow: hidden;
  pointer-events: none;
}

.screen-chrome-inner {
  transform-origin: 0 0;
  display: flex;
  flex-direction: column;
  pointer-events: none;
}

.screen-chrome-inner::before {
  content: "";
  position: absolute;
  inset: 0;
  background-size: cover;
  pointer-events: none;
  z-index: 0;
}

.screen-chrome-inner > * {
  position: relative;
  z-index: 1;
}

.screen-body {
  flex: 1;
  min-height: 0;
  position: relative;
  pointer-events: none;
}

.screen-body > :deep(.screen-page) {
  position: relative;
  z-index: 1;
  height: 100%;
}
</style>
