<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import navTop from './_nav-top.vue'
import navLeft from './_nav-left.vue'
import ThemeCustomizer from './_theme.vue'

// 当前布局类型
const currentLayout = ref(localStorage.getItem('layout') || 'horizontal')

// ThemeCustomizer 的 ref
const themeCustomizerRef = ref(null)

// 根据布局类型返回对应的组件
const layoutComponent = computed(() => {
  switch (currentLayout.value) {
  case 'topside':
    return navLeft
  case 'horizontal':
  default:
    return navTop
  }
})

// 监听 localStorage 变化（用于跨组件通信）
const handleStorageChange = e => {
  if (e.key === 'layout') {
    currentLayout.value = e.newValue || 'horizontal'
  }
}

// 监听自定义事件（用于同一窗口内的通信）
const handleLayoutChange = e => {
  currentLayout.value = e.detail || 'horizontal'
}

onMounted(() => {
  // 监听 storage 事件（跨标签页）
  window.addEventListener('storage', handleStorageChange)

  // 监听自定义事件（同一窗口）
  window.addEventListener('layoutChange', handleLayoutChange)
})

// 监听布局变化，保存到 localStorage
watch(currentLayout, newLayout => {
  localStorage.setItem('layout', newLayout)
})
</script>

<template>
  <component
    :is="layoutComponent"
    :theme-customizer-ref="themeCustomizerRef"
  >
    <RouterView />
  </component>

  <!-- 主题定制器 - 在所有布局中都可用 -->
  <ThemeCustomizer ref="themeCustomizerRef" />

</template>

<style lang="scss">

</style>
