<template>
  <v-app>
    <v-app-bar
      app
      class="app-bar-transition"
      :class="{ 'app-bar-pill': !drawer, 'app-bar-rect': drawer }"
      color="primary"
      elevation="4"
      :rounded="drawer ? 'none' : 'pill'"
    >
      <v-app-bar-nav-icon @click="drawer = !drawer" />
      <v-app-bar-title class="text-h6">
        <template v-if="menuItems.length > 0 && menuItems[selectedIndex]">
          {{ menuItems[selectedIndex].title || $t('appTitle') }}
        </template>
      </v-app-bar-title>

      <v-spacer />

      <v-menu
        v-model="languageMenu"
        :close-on-content-click="true"
        location="bottom end"
        offset="8"
      >
        <template #activator="{ props }">
          <v-btn
            v-bind="props"
            :icon="$vuetify.display.xs"
            :prepend-icon="$vuetify.display.xs ? undefined : 'mdi-translate'"
            :size="$vuetify.display.xs ? 'default' : 'large'"
            variant="text"
          >
            <v-icon v-if="$vuetify.display.xs">mdi-translate</v-icon>
            <span v-else class="text-button">{{ currentLanguage.label }}</span>
          </v-btn>
        </template>

        <!-- <v-list
          class="language-menu"
          density="compact"
          min-width="160"
        >
          <v-list-item
            v-for="lang in availableLanguages"
            :key="lang.code"
            :activate="locale === lang.code"
            :title="lang.label"
            @click="changeLanguage(lang.code)"
          >
            <template #append>
              <v-icon
                v-if="locale === lang.code"
                class="text-primary"
                icon="mdi-check"
              />
            </template>
          </v-list-item>
        </v-list> -->
        <div class="language-pill-container">
          <v-chip-group
            v-model="selectedLanguageIndex"
            direction="vertical"
            selected-class="text-primary"
            @update:model-value="handleLanguageChange"
          >
            <v-chip
              v-for="(lang, index) in availableLanguages"
              :key="lang.code"
              class="language-pill-large"
              :color="locale === lang.code ? 'primary' : undefined"
              label
              rounded="xl"
              size="large"
              :value="index"
              :variant="locale === lang.code ? 'flat' : 'outlined'"
            >
              <v-icon
                v-if="locale === lang.code"
                class="mr-2"
                icon="mdi-check"
                size="small"
              />
              {{ lang.label }}
            </v-chip>
          </v-chip-group>
        </div>

      </v-menu>
    </v-app-bar>

    <v-navigation-drawer
      v-model="drawer"
      app
      class="drawer-transition"
      :width="drawerWidth"
    >

      <div class="fill-height d-flex flex-column">
        <v-list-item class="pa-4">
          <v-list-item-title class="text-h6 text-primary">
            {{ $t('calculator') }}
          </v-list-item-title>
          <v-list-item-subtitle>
            {{ $t('appTitle') }}
          </v-list-item-subtitle>
        </v-list-item>

        <v-divider />

        <v-list class="flex-grow-1" density="compact">
          <v-list-item
            v-for="(item, index) in menuItems"
            :key="index"
            :active="selectedIndex === index"
            class="ma-1"
            :color="selectedIndex === index ? 'primary' : undefined"
            rounded="lg"
            :to="item.to"
            @click="handleSelect(index)"
          >
            <v-list-item-title class="text-body-2">
              {{ item.title }}
            </v-list-item-title>
          </v-list-item>
        </v-list>

        <v-divider />

        <div class="pa3">
          <v-btn
            block
            class="mb-2"
            prepend-icon="mdi-information-outline"
            variant="text"
            @click="showAboutDialog = true"
          >
            {{ $t('about') }}
          </v-btn>
        </div>

      </div>

    </v-navigation-drawer>

    <v-dialog
      v-model="showAboutDialog"
      max-width="500px"
    >
      <v-card
        class="mx-auto"
        prepend-icon="mdi-information-outline"
      >
        <template #title>
          <v-card-title class="text-h5">
            {{ appInfo.appName }}
          </v-card-title>
        </template>

        <template #subtitle>
          <div class="text-caption text-secondary">
            {{ appInfo.version }}
            {{ appInfo.copyright }}
          </div>
        </template>

        <template #text>
          <v-card-text>
            <div>
              {{ appInfo.description }}
            </div>
          </v-card-text>

          <div class="mb-3">
            {{ $t('officialWebsite') }}:
            <v-btn
              color="primary"
              :href="appInfo.officialWebsite"
              prepend-icon="mdi-web"
              rel="noopener noreferrer"
              size="small"
              target="_blank"
              variant="text"
            >
              {{ appInfo.officialWebsite }}
            </v-btn>
          </div></template>

        <v-card-actions>
          <v-spacer />
          <v-btn
            color="primary"
            variant="text"
            @click="showAboutDialog = false"
          >
            {{ $t('close') }}
          </v-btn>
        </v-card-actions>

      </v-card></v-dialog>

    <v-main>
      <v-container
        class="pa-6"
        fluid
      />
      <router-view v-slot="{ Component }">
        <v-fade-transition hide-on-leave>
          <component :is="Component" />
        </v-fade-transition>
      </router-view>
    </v-main>
  </v-app>

