<template>
  <div class="ai-app-header">
    <div class="header-left">
      <!-- 用户头像和信息区域 -->
      <div class="user-info">
        <div class="user-details">
          <!-- 创作页面显示返回按钮 -->
          <button v-if="isInCreatePage" class="back-btn" @click="goBack">
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M15 10H5M5 10L10 15M5 10L10 5" stroke="#1AC3FF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            <span>返回</span>
          </button>
          <!-- 非创作页面显示Logo -->
          <img v-else src="../../assets/Footer_svg/Footer_logo.svg" alt="logo" class="logo">
        </div>
      </div>
    </div>

    <div class="header-right">
      <!-- 已登录状态 -->
      <template v-if="userStore.isLoggedIn">
        <!-- 额度/优惠 pill -->
        <div class="credits-pill" @click="handleCreditsClick()">
          <span class="icon-slot">
            <!-- 放置额度图标SVG -->
            <slot name="credits-icon">
              <svg width="15" height="14" viewBox="0 0 15 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path fill-rule="evenodd" clip-rule="evenodd"
                  d="M7.80005 14C11.666 14 14.8 10.866 14.8 7C14.8 3.134 11.666 0 7.80005 0C3.93405 0 0.800049 3.134 0.800049 7C0.800049 10.866 3.93405 14 7.80005 14ZM9.46669 5.33333C8.32091 4.1875 7.80005 2 7.80005 2C7.80005 2 7.27919 4.1875 6.13338 5.33333C4.98755 6.47914 2.80005 7 2.80005 7C2.80005 7 5.05265 7.58596 6.13338 8.66664C7.21409 9.74738 7.80005 12 7.80005 12C7.80005 12 8.22973 9.90366 9.46669 8.66664C10.7037 7.42968 12.8 7 12.8 7C12.8 7 10.6125 6.47914 9.46669 5.33333Z"
                  fill="url(#paint0_linear_601_221)" />
                <defs>
                  <linearGradient id="paint0_linear_601_221" x1="0.800049" y1="2.72222" x2="8.62646" y2="7.48609"
                    gradientUnits="userSpaceOnUse">
                    <stop offset="0.0001" stop-color="#33DDE5" />
                    <stop offset="1" stop-color="#0F9CFF" />
                  </linearGradient>
                </defs>
              </svg>

            </slot>
          </span>
          <span class="credits-value">{{ formatBalance(userPoints) }}</span>
          <span class="divider"></span>
          <span class="credits-text">账户积分</span>
        </div>

        <!-- 通知铃铛 -->


        <!-- 用户头像 -->
        <button class="avatar-btn" type="button" aria-label="用户" @mouseenter="avatarHover = true" @mouseleave="onAvatarLeave">
          <div class="avatar-wrapper">
            <img 
              v-if="!avatarLoadFailed && currentUserInfo?.avatarUrl" 
              :src="currentUserInfo.avatarUrl" 
              :alt="displayName"
              @error="handleAvatarError"
              class="user-avatar-img"
            />
            <div v-else class="avatar-placeholder">
              {{ getAvatarText(displayName) }}
            </div>
          </div>
        </button>
        <UserAvatarPopover
          :user="currentUserInfo"
          :visible="avatarHover"
          @mouseenter="avatarHover = true"
          @mouseleave="avatarHover = false"
          @recharge="goToSubscriptionPage"
          @subscribe="goToSubscriptionPage"
          @consume="goToConsumeLog"
          @invite="goToInvite"
          @logout="logout"
        />

        <!-- 返回1818AI按钮 -->
        <button class="home-btn" type="button" @click="goToHome">
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M3 10L10 3L17 10M4 9V17C4 17.5523 4.44772 18 5 18H8V14C8 13.4477 8.44772 13 9 13H11C11.5523 13 12 13.4477 12 14V18H15C15.5523 18 16 17.5523 16 17V9" stroke="#1AC3FF" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          <span class="home-text">返回1818AI</span>
        </button>
      </template>

      <!-- 未登录状态 -->
      <template v-else>
        <button class="auth-btn login-btn-style" @click="showLogin">
          登录
        </button>
        <button class="auth-btn register-btn-style" @click="showRegister">
          注册
        </button>
        <button class="home-btn" type="button" @click="goToHome">
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M3 10L10 3L17 10M4 9V17C4 17.5523 4.44772 18 5 18H8V14C8 13.4477 8.44772 13 9 13H11C11.5523 13 12 13.4477 12 14V18H15C15.5523 18 16 17.5523 16 17V9" stroke="#1AC3FF" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          <span class="home-text">返回1818AI</span>
        </button>
      </template>
    </div>
  </div>

  <!-- 登录/注册弹窗 -->
  <LoginModal 
    :visible="loginModalVisible" 
    :mode="loginModalMode"
    @close="handleLoginModalClose"
    @login="handleLoginSuccess"
    @register="handleRegisterSuccess"
  />
  
  <!-- 推广弹窗 -->
  <PromotionModal 
    :visible="promotionModalVisible"
    @close="closePromotionModal"
  />

