<script setup lang="ts">
/**
 * 「我的」页：始终可访问本地设置（主题等）。
 * 账号相关入口跳转独立登录页；员工才显示后台能力。
 * 菜单默认宫格，可切换列表并本地持久化。
 */
import { computed, ref } from 'vue'
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app'
import { useToast, useDialog } from '@wot-ui/ui'
import AppNavbar from '@/components/layout/AppNavbar.vue'
import AppFloatingTabbar from '@/components/layout/AppFloatingTabbar.vue'
import AppPageShell from '@/components/layout/AppPageShell.vue'
import ProfileHero from '@/components/c-end/ProfileHero.vue'
import ArtMenuGroup from '@/components/c-end/ArtMenuGroup.vue'
import ArtMenuItem from '@/components/c-end/ArtMenuItem.vue'
import { useTheme } from '@/composables/useTheme'
import { useAuth } from '@/composables/useAuth'
import { useAppMode } from '@/composables/useAppMode'
import { isStaffRole } from '@/config/menus'
import { resolveMediaUrl } from '@/utils/request'

const LAYOUT_KEY = 'mine-menu-layout'
type MenuLayout = 'grid' | 'list'

const toast = useToast()
/** 与页面内 wd-dialog selector 对应，确保 inject 能命中 */
const dialog = useDialog('merge-account')
const { themeLabel, apply } = useTheme()
const { isAuthenticated, getUser, logout } = useAuth()
const { appMode, canEnterAdmin, enterAdminMode, enterUserMode } = useAppMode()

const authed = ref(false)
const user = ref(getUser())
/** 菜单排版：默认宫格 */
const menuLayout = ref<MenuLayout>('grid')

const DEFAULT_AVATAR = '/static/default-avatar.svg'

/** 从本地恢复宫格/列表偏好 */
const loadMenuLayout = () => {
  const raw = uni.getStorageSync(LAYOUT_KEY)
  menuLayout.value = raw === 'list' ? 'list' : 'grid'
}

/** 头像：未登录用默认图，已登录优先用户头像 */
const avatarUrl = computed(() => {
  if (!authed.value) return DEFAULT_AVATAR
  return resolveMediaUrl(user.value.avatar) || DEFAULT_AVATAR
})

/** 是否游客或匿名（含微信游客_前缀）；须先于副文案/徽章计算 */
const isGuestOrAnon = computed(() => {
  if (!authed.value) return true
  const u = user.value
  return !isStaffRole(u.role) || String(u.username || '').startsWith('游客_')
})

/** 主标题：未登录显示「未登录」，已登录显示昵称 */
const displayName = computed(() => {
  if (!authed.value) return '未登录'
  return user.value.username || '游客'
})

/** 副文案：C 端友好说明，弱化技术角色名 */
const displaySubtitle = computed(() => {
  if (!authed.value) return '登录后可同步更多内容'
  if (isGuestOrAnon.value) return '欢迎回来，继续探索数字花园'
  return '员工身份已就绪'
})

/** 状态 pill：访客 / 角色，避免纯英文 GUEST */
const displayBadge = computed(() => {
  if (!authed.value) return '访客'
  if (isGuestOrAnon.value) return '访客'
  const role = (user.value.role || '').toLowerCase()
  if (role.includes('admin')) return '管理员'
  if (role.includes('editor')) return '编辑'
  return user.value.role || '成员'
})

const layoutLabel = computed(() => (menuLayout.value === 'grid' ? '宫格' : '列表'))

/** 刷新认证态、主题与排版偏好 */
const refresh = () => {
  apply()
  loadMenuLayout()
  authed.value = isAuthenticated()
  user.value = getUser()
}
onShow(refresh)

/** 下拉刷新：同步本地登录态与主题 */
onPullDownRefresh(() => {
  refresh()
  uni.stopPullDownRefresh()
})

/** 进入独立主题页（避免 ActionSheet 被 Tabbar 遮挡） */
const goTheme = () => {
  uni.navigateTo({ url: '/subPackages/content/pages/theme/index' })
}

/** 在宫格 / 列表间切换并写入本地 */
const toggleMenuLayout = () => {
  menuLayout.value = menuLayout.value === 'grid' ? 'list' : 'grid'
  uni.setStorageSync(LAYOUT_KEY, menuLayout.value)
  toast.success(`已切换为${layoutLabel.value}`)
}

