<template>
  <div class="side-nav">
    <!-- 顶部 Logo -->
    <div class="side-nav__header">

      <!-- 侧边栏Logo图片 -->
      <img src="@/assets/images/logo.png" alt="Offer派" class="side-nav__logo-img" />
    </div>

    <!-- 主导航 -->
    <nav class="side-nav__menu">
      <a
        v-for="item in mainMenus"
        :key="item.name"
        href="javascript:void(0)"
        class="side-nav__item"
        :class="{ 'side-nav__item--active': isActive(item.name) }"
        @click="handleNav(item)"
      >
        <img class="side-nav__item-icon" :src="item.iconImg" :alt="item.label" />
        <span class="side-nav__item-label">{{ item.label }}</span>
        <span v-if="item.badge" class="side-nav__badge">{{ item.badge }}</span>
      </a>
    </nav>

    <!-- 底部菜单 -->
    <div class="side-nav__footer">
      <div class="side-nav__item" v-for="item in footerMenus" :key="item.label" @click="item.action?.()">
        <img class="side-nav__item-icon" :src="item.iconImg" :alt="item.label" />
        <span class="side-nav__item-label">{{ item.label }}</span>
        <span v-if="item.badge" class="side-nav__badge">{{ item.badge }}</span>
      </div>
    </div>

    <!-- 消息通知弹窗 -->
    <Teleport to="body">
      <div v-if="showMessageDialog" class="side-nav__dialog-overlay" @click="showMessageDialog = false">
        <div class="side-nav__dialog" @click.stop>
          <div class="side-nav__dialog-header">
            <span>消息通知</span>
            <span class="side-nav__dialog-close" @click="showMessageDialog = false">✕</span>
          </div>
          <div class="side-nav__dialog-body">
            <p>暂无新消息</p>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- 反馈弹窗 -->
    <Teleport to="body">
      <div v-if="showFeedbackDialog" class="side-nav__dialog-overlay" @click="showFeedbackDialog = false">
        <div class="side-nav__dialog feedback-dialog" @click.stop>
          <div class="feedback-dialog__title">反馈与帮助</div>

          <div class="feedback-dialog__section">
            <div class="feedback-dialog__label">*你想向我们反馈什么问题？</div>
            <div class="feedback-dialog__options">
              <div
                v-for="opt in feedbackOptions"
                :key="opt"
                class="feedback-dialog__option"
                :class="{ 'feedback-dialog__option--active': feedbackType === opt }"
                @click="feedbackType = opt"
              >
                {{ opt }}
              </div>
            </div>
          </div>

          <div class="feedback-dialog__section">
            <div class="feedback-dialog__label">*能否提供更多细节？</div>
            <textarea
              v-model="feedbackDetail"
              class="feedback-dialog__textarea"
              placeholder="请描述你的使用体验或分享您的想法。描述越具体，我们越能更好地处理您的反馈。"
              rows="5"
            ></textarea>
          </div>

          <div class="feedback-dialog__actions">
            <button class="feedback-dialog__btn feedback-dialog__btn--cancel" @click="showFeedbackDialog = false">取消</button>
            <button class="feedback-dialog__btn feedback-dialog__btn--submit" @click="handleFeedbackSubmit">确认提交</button>
          </div>
        </div>
      </div>
    </Teleport>
    <!-- 设置弹窗 -->
    <SettingsDialog v-model="showSettingsDialog" />
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import SettingsDialog from '@/components/SettingsDialog.vue'
import { checkLogin } from '@/api/auth'
import navJobsIcon from '@/assets/images/nav/nav-jobs-icon.png'
import navResumeIcon from '@/assets/images/nav/nav-resume-icon.png'
import navProfileIcon from '@/assets/images/nav/nav-profile-icon.png'
import navAgentIcon from '@/assets/images/nav/nav-agent-icon.png'
import navMessageIcon from '@/assets/images/nav/nav-message-icon.png'
import navSettingIcon from '@/assets/images/nav/nav-setting-icon.png'
import navFeedbackIcon from '@/assets/images/nav/nav-feedback-icon.png'

const route = useRoute()
const router = useRouter()
const store = useStore()

interface MenuItem {
  name: string
  path: string
  iconImg: string
  label: string
  badge?: string
}

/**
 * 图标映射表
 * 后端 meta.icon 返回的是字符串 key，这里映射到实际的图片资源
 * 【新增图标时】在这里加一条即可
 */
