<template>
  <div class="app-desktop-shell" :style="desktopScaleStyle">
    <div class="app-desktop-stage">
      <RouterView />
      <ToastNotification :toast-text="toastText" />
    </div>
  </div>
</template>

<script setup>
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { RouterView } from 'vue-router'

import './assets/styles/global.css'

import ToastNotification from './components/shared/ToastNotification.vue'
import { useToast } from './composables/useToast.js'

const { toastText } = useToast()

const DESKTOP_BASE_WIDTH = 1600
const DESKTOP_BASE_HEIGHT = 920
const DESKTOP_MIN_SCALE = 0.82

const viewportWidth = ref(typeof window === 'undefined' ? DESKTOP_BASE_WIDTH : window.innerWidth)
const viewportHeight = ref(typeof window === 'undefined' ? DESKTOP_BASE_HEIGHT : window.innerHeight)

const desktopScaleStyle = computed(() => {
  const scale = resolveDesktopScale(viewportWidth.value, viewportHeight.value)
  const inverseScale = Number((1 / scale).toFixed(4))

  return {
    '--desktop-ui-scale': scale.toFixed(4),
    '--desktop-ui-inverse-scale': inverseScale.toFixed(4),
    '--desktop-stage-width': `${Math.round(viewportWidth.value * inverseScale)}px`,
    '--desktop-stage-height': `${Math.round(viewportHeight.value * inverseScale)}px`
  }
})

function resolveDesktopScale(width, height) {
  if (width < 960) {
    return 1
  }

  const scaleByWidth = width / DESKTOP_BASE_WIDTH
  const scaleByHeight = height / DESKTOP_BASE_HEIGHT

  return Number(Math.min(1, Math.max(DESKTOP_MIN_SCALE, Math.min(scaleByWidth, scaleByHeight))).toFixed(4))
}

function updateViewport() {
  viewportWidth.value = window.innerWidth
  viewportHeight.value = window.innerHeight
}

onMounted(() => {
  updateViewport()
  window.addEventListener('resize', updateViewport, { passive: true })
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', updateViewport)
})
</script>

<style src="./assets/styles/app.css"></style>
