<template>
  <div class="head surface-card">
    <el-button
      v-if="showBackButton"
      text
      class="back-btn"
      @click="router.push('/welcome')"
    >
      ← 返回首页
    </el-button>
    <template v-if="pageTitle">
      <h1 class="head-title">{{ pageTitle }}</h1>
    </template>
    <div v-else class="brand-block">
      <p class="brand-title">学习进度跟踪系统</p>
      <p class="brand-subtitle">把学习变成可记录、可回顾、可持续的日常流程</p>
    </div>
    <el-button
      v-if="!isLoginRoute"
      type="success"
      plain
      class="logout-btn"
      @click="handleLogout"
    >
      退出登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import router from "@/router";
import { logout } from "@/api/login";

const route = useRoute();
const isLoginRoute = computed(() => route.path === "/login");
const showBackButton = computed(() => route.path !== "/login" && route.path !== "/welcome");
const pageTitle = computed(() => route.meta?.title as string | undefined);

const handleLogout = async () => {
  try {
    await logout();
  } catch {
    // 后端退出失败时，仍然清理前端登录态，避免用户被卡住。
  } finally {
    localStorage.removeItem("isLoggedIn");
    ElMessage.success("已退出登录");
    await router.push("/login");
  }
};
</script>

<style scoped>
.head {
  min-height: 82px;
  padding: 14px 18px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.brand-title {
  margin: 0;
  font-weight: 700;
  font-size: clamp(18px, 2.4vw, 24px);
  letter-spacing: 0.3px;
  color: var(--green-900);
}

.brand-subtitle {
  margin: 4px 0 0;
  font-size: 13px;
  color: var(--text-secondary);
}

.head-title {
  margin: 0;
  font-size: clamp(18px, 2.4vw, 24px);
  font-weight: 700;
  color: var(--green-900);
  flex: 1;
}

.back-btn {
  font-size: 14px;
  color: var(--green-700);
  padding: 0 4px;
  flex-shrink: 0;
}
.back-btn:hover {
  color: var(--green-900);
}

.logout-btn {
  border-color: var(--green-600);
  color: var(--green-700);
}

@media (max-width: 768px) {
  .head {
    align-items: flex-start;
    flex-direction: column;
  }

  .logout-btn {
    width: 100%;
  }
}
</style>
