<template>
  <router-view v-slot="{ Component }">
    <component
      :is="Component"
      :theme-mode="themeMode"
      :resolved-theme="resolvedTheme"
      @set-theme-mode="setThemeMode"
    />
  </router-view>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'

const STORAGE_KEY = 'theme-mode'
const themeMode = ref(localStorage.getItem(STORAGE_KEY) || 'system')
const resolvedTheme = ref('light')
let mediaQuery

function getSystemTheme() {
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}

function applyTheme() {
  const nextTheme = themeMode.value === 'system' ? getSystemTheme() : themeMode.value
  resolvedTheme.value = nextTheme
  document.documentElement.dataset.theme = nextTheme
  document.documentElement.style.colorScheme = nextTheme
}

function setThemeMode(mode) {
  themeMode.value = mode
}

watch(themeMode, (mode) => {
  localStorage.setItem(STORAGE_KEY, mode)
  applyTheme()
})

onMounted(() => {
  mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  mediaQuery.addEventListener('change', applyTheme)
  applyTheme()
})

onUnmounted(() => {
  mediaQuery?.removeEventListener('change', applyTheme)
})
</script>
