<!-- eslint-disable unused-imports/no-unused-vars -->
<script lang="ts" setup>
import VScaleScreen from 'v-scale-screen'
import { computed, onMounted, ref, watch } from 'vue'
import _defaultBg from '@/assets/imgs/user/home-bg.webp'
import titleBg2 from '@/assets/imgs/user/title-bg2.webp'
import _defaultTitleBg from '@/assets/imgs/user/title-bg.webp'
import { useRouterPush } from '@/hooks/common/router'

import ActionButton from './ActionButton.vue'

interface Props {
  /** 是否显示返回按钮 */
  showBack?: boolean
  /** 是否显示下一步按钮 */
  showNext?: boolean
  /** 背景图片URL，如果不传则尝试内部获取或使用默认 */
  bgUrl?: string
  /** 下一步按钮的文本，如果存在则显示为文字按钮，否则显示为图标按钮 */
  nextBtnText?: string
  /** 页面标题 */
  title?: string
  /** 是否显示标题 */
  showTitle?: boolean
  /** 按钮操作栏位置：'bottom' | 'top'，默认 'bottom' */
  actionPosition?: 'bottom' | 'top'
  /** 返回按钮的文本，如果存在则显示为文字按钮，否则显示为图标按钮 */
  backBtnText?: string
  /** 按钮主题：'primary' (红色填充) | 'light' (白色背景红字)，默认 'primary' */
  btnTheme?: 'primary' | 'light'
  /** 是否禁用下一步按钮 */
  nextDisabled?: boolean
  /** 标题区域背景图片URL，不传则使用默认 title-bg.webp */
  titleBgType?: number
  /** 是否显示第二个下一步按钮 */
  showNextBtn2?: boolean
  /** 第二个按钮的文本 */
  nextBtnText2?: string
}

const props = withDefaults(defineProps<Props>(), {
  showBack: true,
  showNext: true,
  bgUrl: undefined,
  nextBtnText: undefined,
  title: undefined,
  showTitle: true,
  actionPosition: 'bottom',
  backBtnText: undefined,
  btnTheme: 'primary',
  nextDisabled: false,
  titleBgType: 1,
  showNextBtn2: false,
  nextBtnText2: undefined,
})

const emit = defineEmits<{
  (e: 'back'): void
  (e: 'next'): void
  (e: 'next2'): void
}>()

const titleBgUrlMapping: Record<number, string> = {
  1: _defaultTitleBg,
  2: titleBg2,
}

const { routerPushByKey } = useRouterPush()

const titleBgUrl = computed(() => titleBgUrlMapping[props.titleBgType] || _defaultBg)
const titleBgLoaded = ref(false)
const currentTitleBg = ref('')
const imageLoadStatus = ref<Record<string, boolean>>({})

// const router = useRouter()
const innerBgUrl = ref(_defaultBg)

async function fetchSystemConfig() {
  // 如果外部传入了 bgUrl，则优先使用外部的
  if (props.bgUrl) {
    innerBgUrl.value = props.bgUrl
  }

  // 模拟接口请求系统配置
  // const res = await fetchConfig()
  // if (res.bgUrl) innerBgUrl.value = res.bgUrl

  // 这里的逻辑保持与原 Home 页面一致：如果没有配置，则使用默认
  if (!innerBgUrl.value)
    innerBgUrl.value = _defaultBg
}

const showContent = ref(false)
const showSlotContent = ref(false)
const showButton = ref(false)

function handleBack() {
  emit('back')
}

function handleNext() {
  if (props.nextDisabled)
    return
  emit('next')
}

function handleNext2() {
  emit('next2')
}

/** 点击返回首页 */
function handleBackHome() {
  routerPushByKey('user_home')
}

