<template>
  <div
    v-show="mobileNavOpen"
    class="fixed inset-0 z-[98] bg-apptext/20 backdrop-blur-[2px] md:hidden motion-safe:transition-opacity"
    aria-hidden="true"
    @click="closeMobileNav"
  />

  <div class="sticky top-0 z-[100] relative">
      <header
      class="flex items-center justify-between gap-2 min-h-[52px] px-[5vw] py-2.5 glass-strong border-b border-white/35 shadow-[0_4px_24px_rgba(33,33,40,0.08)] md:min-h-0 md:py-2.5 md:gap-3 max-md:px-3 max-md:py-2"
    >
      <div
        class="flex gap-4 items-center cursor-pointer select-none min-w-0 flex-1 md:flex-initial md:gap-4 max-md:gap-2"
        @click="onLogoClick"
      >
        <div class="w-10 h-10 md:w-11 md:h-11 rounded-[10px] overflow-hidden border border-white/60 glass-strong shadow-[0_12px_24px_rgba(33,33,40,0.18)] flex items-center justify-center shrink-0 max-md:w-9 max-md:h-9">
          <img src="/pwa-192x192.png" alt="萌芽小店" draggable="false" class="w-full h-full object-contain" />
        </div>
        <div class="min-w-0">
            <h1 class="text-[20px] md:text-[22px] tracking-wide truncate max-md:text-[15px] max-md:font-semibold text-apptext">萌芽小店</h1>
        </div>
      </div>

      <div class="hidden md:flex gap-3 items-center shrink-0">
        <button type="button" class="ghost" @click="goHome">商店</button>
        <template v-if="loggedIn">
          <button type="button" class="ghost relative inline-flex items-center gap-1" @click="goWishlist">
            <span>☆</span>
            收藏夹
            <span
              v-if="wishlistCount > 0"
              class="inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full bg-gradient-to-br from-accent to-accent2 text-white text-[11px] font-bold leading-none"
            >{{ wishlistCount }}</span>
          </button>
          <button type="button" class="ghost" @click="goMyOrders">我的订单</button>
          <div
            class="flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/60 border border-white/35 cursor-pointer hover:bg-white/85 transition-colors"
            @click="goProfile"
          >
            <img
              v-if="authState.avatarUrl"
              class="w-7 h-7 rounded-full object-cover border border-white/35"
              :src="authState.avatarUrl"
              :alt="authState.username"
            />
            <div
              v-else
              class="w-7 h-7 rounded-full flex items-center justify-center bg-gradient-to-br from-accent to-accent2 text-white text-[15px] font-semibold border border-white/35"
            >
              {{ (authState.username || authState.account || '?').charAt(0) }}
            </div>
            <span class="text-[17px] font-bold text-apptext max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap">
              {{ authState.username || authState.account }}
            </span>
          </div>
          <button type="button" class="ghost" @click="logout">退出</button>
        </template>
        <a
          v-else
          class="inline-flex items-center px-[18px] py-[10px] rounded-lg bg-gradient-to-br from-accent to-accent2 text-white no-underline text-[17px] shadow-[0_10px_30px_rgba(184,109,92,0.32)] transition-transform hover:-translate-y-px"
          :href="loginUrl"
        >萌芽账号登录</a>
      </div>

      <button
        type="button"
        class="md:hidden flex-shrink-0 flex items-center justify-center w-10 h-10 rounded-xl border border-white/50 bg-white/60 text-apptext shadow-sm tap-target"
        :aria-expanded="mobileNavOpen"
        :aria-label="mobileNavOpen ? '关闭菜单' : '打开菜单'"
        @click="mobileNavOpen = !mobileNavOpen"
      >
        <svg v-if="!mobileNavOpen" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
          <path d="M4 6h16M4 12h16M4 18h16"/>
        </svg>
        <svg v-else width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
          <path d="M18 6L6 18M6 6l12 12"/>
        </svg>
      </button>
    </header>

    <Transition
      enter-active-class="transition ease-out duration-200"
      enter-from-class="opacity-0 -translate-y-2"
      enter-to-class="opacity-100 translate-y-0"
      leave-active-class="transition ease-in duration-150"
      leave-from-class="opacity-100 translate-y-0"
      leave-to-class="opacity-0 -translate-y-2"
    >
      <nav
        v-if="mobileNavOpen"
        class="md:hidden absolute left-0 right-0 top-full z-[101] border-t border-white/35 glass-strong shadow-[0_16px_40px_rgba(33,33,40,0.14)] max-h-[min(75vh,560px)] overflow-y-auto overscroll-contain px-3 py-3 pb-[max(16px,env(safe-area-inset-bottom))]"
        @click.stop
      >
        <div class="flex flex-col gap-2">
          <button type="button" class="app-mobile-nav-btn" @click="navGoHome">商店</button>
          <template v-if="loggedIn">
            <button type="button" class="app-mobile-nav-btn flex items-center justify-between gap-3" @click="navGoWishlist">
              <span class="inline-flex items-center gap-1.5">
                <span class="text-accent">☆</span>
                收藏夹
              </span>
              <span
                v-if="wishlistCount > 0"
                class="inline-flex items-center justify-center min-w-[22px] h-[22px] px-1.5 rounded-full bg-gradient-to-br from-accent to-accent2 text-white text-[12px] font-bold"
              >{{ wishlistCount }}</span>
            </button>
            <button type="button" class="app-mobile-nav-btn" @click="navGoMyOrders">我的订单</button>
            <button type="button" class="app-mobile-nav-btn flex items-center gap-3 text-left min-w-0" @click="navGoProfile">
              <img
                v-if="authState.avatarUrl"
                class="w-9 h-9 rounded-full object-cover border border-white/35 shrink-0"
                :src="authState.avatarUrl"
                alt=""
              />
              <div
                v-else
                class="w-9 h-9 rounded-full flex items-center justify-center bg-gradient-to-br from-accent to-accent2 text-white text-sm font-semibold shrink-0"
              >
                {{ (authState.username || authState.account || '?').charAt(0) }}
              </div>
              <span class="font-bold truncate min-w-0">{{ authState.username || authState.account }}</span>
              <span class="text-muted text-[13px] shrink-0 ml-auto">个人主页</span>
            </button>
            <button type="button" class="app-mobile-nav-btn !text-[#b84d5c] !border-[rgba(184,77,92,0.25)]" @click="navLogout">
              退出登录
            </button>
          </template>
          <a
            v-else
            class="app-mobile-nav-btn app-mobile-nav-btn-primary text-center no-underline"
            :href="loginUrl"
            @click="closeMobileNav"
          >萌芽账号登录</a>
        </div>
      </nav>
    </Transition>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { authState, clearAuth } from '../shared/auth'

