<template>
  <div class="app">
    <header class="top-bar">
      <div class="brand" @click="onLogoClick">
        <div class="brand-mark">
          <img src="/logo.png" alt="萌芽小店" draggable="false" />
        </div>
        <div>
          <h1>萌芽小店</h1>
        </div>
      </div>
      <div class="top-actions">
        <button class="ghost" @click="goHome">商店</button>
        <template v-if="loggedIn">
          <button class="ghost" @click="goMyOrders">我的订单</button>
          <div class="user-badge" @click="goProfile">
            <img
              v-if="authState.avatarUrl"
              class="user-avatar"
              :src="authState.avatarUrl"
              :alt="authState.username"
            />
            <div v-else class="user-avatar user-avatar-placeholder">
              {{ (authState.username || authState.account || '?').charAt(0) }}
            </div>
            <span class="user-name">{{ authState.username || authState.account }}</span>
          </div>
          <button class="ghost" @click="logout">退出</button>
        </template>
        <a v-else class="login-btn" :href="loginUrl">萌芽账号登录</a>
      </div>
    </header>

    <Teleport to="body">
      <Transition name="modal">
        <div v-if="showAdminModal" class="admin-modal-overlay" @click.self="showAdminModal = false">
          <div class="admin-modal">
            <button class="admin-modal-close" @click="showAdminModal = false">&times;</button>
            <div class="admin-modal-icon">
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
            </div>
            <h3>管理员验证</h3>
            <p class="admin-modal-hint">请输入管理员令牌以访问后台</p>
            <form @submit.prevent="submitAdminToken">
              <input
                ref="tokenInputRef"
                v-model="tokenInput"
                type="password"
                class="admin-modal-input"
                placeholder="输入 Token…"
                autocomplete="off"
              />
              <p v-if="tokenError" class="admin-modal-error">{{ tokenError }}</p>
              <button type="submit" class="primary admin-modal-btn" :disabled="!tokenInput.trim()">
                进入后台
              </button>
            </form>
          </div>
        </div>
      </Transition>
    </Teleport>

    <div class="app-body">
    <main class="main-content">
      <router-view />
    </main>

    <footer class="footer">
      <div class="footer-inner">
        <div class="footer-brand">
          <img src="/logo.png" alt="萌芽小店" class="footer-logo" />
          <span class="footer-title">萌芽小店</span>
        </div>
        <div class="footer-divider"></div>
        <div class="footer-links">
          <a class="footer-mail" href="mailto:mail@smyhub.com">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>
            mail@smyhub.com
          </a>
          <span v-if="statsLoaded" class="footer-stat">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20V10"/><path d="M18 20V4"/><path d="M6 20v-4"/></svg>
            累计下单 {{ stats.totalOrders }} 次
          </span>
          <span v-if="statsLoaded" class="footer-stat footer-stat-visit">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>
            累计访问 {{ stats.totalVisits }} 次
          </span>
        </div>
        <p class="footer-copy">© 2025 – 2026 萌芽小店 · All rights reserved</p>
      </div>
    </footer>
    </div>
  </div>
</template>

<script setup>
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { fetchAdminToken, fetchStats, recordSiteVisit } from './modules/shared/api'
import { authState, isLoggedIn, clearAuth, getLoginUrl } from './modules/shared/auth'

const router = useRouter()
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 tokenInputRef = ref(null)

let logoClickCount = 0
let logoClickTimer = null
const CLICK_THRESHOLD = 5
const CLICK_WINDOW_MS = 2000

const onLogoClick = () => {
  logoClickCount++
  clearTimeout(logoClickTimer)
  if (logoClickCount >= CLICK_THRESHOLD) {
    logoClickCount = 0
    tokenInput.value = ''
    tokenError.value = ''
    showAdminModal.value = true
    nextTick(() => tokenInputRef.value?.focus())
    return
  }
  logoClickTimer = setTimeout(() => { logoClickCount = 0 }, CLICK_WINDOW_MS)
}

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

const goHome = () => { router.push('/') }
const goMyOrders = () => { router.push('/my/orders') }

const goProfile = () => {
  if (authState.account) {
    window.open(`https://auth.shumengya.top/user/${authState.account}`, '_blank')
  }
}

const logout = () => { clearAuth() }

onMounted(async () => {
  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
  }
})
</script>