const iconMap: Record<string, string> = {
  'nav-jobs-icon':    navJobsIcon,
  'nav-resume-icon':  navResumeIcon,
  'nav-profile-icon': navProfileIcon,
  'nav-agent-icon':   navAgentIcon,
  'nav-setting-icon': navSettingIcon,
}

/**
 * 静态菜单 — 不需要登录就能看到的导航项（比如"职位"）
 * 这些菜单始终显示，不依赖后端返回
 */
const staticMenus: MenuItem[] = [
  { name: 'Jobs', path: '/jobs', iconImg: navJobsIcon, label: '职位' },
]

/**
 * 动态菜单 — 从 store.state.dynamicMenus（后端返回的数据）转换而来
 * 登录后才会有数据，登出后自动清空
 * 过滤掉 position === 'footer' 的项（如"设置"），它们显示在底部区域
 */
const dynamicMenuItems = computed<MenuItem[]>(() => {
  return store.state.dynamicMenus
    .filter((item: any) => item.meta?.position !== 'footer')
    .map((item: any) => ({
      name: item.name,
      path: item.path,
      iconImg: iconMap[item.meta?.icon] || '',
      label: item.meta?.label || item.name,
      badge: item.meta?.badge,
    }))
})

/**
 * 最终渲染的主菜单 = 静态菜单 + 动态菜单
 */
const mainMenus = computed<MenuItem[]>(() => {
  return [...staticMenus, ...dynamicMenuItems.value]
})

const showMessageDialog = ref(false)
const showFeedbackDialog = ref(false)
const showSettingsDialog = ref(false)
const feedbackType = ref('')
const feedbackDetail = ref('')

const feedbackOptions = ['Bug反馈', '功能建议', '使用体验', '订阅及会员权益相关问题', '其它']

function handleFeedbackSubmit() {
  // TODO: 调用反馈提交接口
  console.log('反馈类型:', feedbackType.value, '详情:', feedbackDetail.value)
  feedbackType.value = ''
  feedbackDetail.value = ''
  showFeedbackDialog.value = false
}

/**
 * 底部"设置"按钮 — 从动态菜单中取 position === 'footer' 的项
 * 未登录时使用默认图标和文字
 */
const settingsMenu = computed(() => {
  const item = store.state.dynamicMenus.find((m: any) => m.meta?.position === 'footer')
  if (item) {
    return {
      iconImg: iconMap[item.meta?.icon] || navSettingIcon,
      label: item.meta?.label || '设置',
      path: item.path,
    }
  }
  return { iconImg: navSettingIcon, label: '设置', path: '/settings' }
})

const footerMenus = computed(() => [
  { iconImg: navMessageIcon, label: '消息通知', badge: 'NEW', action: () => { showMessageDialog.value = true } },
  { iconImg: settingsMenu.value.iconImg, label: settingsMenu.value.label, action: () => { handleSettingsNav() } },
  { iconImg: navFeedbackIcon, label: '反馈', action: () => { showFeedbackDialog.value = true } },
])

/**
 * 设置弹窗：需要登录，通过 checkLogin 接口验证
 */
async function handleSettingsNav() {
  try {
    const res = await checkLogin()
    if (res.code === '0' && res.data === true) {
      store.commit('SET_AUTHENTICATED', true)
      showSettingsDialog.value = true
    } else {
      store.commit('SET_AUTHENTICATED', false)
      store.dispatch('openLogin')
    }
  } catch {
    store.commit('SET_AUTHENTICATED', false)
    store.dispatch('openLogin')
  }
}

/**
 * 导航点击处理：
 * - 静态页面（Jobs）直接跳转
 * - 动态页面通过 checkLogin 接口验证，未登录则弹登录框
 */
const staticNames = staticMenus.map(m => m.name)

async function handleNav(item: MenuItem) {
  if (staticNames.includes(item.name)) {
    router.push(item.path)
    return
  }
  try {
    const res = await checkLogin()
    if (res.code === '0' && res.data === true) {
      store.commit('SET_AUTHENTICATED', true)
      router.push(item.path)
    } else {
      store.commit('SET_AUTHENTICATED', false)
      store.dispatch('openLogin', item.path)
    }
  } catch {
    store.commit('SET_AUTHENTICATED', false)
    store.dispatch('openLogin', item.path)
  }
}

function isActive(name: string) {
  return route.name === name
}
</script>