defineProps({
  loggedIn: { type: Boolean, required: true },
  loginUrl: { type: String, required: true },
  wishlistCount: { type: Number, default: 0 }
})

const emit = defineEmits(['admin-unlock'])

const router = useRouter()
const mobileNavOpen = ref(false)

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

function onLogoClick() {
  logoClickCount++
  clearTimeout(logoClickTimer)
  if (logoClickCount >= CLICK_THRESHOLD) {
    logoClickCount = 0
    emit('admin-unlock')
    return
  }
  logoClickTimer = setTimeout(() => {
    logoClickCount = 0
  }, CLICK_WINDOW_MS)
}

const closeMobileNav = () => {
  mobileNavOpen.value = false
}

const goHome = () => router.push('/')
const goMyOrders = () => router.push('/my/orders')
const goWishlist = () => router.push('/wishlist')

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

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

const navGoHome = () => {
  closeMobileNav()
  goHome()
}
const navGoWishlist = () => {
  closeMobileNav()
  goWishlist()
}
const navGoMyOrders = () => {
  closeMobileNav()
  goMyOrders()
}
const navGoProfile = () => {
  closeMobileNav()
  goProfile()
}
const navLogout = () => {
  closeMobileNav()
  logout()
}

watch(
  () => router.currentRoute.value.fullPath,
  () => closeMobileNav()
)

watch(mobileNavOpen, (open) => {
  if (typeof document === 'undefined') return
  document.body.style.overflow = open ? 'hidden' : ''
})

const onNavEscape = (e) => {
  if (e.key === 'Escape') closeMobileNav()
}

onMounted(() => {
  window.addEventListener('keydown', onNavEscape)
})

onUnmounted(() => {
  window.removeEventListener('keydown', onNavEscape)
  if (typeof document !== 'undefined') document.body.style.overflow = ''
  clearTimeout(logoClickTimer)
})
</script>

<style scoped>
.app-mobile-nav-btn {
  width: 100%;
  box-sizing: border-box;
  text-align: left;
  padding: 0.875rem 1rem;
  border-radius: 0.75rem;
  border: 1px solid var(--line-color);
  background: rgba(255, 255, 255, 0.58);
  color: var(--color-apptext);
  font-size: 16px;
  font-weight: 700;
  font-family: var(--font-serif);
  cursor: pointer;
  transition: background 0.15s ease, transform 0.12s ease;
}
.app-mobile-nav-btn:hover {
  background: rgba(255, 255, 255, 0.78);
}
.app-mobile-nav-btn:active {
  transform: scale(0.99);
}
.app-mobile-nav-btn-primary {
  background: linear-gradient(135deg, var(--color-accent), var(--color-accent2));
  color: #fff !important;
  border-color: transparent;
  box-shadow: 0 8px 24px rgba(184, 109, 92, 0.32);
}
.tap-target {
  min-width: 44px;
  min-height: 44px;
}
</style>
