<script setup lang="ts">
import { onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useTaskStore } from '@/stores/useTaskStore'
import { useCategoryStore } from '@/stores/useCategoryStore'
import { useTagStore } from '@/stores/useTagStore'
import { useUIStore } from '@/stores/useUIStore'
import { useUserSettingsStore } from '@/stores/useUserSettingsStore'
import { useAuthStore } from '@/stores/useAuthStore'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import AppHeader from '@/components/AppHeader.vue'
import TaskDialog from '@/components/TaskDialog.vue'
import CategoryDialog from '@/components/CategoryDialog.vue'

const route = useRoute()
const router = useRouter()
const taskStore = useTaskStore()
const categoryStore = useCategoryStore()
const tagStore = useTagStore()
const uiStore = useUIStore()
const userSettingsStore = useUserSettingsStore()
const authStore = useAuthStore()

// 路由变化时同步 currentView
watch(() => route.meta.view, (view) => {
  if (view) {
    uiStore.setCurrentView(view as 'list' | 'calendar' | 'quadrant' | 'profile' | 'settings' | 'habits' | 'anniversaries' | 'assets')
  }
}, { immediate: true })

// 网站名称变化时更新页面标题
watch(() => userSettingsStore.siteName, (name) => {
  const page = (route.meta.title as string) || ''
  document.title = page ? `${page} - ${name}` : name
})

onMounted(async () => {
  if (!authStore.isLoggedIn) return

  await userSettingsStore.fetchAndSync()

  // 根据用户设置初始化默认排序
  taskStore.setFilters({
    sort_by: userSettingsStore.defaultSortBy as 'priority' | 'due_date' | 'created_at',
    sort_order: userSettingsStore.defaultSortOrder as 'asc' | 'desc'
  })

  // 首次访问根路径时根据设置跳转到默认视图
  if (route.path === '/') {
    const viewMap: Record<string, string> = {
      list: '/tasks',
      calendar: '/calendar',
      quadrant: '/quadrant'
    }
    const target = viewMap[userSettingsStore.defaultView] || '/tasks'
    router.replace(target)
  }

  await Promise.all([
    taskStore.fetchTasks(),
    categoryStore.fetchCategories(),
    tagStore.fetchTags()
  ])
})
</script>

<template>
  <el-config-provider :locale="zhCn">
  <div class="app-container">
    <template v-if="route.name !== 'login'">
      <div class="decoration-star" style="top: 20%; right: 8%; animation-delay: 0.5s;"></div>
      <div class="decoration-star" style="top: 60%; left: 3%; animation-delay: 1s;"></div>
      <div class="decoration-star" style="top: 80%; right: 5%; animation-delay: 1.5s;"></div>

      <AppHeader />

      <div class="app-main">
        <main
          class="main-content"
          :class="{
            'full-width': uiStore.currentView !== 'list'
          }"
        >
          <router-view v-slot="{ Component }">
            <Transition name="view-fade" mode="out-in">
              <component :is="Component" />
            </Transition>
          </router-view>
        </main>
      </div>

      <div v-if="uiStore.currentView !== 'settings' && uiStore.currentView !== 'profile' && uiStore.currentView !== 'habits' && uiStore.currentView !== 'anniversaries' && uiStore.currentView !== 'assets'" class="fab-container">
        <el-button
          type="primary"
          circle
          size="large"
          class="add-btn btn-glow"
          @click="uiStore.openTaskDialog()"
        >
          <el-icon :size="24"><Plus /></el-icon>
        </el-button>
      </div>

      <TaskDialog />
      <CategoryDialog />
    </template>
    <router-view v-else v-slot="{ Component }">
      <component :is="Component" />
    </router-view>
  </div>
  </el-config-provider>
</template>

<style scoped lang="scss">
.app-container {
  min-height: 100vh;
  position: relative;
}

.app-main {
  margin-top: 60px;
  min-height: calc(100vh - 60px);
}

.main-content {
  padding: 0;

  &.full-width {
    padding: 0;
  }
}

.fab-container {
  position: fixed;
  bottom: 32px;
  right: 32px;
  z-index: 100;

  .add-btn {
    width: 60px;
    height: 60px;
    background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%);
    border: none;
    box-shadow: var(--shadow-lg);

    &:hover {
      transform: scale(1.1);
    }
  }
}

.view-fade-enter-active,
.view-fade-leave-active {
  transition: opacity 0.2s ease, transform 0.2s ease;
}

.view-fade-enter-from {
  opacity: 0;
  transform: translateY(10px);
}

.view-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>
