<template>
  <div id="home-index" class="test-slide-wrapper">
    <SlideHorizontal v-model:index="state.baseIndex" name="first">
      <SlideItem class="sidebar">
        <div class="user-profile">
          <img class="avatar" :src="sidebarUser.avatar" alt="" />
          <span class="nickname">{{ sidebarUser.nickname }}</span>
        </div>

        <div class="menu-card">
          <div
            v-for="(item, index) in menuItems"
            :key="item.id"
            class="menu-item"
            :class="{ 'is-last': index === menuItems.length - 1 }"
            @click="onMenuClick(item)"
          >
            <span class="label">
              {{ item.label }}
              <Icon icon="icon-park-outline:right" class="arrow" />
            </span>
            <span v-if="item.badge" class="badge">{{ item.badge }}</span>
          </div>
        </div>
      </SlideItem>
      <SlideItem class="slide-main">
        <IndicatorHome
          v-if="!state.fullScreen"
          :loading="loading"
          name="second"
          @show-slidebar="state.baseIndex = 0"
          v-model:index="state.navIndex"
        />
        <SlideHorizontal
          v-model:index="state.navIndex"
          class="first-horizontal-item"
          name="second"
          :change-active-index-use-anim="false"
        >
          <Slide0 :active="state.navIndex === 0 && state.baseIndex === 1" />
          <Slide1 :active="state.navIndex === 1 && state.baseIndex === 1" />
        </SlideHorizontal>

        <BaseFooter :init-tab="1" />
        <BaseMask
          v-if="state.baseIndex === 0"
          mode="white"
          style="position: absolute"
          @click="state.baseIndex = 1"
        />
      </SlideItem>
      <SlideItem>
        <UserPanel
          :current-item="state.currentItem"
          @back="state.baseIndex = 1"
        />
      </SlideItem>
    </SlideHorizontal>

    <Comment
      page-id="home-index"
      :video-id="state.currentItem.aweme_id"
      v-model="state.commentVisible"
      @close="closeComments"
    />
  </div>
</template>

<script setup lang="ts">
import { Icon } from '@iconify/vue'
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import SlideHorizontal from '@/components/slide/SlideHorizontal.vue'
import SlideItem from '@/components/slide/SlideItem.vue'
import Comment from '@/components/Comment.vue'
import IndicatorHome from './components/IndicatorHome.vue'
import bus, { EVENT_KEY } from '@/utils/bus'
import { useNav } from '@/utils/hooks/useNav'
import UserPanel from '@/components/UserPanel.vue'
import Slide0 from './slide/Slide0.vue'
import Slide1 from './slide/Slide1.vue'
import { _no, _notice } from '@/utils'
import BaseMask from '@/components/BaseMask.vue'
import BaseFooter from '@/components/BaseFooter.vue'
import { miniPrograms, recentUsers, recommendVideos } from '@/mock/homeData'
import { useStore } from 'vuex'
import { SET_TOKEN } from '@/store/modules/app/type.js'
import { recommendVideos } from '@/mock/homeData'

const store = useStore()
const route = useRoute()
const nav = useNav()
const loading = ref(false)

type VideoItem = (typeof recommendVideos)[number]

const state = reactive({
  active: true,
  baseIndex: 1,
  navIndex: 1,
  commentVisible: false,
  fullScreen: false,
  currentItem: {
    ...recommendVideos[0],
    isRequest: false,
    aweme_list: [] as unknown[],
  } as VideoItem & { isRequest: boolean; aweme_list: unknown[] },
})

const sidebarUser = computed(() => {
  const author = recommendVideos[0]?.author
  return {
    nickname: author?.nickname || '周六周六周六',
    avatar:
      author?.avatar_168x168?.url_list?.[0] ||
      'https://p3-pc.douyinpic.com/img/aweme-avatar/tos-cn-avt-0015_99d3a4923c94e1e27b16209743eaec24~c5_168x168.jpeg?from=2956013662',
  }
})

type MenuItem = {
  id: string
  label: string
  badge?: number
  path?: string
}

const menuItems: MenuItem[] = [
  { id: 'msg', label: '互动消息', badge: 9 },
  { id: 'adopt', label: '我的认养', path: '/my-guard' },
  { id: 'like', label: '我的点赞' },
  { id: 'favorite', label: '我的收藏' },
]

function onMenuClick(item: MenuItem) {
  if (item.path) {
    nav(item.path)
    state.baseIndex = 1
    return
  }
  _no()
}

function setCurrentItem(val?: unknown) {
  const item = val as VideoItem
  if (!state.active) return
  if (state.baseIndex !== 1) return
  if (state.currentItem.author?.uid !== item.author?.uid) {
    state.currentItem = {
      ...item,
      isRequest: false,
      aweme_list: [],
    }
  }
}