onMounted(() => {
  // 预加载所有标题背景图，并跟踪加载状态
  const preloadAllImages = () => {
    const promises = Object.entries(titleBgUrlMapping).map(([_key, url]) => {
      return new Promise((resolve) => {
        const img = new Image()
        img.onload = () => {
          imageLoadStatus.value[url] = true
          resolve(true)
        }
        img.onerror = () => {
          imageLoadStatus.value[url] = false
          resolve(false)
        }
        img.src = url
      })
    })

    // 也预加载默认背景
    const defaultBgPromise = new Promise((resolve) => {
      const img = new Image()
      img.onload = () => {
        imageLoadStatus.value[_defaultBg] = true
        resolve(true)
      }
      img.onerror = () => {
        imageLoadStatus.value[_defaultBg] = false
        resolve(false)
      }
      img.src = _defaultBg
    })

    return Promise.all([...promises, defaultBgPromise])
  }

  // 开始预加载
  preloadAllImages()
    .then(() => {
      // 所有图片预加载完成后，设置当前背景
      currentTitleBg.value = titleBgUrl.value
      titleBgLoaded.value = true

      fetchSystemConfig()
      setTimeout(() => {
        showContent.value = true
      }, 100)
    })
    .catch(() => {
      // 即使预加载失败也继续
      currentTitleBg.value = titleBgUrl.value
      titleBgLoaded.value = true

      fetchSystemConfig()
      setTimeout(() => {
        showContent.value = true
      }, 100)
    })

  // 延迟显示内容，等待标题卷轴展开
  const delay = props.showTitle ? 500 : 100
  setTimeout(() => {
    showSlotContent.value = true
  }, delay)

  // 延迟显示按钮，等待内容显示
  setTimeout(() => {
    showButton.value = true
  }, delay + 500)
})

// 监听 titleBgUrl 变化，确保图片切换平滑
watch(titleBgUrl, (newUrl) => {
  if (newUrl && imageLoadStatus.value[newUrl]) {
    // 如果图片已经加载过，直接切换
    currentTitleBg.value = newUrl
  }
  else if (newUrl) {
    // 如果图片还没加载，预加载它
    const img = new Image()
    img.onload = () => {
      imageLoadStatus.value[newUrl] = true
      currentTitleBg.value = newUrl
    }
    img.onerror = () => {
      imageLoadStatus.value[newUrl] = false
      // 加载失败时使用默认背景
      currentTitleBg.value = _defaultBg
    }
    img.src = newUrl
  }
})
</script>

<template>
  <div class="competition-layout-wrapper">
    <!-- Background Layer (Outside Scale to cover full screen) -->
    <div class="fixed-bg" :style="innerBgUrl ? { backgroundImage: `url(${innerBgUrl})` } : {}" />

    <VScaleScreen width="2048" height="1080">
      <div class="competition-layout">
        <!-- Header -->
        <!-- <header class="page-header flex items-center text-[30px] text-[#333333] font-bold">
          <span class="org-name" @click="handleBackHome">重庆市教育学会</span>
          <img src="@/assets/imgs/ydzx.png" width="100" height="50" alt="logo" class="logo">
          <span class="org-name">树人教育研究院</span>
        </header> -->

        <div class="glass-overlay">
          <!-- title -->
          <section v-if="showTitle" class="title-section">
            <Transition name="scroll-unfold" appear>
              <div v-if="showContent" class="title-wrapper">
                <div class="scroll-bg">
                  <!-- 预渲染所有背景图，用 opacity 切换避免加载抖动 -->
                  <img
                    v-for="(url, _key) in titleBgUrlMapping"
                    :key="_key"
                    :src="url"
                    class="scroll-bg-img"
                    :class="{
                      active: titleBgUrl === url && imageLoadStatus[url] !== false,
                      loading: imageLoadStatus[url] === undefined,
                    }"
                    :style="{ visibility: imageLoadStatus[url] === false ? 'hidden' : 'visible' }"
                    aria-hidden="true"
                    @load="imageLoadStatus[url] = true"
                    @error="imageLoadStatus[url] = false"
                  >
                  <Transition name="fade-in-delay" appear>
                    <h1 v-if="showContent" class="main-title">
                      {{ title }}
                    </h1>
                  </Transition>
                </div>
              </div>
            </Transition>
          </section>

          <!-- Main Content Slot -->
          <main class="main-content">
            <div v-if="showSlotContent" class="h-full w-full flex flex-col items-center justify-center">
              <slot />
            </div>
          </main>

          <!-- Footer Action -->
          <footer
            v-if="showButton"
            class="page-footer w-full flex items-center justify-between px-20"
            :class="[actionPosition, btnTheme]"
          >
            <div class="left">
              <ActionButton
                class="back-btn" :style="{ visibility: showBack ? 'visible' : 'hidden' }"
                :type="backBtnText ? 'text' : 'button'" :text="backBtnText || ''" :theme="btnTheme" @click="handleBack"
              >
                <SvgIcon v-if="!backBtnText" icon="mdi:arrow-left" size="40" class="arrow-icon" />
              </ActionButton>
            </div>

            <div class="right">
              <ActionButton
                v-if="showNext" :type="nextBtnText ? 'text' : 'button'" :text="nextBtnText || '下一步'"
                :theme="btnTheme" :disabled="nextDisabled" @click="handleNext"
              >
                <SvgIcon v-if="!nextBtnText" icon="mdi:arrow-right" class="arrow-icon" size="40" />
              </ActionButton>

              <ActionButton
                v-if="showNextBtn2" :type="nextBtnText2 ? 'text' : 'button'" :text="nextBtnText2 || '下一步'"
                :theme="btnTheme" :disabled="nextDisabled" @click="handleNext2"
              >
                <SvgIcon v-if="!nextBtnText2" icon="mdi:arrow-right" class="arrow-icon" size="40" />
              </ActionButton>
            </div>
          </footer>
        </div>
      </div>
    </VScaleScreen>
  </div>
