<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">
        <div class="flex-shrink-0 w-36">
          <span class="text-sm font-semibold text-gray-700 tracking-wide">member.ose.tw</span>
        </div>

        <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 flex items-center gap-2">
          <button
            v-if="showManualSync"
            @click="handleManualSync"
            :disabled="syncing"
            class="text-xs text-blue-600 border border-blue-200 hover:border-blue-300 hover:bg-blue-50 transition-colors px-2 py-1 rounded disabled:opacity-60 disabled:cursor-not-allowed"
          >
            {{ syncing ? '同步中...' : '手動同步' }}
          </button>
          <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, ref } from 'vue'
import { useRoute, useRouter, RouterLink } from 'vue-router'
import { ElMessage } from 'element-plus'
import { adminHttp } from '@/api/http'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const syncing = ref(false)

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 showManualSync = computed(() => route.path.startsWith('/admin'))

const adminTabs = [
  { to: '/admin/companies', label: '公司' },
  { to: '/admin/sites', label: '站台' },
  { to: '/admin/systems', label: '系統' },
  { to: '/admin/roles', label: '角色' },
  { to: '/admin/members', label: '會員' },
  { to: '/admin/api-clients', label: 'API Clients' }
]

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')
}

async function handleManualSync() {
  if (syncing.value) return
  syncing.value = true
  try {
    const res = await adminHttp.post('/admin/sync/from-provider', null, { params: { force: true } })
    const data = res?.data || {}
    ElMessage.success(
      `同步完成: 系統+${data.systems_created || 0}/${data.systems_updated || 0}, 角色+${data.roles_created || 0}/${data.roles_updated || 0}`
    )
  } catch (err) {
    const detail = err?.response?.data?.detail || err?.message || 'sync_failed'
    ElMessage.error(`同步失敗：${detail}`)
  } finally {
    syncing.value = false
  }
}
</script>
