<script setup>
import { NScrollbar } from "naive-ui";

const route = useRoute();
const defaultBgUrl = "/assets/image/1920/bg-pc.png";

// Try to inject background from page, fallback to route.meta or default
const pageBg = inject("pageBg", null);

// 使用 ref 而不是 computed，避免路由变化时的自动重新计算
const currentBg = ref({ backgroundImage: `url(${defaultBgUrl})` });

// 手动更新背景，而不是自动响应式
const updateBg = () => {
  let newBg;
  // Priority 1: Provided from page component
  if (pageBg && pageBg.value) {
    newBg = { backgroundImage: pageBg.value };
  }
  // Priority 2: From route meta
  else if (route.meta?.bg && route.meta.bg !== "null") {
    newBg = { backgroundImage: route.meta.bg };
  }
  // Priority 3: Default background
  else {
    newBg = { backgroundImage: `url(${defaultBgUrl})` };
  }

  currentBg.value = newBg;
};

// 监听路由变化，使用 flush: 'post' 在 DOM 更新后执行
watch(
  () => route.path,
  () => {
    updateBg();
  },
  { immediate: true, flush: "post" }
);

onMounted(() => {
  updateBg();
});
</script>

<template>
  <div class="flex flex-col h-screen">
    <CustomHeader />

    <div
      class="flex-1 relative"
      :style="currentBg"
      style="background-size: 100% 100%; background-attachment: fixed"
    >
      <n-scrollbar class="absolute inset-0" :key="route.fullPath">
        <div>
          <slot />
        </div>
      </n-scrollbar>
    </div>

    <CustomFooter />
  </div>
</template>

<style scoped>
/* Ensure the layout takes full height */
:deep(body),
:deep(html),
#__nuxt {
  height: 100%;
  margin: 0;
  padding: 0;
}
</style>