</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '../../store'
import LoginModal from '../LoginModal.vue'
import UserAvatarPopover from './UserAvatarPopover.vue'
import PromotionModal from './PromotionModal.vue'

// 路由
const router = useRouter()
const route = useRoute()

// 使用 store
const userStore = useUserStore()


const handleCreditsClick = () => {
  console.log('点击额度')
 
  router.push('/ai-application/subscription')
}

// 响应式数据
const avatarLoadFailed = ref(false)
const loginModalVisible = ref(false)
const loginModalMode = ref('login') // 'login' 或 'register'
const avatarHover = ref(false)
const promotionModalVisible = ref(false)

const onAvatarLeave = (e) => {
  // 避免鼠标在popover和按钮切换时闪烁
  setTimeout(() => {
    if (!(e.relatedTarget && e.relatedTarget.closest('.popover-container'))) {
      avatarHover.value = false
    }
  }, 60)
}

// 计算属性 - 当前用户信息
const currentUserInfo = computed(() => userStore.userInfo)

// 计算属性 - 显示名称
const displayName = computed(() => {
  if (!currentUserInfo.value) return '用户'
  return currentUserInfo.value.username || currentUserInfo.value.phone || '用户'
})

// 计算属性 - 用户积分
const userPoints = computed(() => {
  if (!currentUserInfo.value || !currentUserInfo.value.points) {
    return 0
  }
  return currentUserInfo.value.points
})

// 计算属性 - 是否在创作页面
const isInCreatePage = computed(() => {
  const path = route.path
  return path.includes('/create') || path.includes('/image-create')
})

// 格式化积分
const formatBalance = (points) => {
  if (!points && points !== 0) {
    return '0'
  }
  return Number.parseFloat(points).toFixed(0)
}

// 获取头像文字（用户名首字符）
const getAvatarText = (name) => {
  if (!name) return '用'
  return name.charAt(0).toUpperCase()
}

// 处理头像加载失败
const handleAvatarError = () => {
  avatarLoadFailed.value = true
}

// 处理头像点击
const handleAvatarClick = () => {
  // 如果已登录，跳转到AI创作个人主页
  if (userStore.isLoggedIn) {
    router.push('/ai-application/profile')
  }
}

// 显示登录弹窗
const showLogin = () => {
  loginModalMode.value = 'login'
  loginModalVisible.value = true
}

// 显示注册弹窗
const showRegister = () => {
  loginModalMode.value = 'register'
  loginModalVisible.value = true
}

// 关闭登录弹窗
const handleLoginModalClose = () => {
  loginModalVisible.value = false
}

// 登录成功处理
const handleLoginSuccess = () => {
  loginModalVisible.value = false
  console.log('登录成功')
  // 可以刷新页面或更新用户信息
}

// 注册成功处理
const handleRegisterSuccess = () => {
  loginModalVisible.value = false
  console.log('注册成功')
  // 可以刷新页面或更新用户信息
}

// 返回首页
const goToHome = () => {
  router.push('/')
}

// 返回AI创作主页
const goBack = () => {
  router.push('/ai-application')
}

const goToSubscriptionPage = () => {
  router.push('/ai-application/subscription')
}
const goToConsumeLog = () => router.push({ path: '/ai-application/subscription', query: { showConsumeModal: 1 } })

// 显示推广弹窗
const goToInvite = () => {
  avatarHover.value = false  // 关闭头像悬浮窗
  promotionModalVisible.value = true
}

// 关闭推广弹窗
const closePromotionModal = () => {
  promotionModalVisible.value = false
}

const logout = () => userStore.logout()
</script>

<style scoped>
.ai-app-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 80px;
  background-color: #151515;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 40px;
  box-sizing: border-box;
  color: #1AC3FF;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  z-index: 1000;
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  
}

.header-left {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}


.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
  font-size: 24px;
  font-weight: 600;
  color: #1AC3FF;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.logo {
  height: 40px;
  width: auto;
  object-fit: contain;
}

/* 返回按钮 */
.back-btn {
  height: 40px;
  padding: 0 16px;
  border-radius: 20px;
  border: 1px solid rgba(26, 195, 255, 0.3);
  background: rgba(26, 195, 255, 0.1);
  color: #1AC3FF;
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  outline: none;
}

.back-btn:hover {
  background: rgba(26, 195, 255, 0.2);
  border-color: #1AC3FF;
  transform: translateX(-2px);
  box-shadow: 0 4px 12px rgba(26, 195, 255, 0.3);
}

.back-btn:active {
  transform: translateX(0);
}

