<template>
  <div class="min-h-screen bg-gray-50">
    <header v-if="showNav" class="bg-white border-b border-gray-200 sticky top-0 z-50 shadow-sm">
      <div class="max-w-7xl mx-auto px-6 flex items-center justify-between h-14">

        <!-- Logo 區（之後換圖） -->
        <div class="flex-shrink-0 w-36">
          <span class="text-sm font-semibold text-gray-700 tracking-wide">member.ose.tw</span>
        </div>

        <!-- Tab 導覽 -->
        <nav class="flex items-stretch h-full overflow-x-auto gap-0 flex-1 min-w-0">
          <NavTab v-for="tab in userTabs" :key="tab.to" :to="tab.to">{{ tab.label }}</NavTab>

          <span class="self-center mx-3 text-gray-200 select-none text-lg">|</span>

          <NavTab v-for="tab in adminTabs" :key="tab.to" :to="tab.to">{{ tab.label }}</NavTab>
        </nav>

        <!-- 右側：登出 -->
        <div class="flex-shrink-0 ml-4">
          <button
            @click="logout"
            class="text-xs text-gray-400 hover:text-gray-600 transition-colors px-2 py-1 rounded hover:bg-gray-100"
          >
            登出
          </button>
        </div>

      </div>
    </header>

    <main class="p-6 max-w-6xl mx-auto">
      <router-view />
    </main>
  </div>
</template>

<script setup>
import { computed, defineComponent, h } from 'vue'
import { useRoute, useRouter, RouterLink } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const showNav = computed(() => {
  const onAuthPage = route.name === 'login' || route.name === 'auth-callback'
  return authStore.isLoggedIn && !onAuthPage
})

const userTabs = [
  { to: '/me', label: '我的資料' },
  { to: '/me/permissions', label: '我的權限' }
]

const adminTabs = [
  { to: '/admin/systems', label: '系統' },
  { to: '/admin/modules', label: '模組' },
  { to: '/admin/companies', label: '公司' },
  { to: '/admin/sites', label: '站台' },
  { to: '/admin/members', label: '會員' },
  { to: '/admin/permission-groups', label: '群組' }
]

// 行內 NavTab 元件：避免另開檔案
const NavTab = defineComponent({
  props: { to: String },
  setup(props, { slots }) {
    return () => h(RouterLink, { to: props.to, custom: true }, {
      default: ({ isActive, navigate }) => h('button', {
        onClick: navigate,
        class: [
          'px-3 h-full text-sm whitespace-nowrap border-b-2 transition-all duration-150 flex items-center',
          isActive
            ? 'border-blue-500 text-blue-600 font-medium bg-blue-50/40'
            : 'border-transparent text-gray-500 hover:text-gray-800 hover:border-gray-300'
        ].join(' ')
      }, slots.default?.())
    })
  }
})

function logout() {
  authStore.logout()
  router.push('/login')
}
</script>
