<template>
  <div class="user-layout">
    <div class="sidebar-mask" v-if="showMobileMenu" @click="showMobileMenu = false" />

    <aside class="sidebar" :class="{ collapsed, 'mobile-show': showMobileMenu }">
      <div class="sidebar-header">
        <router-link to="/workspace" class="logo">{{ collapsed ? 'TM' : 'TradeMate' }}</router-link>
        <div class="sidebar-header-actions">
          <el-button text class="collapse-btn dt-only" @click="collapsed = !collapsed">
            <el-icon><Fold v-if="!collapsed" /><Expand v-else /></el-icon>
          </el-button>
          <el-button v-if="showMobileMenu" text class="collapse-btn" @click="showMobileMenu = false">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </div>
      <el-menu
        :default-active="route.path"
        :collapse="collapsed"
        router
        :collapse-transition="false"
        @select="showMobileMenu = false"
      >
        <el-menu-item index="/workspace"><el-icon><Odometer /></el-icon><span>{{ $t('nav.home') }}</span></el-menu-item>
        <el-menu-item index="/workspace/customers"><el-icon><User /></el-icon><span>{{ $t('nav.customers') }}</span></el-menu-item>
        <el-menu-item index="/workspace/biz"><el-icon><Goods /></el-icon><span>{{ $t('nav.biz') }}</span></el-menu-item>
        <el-menu-item index="/workspace/analytics"><el-icon><DataAnalysis /></el-icon><span>{{ $t('nav.analytics') }}</span></el-menu-item>
        <el-sub-menu index="more">
          <template #title>
            <el-icon><Menu /></el-icon>
            <span>{{ $t('nav.more') || '更多' }}</span>
          </template>
          <el-menu-item index="/workspace/profile"><el-icon><User /></el-icon><span>{{ $t('nav.profile') }}</span></el-menu-item>
          <el-menu-item index="/workspace/team"><el-icon><UserFilled /></el-icon><span>{{ $t('nav.team') }}</span></el-menu-item>
        </el-sub-menu>
      </el-menu>
    </aside>

    <div class="main-area">
      <header class="topbar">
        <el-button text class="menu-btn" @click="showMobileMenu = true">
          <el-icon :size="20"><Expand /></el-icon>
        </el-button>
        <el-breadcrumb separator="/" class="breadcrumb">
          <el-breadcrumb-item :to="'/workspace'">{{ $t('nav.home') || '首页工作台' }}</el-breadcrumb-item>
          <el-breadcrumb-item v-if="route.meta?.title && route.path !== '/workspace'" :to="route.path">{{ $t('nav.' + route.name?.toLowerCase()) || route.meta.title }}</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="topbar-right">
          <el-button text style="font-size:13px;color:#999" @click="toggleLang">{{ currentLang }}</el-button>
          <el-button v-if="creditBalance !== null" text class="credit-btn" @click="$router.push('/workspace/profile/credits')">
            <el-icon><Coin /></el-icon>
            <span class="credit-text">{{ creditBalance }} {{ $t('topbar.credits') }}</span>
          </el-button>
          <el-badge :value="unread" :hidden="!unread" class="notif-badge">
            <el-button text style="font-size:18px" @click="$router.push('/workspace/profile/notifications')">
              <el-icon><Bell /></el-icon>
            </el-button>
          </el-badge>
          <el-dropdown trigger="click">
            <el-button text style="display:flex;align-items:center;gap:6px">
              <el-icon><User /></el-icon>
              <span class="user-name">{{ displayName }}</span>
              <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="$router.push('/workspace/profile')">{{ $t('nav.profile') }}</el-dropdown-item>
                <el-dropdown-item @click="$router.push('/workspace/profile/notifications')">{{ $t('nav.notifications') }}</el-dropdown-item>
                <el-dropdown-item divided @click="handleLogout">{{ $t('common.confirm') }}退出</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </header>

      <main class="content">
        <router-view />
      </main>


    </div>
    <CommandK />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '@/stores/auth'
import { getUnreadCount, getCreditBalance } from '@/api'
import CommandK from '@/components/CommandK.vue'
import { switchLang } from '@/i18n'

const route = useRoute()
const router = useRouter()
const { locale } = useI18n()
const auth = useAuthStore()
const collapsed = ref(window.innerWidth < 1024)
const showMobileMenu = ref(false)
const unread = ref(0)
const creditBalance = ref(null)

function handleResize() {
  const w = window.innerWidth
  collapsed.value = w < 1024
  if (w >= 768) showMobileMenu.value = false
}
onMounted(() => window.addEventListener('resize', handleResize))
onUnmounted(() => window.removeEventListener('resize', handleResize))

const displayName = computed(() => {
  const u = auth.user
  if (u && typeof u === 'object' && typeof u.username === 'string') return u.username
  return '用户'
})