/** 跳转独立登录页（content 分包路径） */
const goLogin = () => {
  uni.navigateTo({ url: '/subPackages/content/pages/login/index' })
}

/** 打开合并账号确认（useDialog / wd-dialog），确认后进合并登录页 */
const openMergeConfirm = async () => {
  try {
    await dialog.confirm({
      title: '合并账号',
      msg: '合并后当前游客账号将注销（逻辑删除），微信将绑定到管理员账号。是否继续？',
    })
    uni.navigateTo({ url: '/subPackages/content/pages/login/index?mode=merge' })
  }
  catch {
    /* 用户取消 */
  }
}

const onLogout = () => {
  logout()
  enterUserMode()
}

const goProfile = () => {
  if (appMode.value !== 'admin') {
    toast.show('请先进入后台模式')
    return
  }
  uni.navigateTo({ url: '/subPackages/admin/pages/profile/index' })
}

const goAbout = () => {
  uni.navigateTo({ url: '/subPackages/content/pages/about/index' })
}
</script>

<template>
  <AppPageShell with-tab-pad>
    <AppNavbar title="我的" />
    <view class="page-pad">
      <ProfileHero
        :avatar-url="avatarUrl"
        :name="displayName"
        :subtitle="displaySubtitle"
        :badge="displayBadge"
      />

      <ArtMenuGroup eyebrow="Prefs" title="偏好设置" :layout="menuLayout">
        <ArtMenuItem
          title="主题"
          icon="settings"
          :value="themeLabel"
          is-link
          @click="goTheme"
        />
        <ArtMenuItem
          title="菜单排版"
          label="宫格更适合浏览，列表信息更全"
          icon="apps"
          :value="layoutLabel"
          is-link
          @click="toggleMenuLayout"
        />
      </ArtMenuGroup>

      <ArtMenuGroup eyebrow="Garden" title="探索" :layout="menuLayout">
        <ArtMenuItem
          title="关于"
          label="了解站点与作者"
          icon="user"
          is-link
          @click="goAbout"
        />
      </ArtMenuGroup>

      <ArtMenuGroup eyebrow="Account" title="账号" :layout="menuLayout">
        <ArtMenuItem
          v-if="!authed"
          title="登录"
          label="管理员账号密码登录"
          icon="lock"
          is-link
          @click="goLogin"
        />
        <ArtMenuItem
          v-if="authed && isGuestOrAnon"
          title="管理员登录"
          label="使用账号密码进入员工身份"
          icon="lock"
          is-link
          @click="goLogin"
        />
        <ArtMenuItem
          v-if="authed && isGuestOrAnon"
          title="合并账号"
          label="验证管理员密码，绑定微信并注销当前游客"
          icon="swap"
          is-link
          @click="openMergeConfirm"
        />
        <ArtMenuItem
          v-if="authed && !isGuestOrAnon"
          title="退出登录"
          label="清除本地会话"
          icon="poweroff"
          is-link
          @click="onLogout"
        />
      </ArtMenuGroup>

      <ArtMenuGroup
        v-if="canEnterAdmin || appMode === 'admin'"
        eyebrow="Staff"
        title="管理"
        :layout="menuLayout"
      >
        <ArtMenuItem
          v-if="canEnterAdmin && appMode === 'user'"
          title="进入后台"
          label="切换为管理端三栏"
          icon="home"
          is-link
          @click="enterAdminMode"
        />
        <ArtMenuItem
          v-if="appMode === 'admin'"
          title="返回用户端"
          label="切换回前台浏览"
          icon="arrow-left"
          is-link
          @click="enterUserMode"
        />
        <ArtMenuItem
          v-if="appMode === 'admin'"
          title="个人中心"
          icon="user"
          is-link
          @click="goProfile"
        />
        <ArtMenuItem
          v-if="authed"
          title="当前模式"
          :value="appMode === 'admin' ? '后台' : '前台'"
          icon="eye"
        />
      </ArtMenuGroup>
    </view>

    <!-- selector 与 useDialog('merge-account') 配对 -->
    <wd-dialog selector="merge-account" />
    <AppFloatingTabbar />
  </AppPageShell>
</template>
