<template>
  <!-- 顶部栏（仅小屏显示） -->
  <header v-if="showHeader === false" class="lg:hidden sticky top-0 z-40 bg-white/90 backdrop-blur border-amber-50 shadow">
    <div class="h-14 px-4 flex items-center justify-between">
      <button
        class="inline-flex items-center gap-2 px-3 py-2 rounded-md hover:bg-gray-50"
        aria-controls="mobile-drawer"
        :aria-expanded="open"
        aria-label="Open menu"
        @click="open = true"
      >
        ☰ <span class="text-sm"></span>
      </button>
      <h1 class="text-lg font-bold">{{ activeKey }}</h1>
      <div class="w-10"></div>
    </div>
  </header>

  <!-- 主体：铺满屏幕；PC 为两列（左侧 260 固定，右侧自适应） -->
  <div class="">
    <div class="grid lg:grid-cols-[100px_minmax(0,1fr)]">
      <!-- PC 左侧固定侧栏（紧贴屏幕左边） -->
      <aside class="hidden lg:block">
        <nav class="sticky top-0 bottom-0 bg-white p-2 items-center flex flex-col h-screen">
          <img
            @click="toHome"
            :src="iconImg"
            alt=""
            style="width: 50px; margin-bottom: 50px; margin-top: 20px"
          />
          <button
            v-for="item in items"
            :key="item.key"
            class="w-full text-left flex-col flex items-center gap-2 px-3 py-2 rounded-md mb-5"
            :class="activeKey === item.label ? 'bg-[#d8ffee] text-gray-900' : ''"
            @click="select(item.key)"
          >
            <component :is="nowIcon(item.key)" class="w-6 h-6 text-black" />
            <span
              style="font-weight: 300; font-size: 16px"
              :class="activeKey === item.label ? 'text-green-700' : ''"
              >{{ item.label }}</span
            >
          </button>
        </nav>
      </aside>

      <!-- 右侧内容区（可选做个最大宽度，避免超宽行；不影响左侧贴边） -->
      <main class="min-h-[60vh]">
        <!-- <div class="max-w-6xl mx-auto"> -->
        <RouterView></RouterView>
        <!-- </div> -->
      </main>
    </div>
  </div>

  <!-- 小屏抽屉：遮罩 -->
  <transition name="fade">
    <div v-if="open" class="lg:hidden fixed inset-0 z-50 bg-black/40" @click="close"></div>
  </transition>

  <!-- 小屏抽屉：面板（左侧弹出） -->
  <transition name="slide-left">
    <aside
      v-if="open"
      id="mobile-drawer"
      class="lg:hidden fixed inset-y-0 left-0 z-50 w-72 bg-white shadow-xl"
    >
      <div class="h-14 px-3 flex items-center justify-between">
        <!-- <span class="text-sm font-medium">Menu</span> -->
        <button
          class="px-2 py-1 rounded-md hover:bg-gray-100"
          aria-label="Close menu"
          @click="close"
        >
          ✕
        </button>
      </div>
      <nav class="p-2">
        <button
          v-for="item in items"
          :key="item.key"
          class="w-full text-left flex items-center gap-2 px-3 py-2 rounded-md mb-3"
          :class="activeKey === item.label ? 'bg-[#d8ffee] text-gray-900' : ''"
          @click="select(item.key, true)"
        >
          <component :is="nowIcon(item.key)" class="w-6 h-6 text-black" />
          <span
            style="font-weight: 300; font-size: 16px"
            :class="activeKey === item.label ? 'text-green-700' : ''"
            >{{ item.label }}</span
          >
        </button>
      </nav>
    </aside>
  </transition>
</template>
  

<script setup>
import { ref, watchEffect, onMounted, onBeforeUnmount, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import iconImg from '@/assets/icon.jpg'
import { useRoute } from 'vue-router'
import { HomeIcon, CurrencyDollarIcon, UserCircleIcon } from '@heroicons/vue/24/outline'

const router = useRouter()
const route = useRoute()
const props = defineProps({
  /** 小屏顶部标题 */
  title: { type: String, default: 'My App' },
  /** 菜单项 */
  items: {
    type: Array,
    default: () => [
      { key: 'home', label: 'Home', icon: 'HomeIcon' },
      { key: 'rewards', label: 'Rewards', icon: 'CurrencyDollarIcon' },
      { key: 'account', label: 'Account', icon: 'UserCircleIcon' },
    ],
  },
  /** 初始激活项（默认 home） */
  defaultActive: { type: String, default: 'home' },
})
// const emit = defineEmits(['update:active', 'select'])

const open = ref(false)

function select(key, shouldClose = false) {
  router.push({ path: `/${key}` })
  //   activeKey.value = key
  //   emit('update:active', key)
  //   emit('select', key)
  if (shouldClose) close()
}
function close() {
  open.value = false
}

// ESC 关闭、抽屉开时锁定滚动
function onKey(e) {
  if (e.key === 'Escape') close()
}

// watch(
//   () => route.path,
//   (newPath) => {
//     console.log('现在的路径是：', newPath)
//   },
//   {
//     immediate: true,
//   }
// )
const activeKey = computed(() => {
  const key = route.path.split('/')[1] || 'home'
  const value = props.items.find((i) => i.key === key)
  return value?.label ?? ''
})
const showHeader = computed(() => {
  console.log(route.meta.hideHeader)
  return route.meta.hideHeader
})
const nowIcon = (location) => {
  if (location == 'home') {
    return HomeIcon
  } else if (location == 'rewards') {
    return CurrencyDollarIcon
  } else {
    return UserCircleIcon
  }
}
const toHome = () => {
  router.push({ path: '/home' })
}

onMounted(() => window.addEventListener('keydown', onKey))
onBeforeUnmount(() => window.removeEventListener('keydown', onKey))

watchEffect(() => {
  document.documentElement.style.overflow = open.value ? 'hidden' : ''
})
</script>
  

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
.slide-left-enter-active,
.slide-left-leave-active {
  transition: transform 0.25s ease;
}
.slide-left-enter-from,
.slide-left-leave-to {
  transform: translateX(-100%);
}
</style>
  