</template>

<style lang="scss" scoped>
.title-section {
  margin: 10px auto;
  width: 412px;
  height: 165px;
  display: flex;
  justify-content: center; /* Ensure wrapper stays centered during expansion */

  .title-wrapper {
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: flex;
    justify-content: center; /* Keep the background image centered */
  }

  .scroll-bg {
    width: 400px !important; /* Fixed width to prevent squishing during animation */
    height: 155px !important;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    padding-bottom: 10px;
    flex-shrink: 0; /* Prevent shrinking */

    .scroll-bg-img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: contain;
      opacity: 0;
      transition: opacity 0.5s ease;
      pointer-events: none;

      &.active {
        opacity: 1;
      }

      &.loading {
        opacity: 0;
        filter: blur(2px);
      }
    }

    .main-title {
      font-size: 2.5rem;
      color: $text-color;
      margin: 0;
      letter-spacing: 4px;
      text-align: center;
      white-space: nowrap; /* Prevent text wrapping */
      position: relative;
      z-index: 1;
    }
  }
}

.competition-layout-wrapper {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  position: relative;
  background-color: #f0f2f5; // 给一个底色，防止背景图加载前白屏
}

.fixed-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  z-index: 0; // 提升 z-index，确保不被底层遮挡
  pointer-events: none;
}

.competition-layout {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 70px;
  overflow: hidden;
  position: relative;
  font-family: 'Noto Serif SC', serif;
  z-index: 2; // 确保内容在背景之上
  // margin: 10px auto;
  margin-top: 28px;

  // 底部波浪背景
  &::before {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 40%;
    background-repeat: no-repeat;
    background-position: bottom;
    background-size: cover;
    z-index: 0;
    pointer-events: none;
  }
}

.glass-overlay {
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(2px);
  border-radius: 30px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.6);
  display: flex;
  flex-direction: column;
  position: relative;
  z-index: 1;
  overflow: hidden;
}

.page-header {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 20px 40px;
  font-weight: 700;
  color: $secondary-color;
  z-index: 10;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center; // 让内容决定位置，通常是 margin-top
  // margin: 40px auto;
  z-index: 10;
  padding-bottom: 20px;
  width: 100%; // 确保内容宽度
}

.page-footer {
  position: absolute;
  bottom: 40px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  z-index: 20;

  .right {
    display: flex;
    gap: 10px;
  }

  &.top {
    bottom: auto;
    top: 40px;
  }
}

// Transitions
.scroll-unfold-enter-active {
  transition: width 1.5s cubic-bezier(0.25, 1, 0.5, 1);
}

.scroll-unfold-enter-from {
  width: 0 !important;
}

.fade-in-delay-enter-active {
  transition: opacity 0.8s ease;
  transition-delay: 1s; /* Wait for scroll to unfold */
}

.fade-in-delay-enter-from {
  opacity: 0;
}

.fade-slide-down-enter-active,
.fade-slide-down-leave-active {
  transition: all 0.8s ease;
}

.fade-slide-down-enter-from,
.fade-slide-down-leave-to {
  opacity: 0;
  transform: translateY(-30px);
}

// Responsive
@media (max-width: 768px) {
  .page-header {
    padding: 15px 20px;
    font-size: 1rem;
  }
}
</style>