</template>

<script lang="ts" setup>
  import { computed, onMounted, onUnmounted, ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { navigationConfig } from '@/config/navigation'
  import { useNavigationStore } from '@/stores/navigation'

  const { t, locale } = useI18n()

  const navigationStore = useNavigationStore()

  const drawer = computed({
    get: () => navigationStore.drawer,
    set: (value: boolean) => {
      navigationStore.setDrawerOpen(value)
    },
  })
  const selectedIndex = computed(() => navigationStore.selectedIndex)

  const windowWidth = ref(typeof window === 'undefined' ? 1200 : window.innerWidth)

  const showAboutDialog = ref(false)
  const languageMenu = ref(false)

  // 应用信息
  const appInfo = computed(() => {
    return {
      appName: t('appTitle'),
      version: '1.0.0',
      author: t('companyName'),
      description: t('appDescription'),
      copyright: `© ${new Date().getFullYear()} ${t('companyName')}. ${t('allRightsReserved')}`,
      officialWebsite: 'http://www.jinshen.cn',
    }
  })

  // 动态设置网页标题
  const pageTitle = computed(() => {
    return t('appTitle')
  })

  // 监听窗口变化
  const handleResize = () => {
    if (typeof window === 'undefined') return
    windowWidth.value = window.innerWidth
  }

  onMounted(() => {
    if (typeof window === 'undefined') return
    window.addEventListener('resize', handleResize)
  })

  onUnmounted(() => {
    if (typeof window === 'undefined') return
    window.removeEventListener('resize', handleResize)
  })

  const drawerWidth = computed(() => {
    const isZh = locale.value === 'zh'

    // 计算菜单项中最长标题的长度
    const maxTitleLength = menuItems.value.reduce((max, item) => {
      return Math.max(max, item.title.length)
    }, 0)

    const isMobile = windowWidth.value < 600
    const isTablet = windowWidth.value < 960

    // 根据屏幕宽度和标题长度计算抽屉宽度
    let calculatedWidth: number

    if (isMobile) {
      // 移动设备：更紧凑的布局
      calculatedWidth = isZh ? maxTitleLength * 12 + 60 : maxTitleLength * 6 + 60
    } else if (isTablet) {
      // 平板设备：中等布局
      calculatedWidth = isZh ? maxTitleLength * 13 + 70 : maxTitleLength * 6.5 + 70
    } else {
      // 桌面设备：宽松布局
      calculatedWidth = isZh ? maxTitleLength * 15 + 80 : maxTitleLength * 7 + 80
    }

    const minWidth = isMobile ? 240 : (isTablet ? 280 : 300)
    const maxWidth = isMobile ? 360 : (isTablet ? 400 : 500)

    const finalWidth = Math.max(minWidth, Math.min(calculatedWidth, maxWidth))

    // 开发环境调试信息
    if (import.meta.env.DEV) {
      console.debug('Navigation drawer width calculation:', {
        locale: locale.value,
        maxTitleLength,
        calculatedWidth,
        finalWidth,
        windowWidth: windowWidth.value,
        device: isMobile ? 'mobile' : (isTablet ? 'tablet' : 'desktop'),
      })
    }

    return finalWidth
  })

  const menuItems = computed(() => {
    return navigationConfig.map((item, _) => {
      return {
        title: t(item.title),
        to: item.to,
      }
    })
  })

  const availableLanguages = [
    {
      code: 'zh',
      label: '中文（简体）',
    },
    {
      code: 'en',
      label: 'English',
    },
    {
      code: 'ru',
      label: 'Русский(Experimental)',
    },
    {
      code: 'sp',
      label: 'Español(Experimental)',
    },
  ]
  const currentLanguage = computed(() => {
    return availableLanguages.find(lang => lang.code === locale.value) || availableLanguages[0]
  })

  const selectedLanguageIndex = computed(() => {
    return availableLanguages.findIndex(lang => lang.code === locale.value)
  })

  function handleLanguageChange (index: number) {
    if (index !== undefined && index >= 0 && index < availableLanguages.length) {
      locale.value = availableLanguages[index].code
    }
  }

  function handleSelect (_index: number) {
    drawer.value = false // 选择后自动关闭抽屉
  }

  onMounted(() => {
    document.title = pageTitle.value
  })

  watch(locale, () => {
    document.title = pageTitle.value
  })
</script>

<style scoped>
/* AppBar响应式样式 */
@media (max-width: 599px) {
  .v-app-bar-title {
    font-size: 0.875rem !important;
    line-height: 1.2 !important;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: calc(100vw - 120px); /* 为导航按钮和语言按钮留出空间 */
  }
}

@media (min-width: 600px) and (max-width: 959px) {
  .v-app-bar-title {
    font-size: 1rem !important;
    line-height: 1.3 !important;
  }
}

/* 导航抽屉响应式样式 */
@media (max-width: 599px) {
  .v-list-item-title {
    font-size: 0.75rem !important;
    line-height: 1.2 !important;
  }

  .v-list-item-subtitle {
    font-size: 0.625rem !important;
    line-height: 1.2 !important;
  }

  .v-list-item {
    min-height: 36px !important;
  }

  /* 确保文本不会溢出 */
  .v-list-item-title,
  .v-list-item-subtitle {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

@media (min-width: 600px) and (max-width: 959px) {
  .v-list-item-title {
    font-size: 0.875rem !important;
  }

  .v-list-item-subtitle {
    font-size: 0.75rem !important;
  }

  .v-app-bar-title {
    font-size: 1rem !important;
  }
}

/* 关于对话框响应式样式 */
@media (max-width: 599px) {
  .v-dialog .v-card-title {
    font-size: 1rem !important;
  }

  .v-dialog .v-card-text {
    font-size: 0.875rem !important;
  }

  .v-dialog .text-caption {
    font-size: 0.75rem !important;
  }
}

/* 移动设备上的特殊处理 */
@media (max-width: 599px) {
  .v-list-item.pa-4 {
    padding: 12px 16px !important;
  }

  .v-list-item.ma-1 {
    margin: 2px 4px !important;
  }
}

/* 无背景的语言选择器容器 */
.language-pill-container {
  padding: 8px;
  min-width: 180px;
  max-width: 320px;
}

/* 大尺寸语言药丸样式 */
.language-pill-large {
  margin: 4px 0;
  padding: 12px 20px;
  height: 48px;
  font-size: 1rem;
  font-weight: 500;
  transition: all 0.3s ease;
  border-radius: 24px;
  width: 100%;

  /* 文本居中 */
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
}

.language-pill-large:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* chip内容居中对齐 */
.language-pill-large .v-chip__content {
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  width: 100% !important;
  font-weight: 500;
}

/* 响应式药丸样式 */
@media (max-width: 599px) {
  .language-pill-container {
    min-width: 160px;
    max-width: 280px;
    padding: 6px;
  }

  .language-pill-large {
    margin: 2px 0;
    padding: 8px 16px;
    height: 40px;
    font-size: 0.875rem;
  }

  .text-button {
    font-size: 0.75rem !important;
  }
}

@media (min-width: 600px) and (max-width: 959px) {
  .language-pill-large {
    padding: 10px 18px;
    height: 44px;
    font-size: 0.9375rem;
  }
}

/* 药丸选中状态 */
.v-chip--variant-flat {
  background: rgb(var(--v-theme-primary)) !important;
  color: rgb(var(--v-theme-surface)) !important;
  box-shadow: 0 2px 8px rgba(var(--v-theme-primary), 0.1);
}

/* 药丸未选中状态 */
.v-chip--variant-outlined {
  border: 1px solid rgba(var(--v-theme-info), 0.3);
  color: rgb(var(--v-theme-info));
  background: rgba(var(--v-theme-surface), 1);
}

.v-chip--variant-outlined:hover {
  background: rgba(var(--v-theme-info), 0.08);
  border-color: rgba(var(--v-theme-info), 0.5);
}

/* 选中状态的图标 */
.language-pill-large .v-icon {
  opacity: 1;
}

/* 字体权重调整 */
.language-pill-large .v-chip__content {
  font-weight: 500;
}

.language-pill {
  margin: 2px 4px;
  transition: all 0.2s ease;
}

.language-pill:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 响应式药丸样式 */
@media (max-width: 599px) {
  .language-pill-menu {
    min-width: 160px;
    max-width: 250px;
  }

  .language-pill {
    margin: 1px 2px;
  }

  .text-button {
    font-size: 0.75rem !important;
  }
}
</style>