/** 与 douyin 一致：仅主视频层显示底栏，侧边栏/UserPanel 隐藏 */
function syncFooterBySlide() {
  if (route.path !== '/') return
  bus.emit('setFooterVisible', state.baseIndex === 1)
}

watch(() => state.baseIndex, syncFooterBySlide)

function onEnterFullscreen() {
  if (!state.active) return
  state.fullScreen = true
}

function onExitFullscreen() {
  if (!state.active) return
  state.fullScreen = false
}

function onOpenComments() {
  if (!state.active) return
  bus.emit(EVENT_KEY.ENTER_FULLSCREEN)
  state.commentVisible = true
}

function onCloseComments() {
  if (!state.active) return
  bus.emit(EVENT_KEY.EXIT_FULLSCREEN)
  state.commentVisible = false
}

function onShowShare() {
  if (!state.active) return
  _notice('分享面板待接入')
}

function onNav(val?: unknown) {
  if (!state.active) return
  const { path, query } = val as { path: string; query?: Record<string, string> }
  nav(path, query || {})
}

function onGoUserinfo() {
  if (!state.active) return
  state.baseIndex = 2
}

onMounted(() => {
  syncFooterBySlide()
  bus.on(EVENT_KEY.ENTER_FULLSCREEN, onEnterFullscreen)
  bus.on(EVENT_KEY.EXIT_FULLSCREEN, onExitFullscreen)
  bus.on(EVENT_KEY.OPEN_COMMENTS, onOpenComments)
  bus.on(EVENT_KEY.CLOSE_COMMENTS, onCloseComments)
  bus.on(EVENT_KEY.SHOW_SHARE, onShowShare)
  bus.on(EVENT_KEY.NAV, onNav)
  bus.on(EVENT_KEY.GO_USERINFO, onGoUserinfo)
  bus.on(EVENT_KEY.CURRENT_ITEM, setCurrentItem)

  if (route.query.userId) {
    localStorage.setItem("MINI_USER_ID", route.query.userId as string)
    store.commit("home/SET_MINI_USER_ID", route.query.userId as string)
  }
  if (route.query.token) {
    localStorage.setItem("MINI_TOKEN", route.query.token as string)
    store.dispatch(`app/${SET_TOKEN}`, route.query.token as string)
  }
})

onUnmounted(() => {
  bus.off(EVENT_KEY.ENTER_FULLSCREEN, onEnterFullscreen)
  bus.off(EVENT_KEY.EXIT_FULLSCREEN, onExitFullscreen)
  bus.off(EVENT_KEY.OPEN_COMMENTS, onOpenComments)
  bus.off(EVENT_KEY.CLOSE_COMMENTS, onCloseComments)
  bus.off(EVENT_KEY.SHOW_SHARE, onShowShare)
  bus.off(EVENT_KEY.NAV, onNav)
  bus.off(EVENT_KEY.GO_USERINFO, onGoUserinfo)
  bus.off(EVENT_KEY.CURRENT_ITEM, setCurrentItem)
})

function closeComments() {
  bus.emit(EVENT_KEY.CLOSE_COMMENTS)
}
</script>

<style scoped lang="less">
.test-slide-wrapper {
  font-size: 14rem;
  width: 100%;
  height: 100%;
  background: black;
  overflow: hidden;

  .sidebar {
    touch-action: pan-y;
    width: 80%;
    height: calc(var(--vh, 1vh) * 100);
    overflow: auto;
    background: #ececec;
    padding: 30rem 20rem;
    box-sizing: border-box;

    .user-profile {
      display: flex;
      align-items: center;
      gap: 10rem;

      .avatar {
        width: 46rem;
        height: 46rem;
        border-radius: 50%;
      }

      .nickname {
        font-size: 16rem;
        font-weight: 500;
      }
    }

    .menu-card {
      background: #fff;
      border-radius: 8rem;
      margin-top: 18rem;

      .menu-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 15rem 10rem;
        border-bottom: .5px solid rgba(0, 0, 0, 0.1);
        cursor: pointer;

        &.is-last {
          border-bottom: none;
        }

        .label {
          display: inline-flex;
          align-items: center;
          gap: 2rem;
          font-size: 16rem;

          .arrow {
            font-size: 14rem;
          }
        }

        .badge {
          width: 20rem;
          height: 20rem;
          border-radius: 50%;
          background: #FFA617;
          color: #fff;
          font-size: 12rem;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }
}

.slide-main {
  height: calc(var(--vh, 1vh) * 100);
  overflow: hidden;
}

.first-horizontal-item {
  width: 100%;
  height: 100% !important;
  overflow: hidden;
}
</style>