.back-btn svg {
  flex-shrink: 0;
}

.back-btn span {
  white-space: nowrap;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

/* 额度 pill */
.credits-pill {
  height: 36px;
  display: inline-flex;
  align-items: center;
  padding: 0 12px;
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 12px;
  color: #E2F3FF;
  background: rgba(255, 255, 255, 0.04);
  gap: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.credits-pill:hover {
  background: rgba(255, 255, 255, 0.08);
  border-color: rgba(26, 195, 255, 0.4);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(26, 195, 255, 0.2);
}

.credits-pill .icon-slot {
  width: 18px;
  height: 18px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.credits-value {
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
  font-size: 14px;
  font-weight: 600;
  color: #1AC3FF;
}

.credits-text {
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
  font-size: 14px;
  color: #1AC3FF;
}

.credits-pill .divider {
  width: 1px;
  height: 16px;
  background: rgba(255, 255, 255, 0.2);
}

/* 通知按钮 */
.notify-btn {
  position: relative;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: none;
  outline: none;
  background: rgba(255, 255, 255, 0.08);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.notify-btn:hover {
  background: rgba(255, 255, 255, 0.12);
}

.notify-btn .icon-slot {
  width: 18px;
  height: 18px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.notify-badge {
  position: absolute;
  top: -3px;
  right: -2px;
  min-width: 16px;
  height: 16px;
  padding: 0 4px;
  border-radius: 8px;
  background: #FF4D4F;
  color: #fff;
  font-size: 10px;
  line-height: 16px;
  text-align: center;
  box-shadow: 0 0 0 2px #0F172A inset;
}

/* 头像按钮 */
.avatar-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: none;
  background: rgba(26, 195, 255, 0.15);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: inset 0 0 0 2px #1AC3FF;
  padding: 0;
  overflow: hidden;
  transition: all 0.3s ease;
}

.avatar-btn:hover {
  transform: scale(1.05);
  box-shadow: inset 0 0 0 2px #33DDE5;
}

.avatar-btn .icon-slot {
  width: 18px;
  height: 18px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 头像包装器 */
.avatar-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 用户头像图片 */
.user-avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

/* 登录/注册按钮基础样式 */
.auth-btn {
  height: 36px;
  padding: 0 20px;
  border-radius: 18px;
  border: none;
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  outline: none;
}

/* 登录按钮样式 */
.login-btn-style {
  background: rgba(26, 195, 255, 0.15);
  color: #1AC3FF;
  border: 1px solid #1AC3FF;
}

.login-btn-style:hover {
  background: rgba(26, 195, 255, 0.25);
  border-color: #33DDE5;
  color: #33DDE5;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(26, 195, 255, 0.3);
}

.login-btn-style:active {
  transform: translateY(0);
}

/* 注册按钮样式 */
.register-btn-style {
  background: linear-gradient(135deg, #1AC3FF 0%, #0F9CFF 100%);
  color: #ffffff;
  border: 1px solid transparent;
  box-shadow: 0 2px 8px rgba(26, 195, 255, 0.3);
}

.register-btn-style:hover {
  background: linear-gradient(135deg, #33DDE5 0%, #1AC3FF 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(26, 195, 255, 0.5);
}

.register-btn-style:active {
  transform: translateY(0);
}

/* 返回首页按钮 */
.home-btn {
  height: 36px;
  padding: 0 16px;
  border-radius: 18px;
  border: 1px solid rgba(255, 255, 255, 0.15);
  background: rgba(255, 255, 255, 0.04);
  color: #1AC3FF;
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  outline: none;
}

.home-btn:hover {
  background: rgba(255, 255, 255, 0.08);
  border-color: #1AC3FF;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(26, 195, 255, 0.2);
}

.home-btn:active {
  transform: translateY(0);
}

.home-btn svg {
  flex-shrink: 0;
}

.home-text {
  white-space: nowrap;
}



/* 移动端适配 */
@media (max-width: 768px) {
  .ai-app-header {
    height: 70px;
    padding: 0 20px;
  }

  .avatar {
    width: 40px;
    height: 40px;
  }

  .avatar-placeholder {
    font-size: 20px;
  }

  .username {
    font-size: 18px;
  }

  .user-tip {
    font-size: 12px;
  }

  .user-id {
    font-size: 11px;
  }

  .credits-pill {
    height: 32px;
  }
}

@media (max-width: 480px) {
  .ai-app-header {
    height: 60px;
    padding: 0 15px;
  }

  .user-info {
    gap: 12px;
  }

  .avatar {
    width: 36px;
    height: 36px;
  }

  .avatar-placeholder {
    font-size: 18px;
  }

  .username {
    font-size: 16px;
  }

  .user-tip {
    font-size: 11px;
  }

  .user-id {
    display: none;
  }

  .credits-pill {
    height: 30px;
  }
}
</style>
