<template>
  <div class="header-view">
    <div class="page-header-view">
      <div class="header">
        <div class="left">
          <div class="logo" @click="goHome">
            <img src="@/assets/images/common/logo.svg" alt="Vitiens" class="logo-icon" />
            <img src="@/assets/images/common/Vitiens.svg" alt="Vitiens" class="logo-text" />
          </div>
        </div>
        <div class="header-right">
          <lang-popover ref="langPopoverRef" />

          <!-- 主题切换按钮 -->
          <div class="theme-toggle-container" @click.stop="onToggleThemePopover">
            <div class="theme-toggle-btn">
              <!-- 暗黑主题：月牙 -->
              <svg v-if="currentTheme === 'dark'" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="theme-icon">
                <path d="M12 3a9 9 0 1 0 9 9c0-.46-.04-.92-.1-1.36a5.389 5.389 0 0 1-4.4 2.26 5.403 5.403 0 0 1-3.14-9.8c-.44-.06-.9-.1-1.36-.1z" fill="currentColor"/>
              </svg>
              <!-- 蓝白/浅色主题：太阳 -->
              <svg v-else viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="theme-icon">
                <circle cx="12" cy="12" r="5" fill="currentColor"/>
                <line x1="12" y1="1" x2="12" y2="3" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                <line x1="12" y1="21" x2="12" y2="23" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                <line x1="4.22" y1="4.22" x2="5.64" y2="5.64" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                <line x1="18.36" y1="18.36" x2="19.78" y2="19.78" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                <line x1="1" y1="12" x2="3" y2="12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                <line x1="21" y1="12" x2="23" y2="12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                <line x1="4.22" y1="19.78" x2="5.64" y2="18.36" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                <line x1="18.36" y1="5.64" x2="19.78" y2="4.22" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
              </svg>
            </div>
            <!-- 主题选择下拉 -->
            <div v-if="isThemePopoverOpen" class="theme-popover">
              <div class="theme-popover-title">{{ $t('theme.title') || '外观设置' }}</div>
              <div
                v-for="item in themeList"
                :key="item.key"
                class="theme-option"
                :class="{ selected: currentTheme === item.key }"
                @click.stop="onSelectTheme(item.key)"
              >
                <div class="theme-dot" :class="'dot-' + item.key"></div>
                <span>{{ $t(item.labelKey) }}</span>
                <span v-if="currentTheme === item.key" class="check-mark">&#10003;</span>
              </div>
            </div>
          </div>

          <div class="avatar-dropdown-container" @click="onToggleAvatarDropdown">
            <img :src="avatarSrc" class="icon icon-avatar" />
            <img src="@/assets/images/common/icon_down.svg" class="icon icon-down" />
            <div v-if="isAvatarDropdownOpen" class="dropdown-container">
              <!-- 用户信息区 -->
              <div class="user-profile-section">
                <img :src="avatarSrc" class="profile-avatar" />
                <div class="profile-info">
                  <div class="profile-name">{{ userInfo?.nickname || userInfo?.username || 'User' }}</div>
                  <div class="profile-uid" @click="onCopy">
                    <span>ID: {{ userInfo?.uid }}</span>
                    <img src="@/assets/images/common/copy-icon.svg" class="copy-icon" />
                  </div>
                </div>
              </div>

              <!-- 余额显示 -->
              <div class="balance-section">
                <div class="balance-label">{{ $t('finance.balance') }}</div>
                <div class="balance-value">{{ userInfo?.balance ?? '0.00' }}</div>
              </div>

              <!-- 基本信息 -->
              <div class="info-section">
                <div class="info-item">
                  <span class="info-label">{{ $t('user.region') }}</span>
                  <span class="info-value">{{ userInfo?.region || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">{{ $t('user.age') }}</span>
                  <span class="info-value">{{ userInfo?.age || '--' }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">{{ $t('user.gender') }}</span>
                  <span class="info-value">{{ genderText }}</span>
                </div>
              </div>

              <!-- 退出登录 -->
              <div class="logout-wrapper" @click="onLogout">
                <img src="@/assets/images/common/exit.svg" />
                <span>{{ $t("auth.logout") }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import LangPopover from "@/components/LangPopover/index.vue";
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { copyText } from "@/utils/utils";
import { useGlobalStore } from "@/store/modules/globalStore";
import { useThemeStore } from "@/store/modules/themeStore";
import type { ThemeType } from "@/store/modules/themeStore";
import { requestGetUserInfo } from "@/api";
import defaultAvatar from "@/assets/images/common/logo.svg";

const { t } = useI18n();
const router = useRouter();
const userInfo = ref<UserInfo>();
const avatarSrc = computed(() => userInfo.value?.avatar || defaultAvatar);

// 主题相关
const themeStore = useThemeStore();
const currentTheme = computed(() => themeStore.currentTheme);
const themeList = themeStore.themeList;
const isThemePopoverOpen = ref(false);

const onToggleThemePopover = () => {
  isThemePopoverOpen.value = !isThemePopoverOpen.value;
  // 关闭其他弹出
  isAvatarDropdownOpen.value = false;
  langPopoverRef.value?.close();
};

const onSelectTheme = (theme: ThemeType) => {
  themeStore.setTheme(theme);
  isThemePopoverOpen.value = false;
};

const genderText = computed(() => {
  const g = userInfo.value?.gender;
  if (g === 1) return t('user.male');
  if (g === 2) return t('user.female');
  return '--';
});

const isAvatarDropdownOpen = ref(false);
const langPopoverRef = ref<typeof LangPopover>(null);
// 头像下拉框相关方法
const onToggleAvatarDropdown = () => {
  isAvatarDropdownOpen.value = !isAvatarDropdownOpen.value;
  isThemePopoverOpen.value = false;
  langPopoverRef.value?.close();
};

const onCopy = async () => copyText(userInfo.value?.uid);

const onLogout = () => {
  isAvatarDropdownOpen.value = false;
  localStorage.removeItem("token");
  router.replace("/home");
  window.location.reload();
};

const goHome = () => {
  router.push('/');
};

// 点击外部区域关闭下拉框
const handleClickOutside = (event: Event) => {
  const target = event.target as HTMLElement;
  if (!target.closest(".avatar-dropdown-container")) {
    isAvatarDropdownOpen.value = false;
  }
  if (!target.closest(".theme-toggle-container")) {
    isThemePopoverOpen.value = false;
  }
};

const getUserInfo = async () => {
  const res = await requestGetUserInfo();
  userInfo.value = res.data.user || res.data;
};
const globalStore = useGlobalStore();
const isLoggedIn = computed(() => globalStore.isLoggedIn);
watch(
  () => isLoggedIn.value,
  newVal => {
    if (newVal) {
      getUserInfo();
    }
  }
);
onMounted(() => {
  if (isLoggedIn.value) {
    getUserInfo();
  }
});

onMounted(() => {
  document.addEventListener("click", handleClickOutside);
});

onUnmounted(() => {
  document.removeEventListener("click", handleClickOutside);
});
</script>
<style lang="scss" scoped>
.header-view {
  max-width: 500px;
  margin: 0 auto;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 50;
  background: var(--bg-header, #161617);
  box-shadow: var(--shadow-header, none);
  height: min(11.2vw, 53.76px);
}
.page-header-view {
  height: 100%;

  .header {
    height: 100%;
    padding: 0 min(4.267vw, 20.48px);

    display: flex;
    align-items: center;
    justify-content: space-between;

    .left {
      display: flex;
      align-items: center;
      height: 100%;

      .logo {
        display: flex;
        align-items: center;
        font-weight: 700;
        font-size: min(6.24vw, 29.9px);
        letter-spacing: 0.5px;
        cursor: pointer;

        .logo-icon {
          width: min(7vw, 32px);
          height: min(7vw, 32px);
          margin-right: min(1.5vw, 6px);
        }

        .logo-text {
          height: min(5vw, 24px);
        }
      }
    }

    .header-right {
      display: flex;
      align-items: center;
      height: 100%;
      gap: 4px;
    }

    .icon-avatar {
      margin-left: 7px;
      width: min(8vw, 38.4px);
      height: min(8vw, 38.4px);
      border-radius: 50%;
      object-fit: cover;
    }

    .icon-down {
      margin-left: 7px;
    }
  }

  // ======== 主题切换按钮 ========
  .theme-toggle-container {
    position: relative;
    display: flex;
    align-items: center;

    .theme-toggle-btn {
      width: min(8vw, 34px);
      height: min(8vw, 34px);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      background: var(--bg-theme-toggle, #2a2a2c);
      transition: transform 0.2s ease, background 0.3s ease;

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

      .theme-icon {
        width: min(4.5vw, 18px);
        height: min(4.5vw, 18px);
        color: var(--color-theme-toggle-icon, #ffc300);
      }
    }

    .theme-popover {
      position: absolute;
      top: calc(100% + 8px);
      right: 0;
      width: 160px;
      border-radius: 12px;
      padding: 8px;
      z-index: 200;
      background: var(--bg-popover, #1e1e20);
      border: 1px solid var(--border-color-light, #3c3c3c);
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25);
      animation: popoverSlideIn 0.2s ease;

      .theme-popover-title {
        font-size: 11px;
        font-weight: 600;
        padding: 4px 8px 8px;
        color: var(--text-secondary, #999);
        opacity: 0.7;
      }

      .theme-option {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px;
        border-radius: 8px;
        cursor: pointer;
        font-size: 13px;
        font-weight: 500;
        color: var(--text-primary, #ccc);
        transition: background 0.2s;

        &:hover {
          background: var(--bg-hover, #2a2a2c);
        }

        &.selected {
          background: var(--bg-hover, #2a2a2c);
          color: var(--color-accent, #ffc300);

          .check-mark {
            display: inline;
            color: var(--color-accent, #ffc300);
          }
        }

        .theme-dot {
          width: 22px;
          height: 22px;
          border-radius: 50%;
          flex-shrink: 0;

          &.dot-dark {
            background: linear-gradient(135deg, #161617, #2a2a2c);
            border: 2px solid #ffc300;
          }
          &.dot-blue {
            background: linear-gradient(135deg, #1a56db, #1a73e8);
            border: 2px solid #1a73e8;
          }
          &.dot-light {
            background: linear-gradient(135deg, #f7f8fa, #ffffff);
            border: 2px solid #ddd;
          }
        }

        .check-mark {
          margin-left: auto;
          font-size: 14px;
          display: none;
        }
      }
    }
  }

  // ======== 头像下拉 ========
  .avatar-dropdown-container {
    display: flex;
    align-items: center;
    position: relative;
    .dropdown-container {
      position: absolute;
      top: 150%;
      right: 0;
      width: 220px;
      background: var(--bg-popover, #1e1e20);
      border: 1px solid var(--border-color-light, #3c3c3c);
      border-radius: 12px;
      display: flex;
      flex-direction: column;
      padding: 12px;
      gap: 8px;
      z-index: 50;
      box-shadow: var(--shadow-card, 0px 2px 12px 0px rgba(0, 0, 0, 0.4));

      // 用户信息区
      .user-profile-section {
        display: flex;
        align-items: center;
        gap: 10px;
        padding-bottom: 10px;
        border-bottom: 1px solid var(--border-color, #2a2a2c);

        .profile-avatar {
          width: 42px;
          height: 42px;
          border-radius: 50%;
          object-fit: cover;
          border: 2px solid var(--color-accent, #e8a820);
          flex-shrink: 0;
        }

        .profile-info {
          flex: 1;
          min-width: 0;

          .profile-name {
            font-size: 14px;
            font-weight: 600;
            color: var(--text-primary, #fff);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .profile-uid {
            display: flex;
            align-items: center;
            gap: 4px;
            margin-top: 2px;
            cursor: pointer;

            span {
              font-size: 11px;
              color: var(--text-tertiary, #828694);
            }

            .copy-icon {
              width: 12px;
              height: 12px;
              opacity: 0.6;
            }
          }
        }
      }

      // 余额显示
      .balance-section {
        background: var(--bg-balance, linear-gradient(135deg, #2a2520 0%, #1e1e20 100%));
        border: 1px solid var(--border-balance, #3a3020);
        border-radius: 8px;
        padding: 10px 12px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .balance-label {
          font-size: 12px;
          color: var(--text-tertiary, #828694);
        }

        .balance-value {
          font-size: 18px;
          font-weight: 700;
          color: var(--color-accent, #e8a820);
        }
      }

      // 基本信息
      .info-section {
        display: flex;
        flex-direction: column;
        gap: 6px;
        padding: 6px 0;
        border-bottom: 1px solid var(--border-color, #2a2a2c);

        .info-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 2px 4px;

          .info-label {
            font-size: 12px;
            color: var(--text-tertiary, #828694);
          }

          .info-value {
            font-size: 12px;
            color: var(--text-primary, #d0d0d0);
          }
        }
      }

      // 退出登录
      .logout-wrapper {
        display: flex;
        align-items: center;
        padding: 8px 4px;
        gap: 6px;
        cursor: pointer;
        color: var(--text-tertiary, #828694);
        font-size: 13px;
        border-radius: 6px;
        transition: background 0.2s;

        &:hover {
          background: var(--bg-hover, #232325);
        }

        img {
          width: 16px;
          height: 16px;
        }
      }
    }
  }
}

@keyframes popoverSlideIn {
  from {
    opacity: 0;
    transform: translateY(-6px) scale(0.96);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}
</style>
