<template>
  <div class="relative flex flex-col min-h-screen">
    <div class="app-randbg" aria-hidden="true">
      <img
        v-if="randBgUrl"
        class="app-randbg-img"
        :src="randBgUrl"
        alt=""
        decoding="async"
        fetchpriority="low"
      />
    </div>

    <SplashScreen :visible="showSplash" />

    <AppTopNav
      :logged-in="loggedIn"
      :login-url="loginUrl"
      :wishlist-count="wishlistCount"
      @admin-unlock="openAdminModal"
    />

    <AppAdminUnlockModal
      v-model:open="showAdminModal"
      v-model:token="tokenInput"
      :error="tokenError"
      @submit="submitAdminToken"
    />

    <div class="flex-1 flex flex-col px-[5vw] py-4 max-md:px-[2vw] max-md:py-3 min-h-0">
      <template v-if="mergePageShell">
        <div class="page-card flex flex-col flex-1 min-h-0">
          <main class="flex-1 min-h-0">
            <router-view />
          </main>
          <AppSiteFooter
            embedded
            :stats-loaded="statsLoaded"
            :total-orders="stats.totalOrders"
            :total-visits="stats.totalVisits"
          />
        </div>
      </template>
      <template v-else>
        <main class="flex-1 py-4 min-h-0 max-md:py-3">
          <router-view />
        </main>

        <AppSiteFooter
          :stats-loaded="statsLoaded"
          :total-orders="stats.totalOrders"
          :total-visits="stats.totalVisits"
        />
      </template>
    </div>

    <ChatWidget
      v-if="loggedIn && authState.token"
      :user-token="authState.token"
      :user-name="authState.username || authState.account"
      :user-avatar="authState.avatarUrl"
    />

    <Transition name="pwa-toast">
      <div
        v-if="needRefresh"
        class="fixed bottom-20 left-1/2 -translate-x-1/2 z-[9999] flex items-center gap-3 px-[18px] py-2.5 rounded-3xl bg-[#1a1a1a] text-white text-[13px] shadow-[0_4px_24px_rgba(0,0,0,0.25)] whitespace-nowrap"
      >
        <span>发现新版本</span>
        <button
          class="bg-[#4ade80] text-[#111] border-none rounded-xl px-3.5 py-1 text-xs font-semibold cursor-pointer"
          @click="updateServiceWorker(true)"
        >立即更新</button>
      </div>
    </Transition>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { verifyAdminToken, fetchStats, recordSiteVisit } from './modules/shared/api'
import { authState, isLoggedIn, getLoginUrl } from './modules/shared/auth'
import { wishlistCount, loadWishlist } from './modules/shared/useWishlist'
import ChatWidget from './modules/chat/ChatWidget.vue'
import SplashScreen from './modules/shared/SplashScreen.vue'
import AppTopNav from './modules/shell/AppTopNav.vue'
import AppAdminUnlockModal from './modules/shell/AppAdminUnlockModal.vue'
import AppSiteFooter from './modules/shell/AppSiteFooter.vue'
import { useRegisterSW } from 'virtual:pwa-register/vue'

const RAND_BG_JSON_URL = 'https://randbg.api.smyhub.com/api/random?format=json'

const { needRefresh, updateServiceWorker } = useRegisterSW({
  onRegisteredSW(swUrl, r) {
    if (r) setInterval(() => r.update(), 1000 * 60 * 60)
  }
})

const showSplash = ref(true)
const randBgUrl = ref('')

const router = useRouter()
const route = useRoute()
const mergePageShell = computed(() => route.path !== '/admin')
const stats = reactive({ totalOrders: 0, totalVisits: 0 })
const statsLoaded = ref(false)

const loggedIn = computed(() => isLoggedIn())
const loginUrl = computed(() => getLoginUrl())

const showAdminModal = ref(false)
const tokenInput = ref('')
const tokenError = ref('')

const openAdminModal = () => {
  tokenInput.value = ''
  tokenError.value = ''
  showAdminModal.value = true
}

const submitAdminToken = async () => {
  const input = tokenInput.value.trim()
  if (!input) return
  tokenError.value = ''
  try {
    const valid = await verifyAdminToken(input)
    if (valid) {
      showAdminModal.value = false
      router.push(`/admin?token=${encodeURIComponent(input)}`)
    } else {
      tokenError.value = '令牌错误，请重试'
    }
  } catch {
    tokenError.value = '验证失败，无法连接服务器'
  }
}

const SPLASH_MIN_MS = 1400

onMounted(async () => {
  const splashStart = Date.now()

  fetch(RAND_BG_JSON_URL)
    .then((r) => r.json())
    .then((data) => {
      if (data && typeof data.url === 'string') randBgUrl.value = data.url
    })
    .catch(() => {})

  await loadWishlist()
  try {
    recordSiteVisit().then((result) => {
      if (result.totalVisits) stats.totalVisits = result.totalVisits
    }).catch(() => {})
    const data = await fetchStats()
    stats.totalOrders = data.totalOrders || 0
    stats.totalVisits = data.totalVisits || 0
    statsLoaded.value = true
  } catch (e) {
    statsLoaded.value = false
  }

  const elapsed = Date.now() - splashStart
  const remaining = SPLASH_MIN_MS - elapsed
  setTimeout(() => {
    showSplash.value = false
  }, remaining > 0 ? remaining : 0)
})

watch(() => authState.token, async (newToken) => {
  if (newToken) {
    await loadWishlist()
  }
})
</script>
