<template>
  <section class="app-main">
    <router-view v-slot="{ Component, route }">
      <!-- 非缓存页面 -->
      <div v-if="route.meta.noCache || route.meta.link" :key="`${route.fullPath}_noCache`">
        <transition :enter-active-class="animante" mode="out-in">
          <component :is="Component" v-if="!route.meta.link" :key="route.path" />
          <div v-else></div>
        </transition>
      </div>

      <!-- 缓存页面 -->
      <div v-else :key="`${route.fullPath}_keepAlive`">
        <transition :enter-active-class="animante" mode="out-in">
          <keep-alive :include="tagsViewStore.cachedViews">
            <component :is="Component" :key="route.path" />
          </keep-alive>
        </transition>
      </div>
    </router-view>

    <iframe-toggle />
  </section>
</template>

<script setup name="AppMain" lang="ts">
import { getCurrentInstance, ref, watch } from 'vue';
import useSettingsStore from '@/store/modules/settings';
import useTagsViewStore from '@/store/modules/tagsView';
import IframeToggle from './IframeToggle/index.vue';

const { proxy } = getCurrentInstance() as any;
const tagsViewStore = useTagsViewStore();

// 动画相关
const animante = ref<string>('');
const animationEnable = ref(useSettingsStore().animationEnable);

// 安全随机数
const secureRandom = () => {
  const randomValues = new Uint32Array(1);
  window.crypto.getRandomValues(randomValues);
  return randomValues[0] / 4294967296;
};

watch(
  () => useSettingsStore().animationEnable,
  (val: boolean) => {
    animationEnable.value = val;
    if (val) {
      animante.value =
        proxy?.animate.animateList[Math.floor(secureRandom() * proxy?.animate.animateList.length)] || 'fade-transform';
    } else {
      animante.value = proxy?.animate.defaultAnimate || 'fade-transform';
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.app-main {
  /* 50= navbar  50  */
  min-height: calc(100vh - 50px);
  width: 100%;
  position: relative;
  overflow: hidden;
}

.fixed-header + .app-main {
  padding-top: 50px;
}

/* 使用 ::v-deep 或 :deep() 穿透外部容器类名 */
::v-deep(.hasTagsView) {
  .app-main {
    /* 84 = navbar + tags-view = 50 + 34 */
    min-height: calc(100vh - 84px);
  }

  .fixed-header + .app-main {
    padding-top: 84px;
  }
}
</style>

<style lang="scss">
// 全局样式：必须脱离作用域，但需最小化影响

// 1. 弹窗时修复 fixed-header 的滚动条问题
:root::after {
  content: '';
  pointer-events: none;
  display: none;
}

/* 使用 :global 确保全局生效，但更清晰 */
:global {
  .el-popup-parent--hidden {
    .fixed-header {
      padding-right: 6px !important;
    }
  }

  /* 自定义滚动条 - 全局但合理 */
  ::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  ::-webkit-scrollbar-track {
    background-color: #f1f1f1;
  }

  ::-webkit-scrollbar-thumb {
    background-color: #c0c0c0;
    border-radius: 3px;
  }

  /* 可选：增加 hover 效果 */
  ::-webkit-scrollbar-thumb:hover {
    background-color: #a0a0a0;
  }
}
</style>
