<template>
  <div class="layout" :class="{ 'scaled-layout': isScaled }" :style="layoutStyles">
    <Header />
    <main class="main-content">
      <slot />
    </main>
    <Footer />

    <!-- 缩放调试信息 (仅开发环境) -->
    <ScaleDebugInfo v-if="isDevelopment" />
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
import Header from '@/components/layout/Header.vue'
import Footer from '@/components/layout/Footer.vue'
import ScaleDebugInfo from '@/components/common/ScaleDebugInfo.vue'
import { scaleManager } from '@/utils/scaleManager.js'

export default {
  name: 'DefaultLayout',
  components: {
    Header,
    Footer,
    ScaleDebugInfo
  },
  setup() {
    const isScaled = ref(false)
    const scaleInfo = ref({})
    const layoutStyles = ref({})
    const isDevelopment = ref(process.env.NODE_ENV === 'development')

    // 处理缩放变化
    const handleScaleChange = () => {
      const info = scaleManager.getScaleInfo()
      scaleInfo.value = info
      isScaled.value = info.shouldApply
      
      // 清空布局样式，让管理器处理
      layoutStyles.value = {}
    }

    onMounted(() => {
      // 注册缩放变化监听器
      scaleManager.onScaleChange(handleScaleChange)
      
      // 检查并恢复缩放状态
      scaleManager.checkAndRestore()
      
      // 立即获取当前状态
      const info = scaleManager.getScaleInfo()
      scaleInfo.value = info
      isScaled.value = info.shouldApply
      
      // 延迟再次检查，确保状态正确
      setTimeout(() => {
        scaleManager.checkAndRestore()
        const updatedInfo = scaleManager.getScaleInfo()
        scaleInfo.value = updatedInfo
        isScaled.value = updatedInfo.shouldApply
      }, 200)
    })

    onUnmounted(() => {
      // 只移除监听器，不重置策略
      scaleManager.removeScaleChangeListener(handleScaleChange)
    })

    return {
      isScaled,
      scaleInfo,
      layoutStyles,
      isDevelopment
    }
  }
}
</script>

<style lang="scss" scoped>
.layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding-top: 70px; // Header height
}
</style>