const currentLang = computed(() => locale.value === 'en' ? 'English' : '中文')
function toggleLang() {
  const next = locale.value === 'en' ? 'zh-CN' : 'en'
  switchLang(next)
}

async function loadCreditBalance() {
  try {
    const res = await getCreditBalance()
    creditBalance.value = res.balance
  } catch (e) { creditBalance.value = null }
}

onMounted(async () => {
  try {
    const res = await getUnreadCount()
    unread.value = res.count || res || 0
  } catch { /* ignore */ }
  loadCreditBalance()
})

function handleLogout() {
  auth.logout()
  router.push('/')
}
</script>

<style scoped>
/* ===== Base Layout ===== */
.user-layout { display: flex; height: 100vh; overflow: hidden; }
.sidebar-mask { display: none; }
.main-area { flex: 1; display: flex; flex-direction: column; min-width: 0; }
.content { flex: 1; padding: 24px; overflow-y: auto; background: #f5f5f5; }

/* ===== Sidebar ===== */
.sidebar {
  width: 220px; background: #fff; border-right: 1px solid #e8e8e8;
  transition: width 0.25s; flex-shrink: 0; display: flex; flex-direction: column;
  position: relative; z-index: 100;
}
.sidebar.collapsed { width: 64px; }
.sidebar-header {
  height: 60px; display: flex; align-items: center; padding: 0 12px;
  color: #1890ff; font-size: 18px; font-weight: 700; border-bottom: 1px solid #f0f0f0; flex-shrink: 0;
  gap: 8px;
}
.sidebar-header .logo { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sidebar-header-actions { display: flex; flex-shrink: 0; }
.collapse-btn { font-size: 18px; color: #999; }
.dt-only { display: none; }
.sidebar :deep(.el-menu) { border-right: none; flex: 1; }
.sidebar :deep(.el-menu-item) { margin: 2px 8px; border-radius: 8px; white-space: nowrap; }
.sidebar :deep(.el-menu-item.is-active) { background: #e6f7ff; color: #1890ff !important; font-weight: 500; }

/* ===== Topbar ===== */
.topbar {
  height: 60px; background: #fff; border-bottom: 1px solid #e8e8e8;
  display: flex; align-items: center; padding: 0 16px; flex-shrink: 0; gap: 12px;
}
.menu-btn { display: none; font-size: 20px; }
.breadcrumb { flex: 1; min-width: 0; overflow: hidden; }
.breadcrumb :deep(.el-breadcrumb__inner) { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 160px; display: inline-block; vertical-align: middle; }
.topbar-right { margin-left: auto; display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
.notif-badge :deep(.el-badge__content) { top: 8px; right: 4px; }
.credit-btn { display: flex; align-items: center; gap: 4px; color: #e6a23c !important; font-weight: 600; }

/* ===== Desktop: > 1024px ===== */
@media (min-width: 1025px) {
  .dt-only { display: inline-flex; }
  .sidebar-header { padding: 0 16px; }
  .sidebar.collapsed .sidebar-header { justify-content: center; }
  .sidebar.collapsed .sidebar-header .logo { font-size: 16px; text-align: center; }
}

/* ===== Tablet: 769-1024px ===== */
@media (min-width: 769px) and (max-width: 1024px) {
  .sidebar { width: 64px; }
  .sidebar-header { padding: 0; justify-content: center; }
  .sidebar-header .logo { font-size: 16px; flex: none; }
  .sidebar-header-actions .dt-only { display: none; }
  .menu-btn { display: inline-flex; }
  .content { padding: 20px; }
}

/* ===== Mobile: < 769px ===== */
@media (max-width: 768px) {
  .sidebar {
    position: fixed; left: -220px; top: 0; bottom: 0; z-index: 1000;
    transition: left 0.3s; width: 220px;
  }
  .sidebar.collapsed { width: 220px; }
  .sidebar.mobile-show { left: 0; }
  .sidebar.collapsed.mobile-show { left: 0; }
  .sidebar-header { padding: 0 16px; }
  .sidebar-header .logo { font-size: 18px; flex: 1; }
  .sidebar-header-actions .dt-only { display: none; }
  .sidebar-mask {
    display: block; position: fixed; inset: 0; background: rgba(0,0,0,0.3);
    z-index: 999; opacity: 0; pointer-events: none; transition: opacity 0.3s;
  }
  .sidebar-mask:has(+ .sidebar.mobile-show) { opacity: 1; pointer-events: auto; }
  .menu-btn { display: inline-flex; }
  .user-name { display: none; }
  .content { padding: 16px; }
  .breadcrumb :deep(.el-breadcrumb__inner) { max-width: 80px; }
}

/* ===== Tiny: < 480px ===== */
@media (max-width: 480px) {
  .topbar-right { gap: 4px; }
  .credit-text { display: none; }
  .content { padding: 12px; }
  .breadcrumb :deep(.el-breadcrumb__inner) { max-width: 60px; }
}
</style>
