<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useSystemStore } from '@/stores/system'
import { useRoute, useRouter } from 'vue-router'

const systemStore = useSystemStore()
const { metrics } = storeToRefs(systemStore)
const route = useRoute()
const router = useRouter()

const showBackButton = computed(() => {
  return route.path.split('/').filter(Boolean).length > 1
})

function handleBack() {
  const backRouteName = route.meta.backRouteName
  if (typeof backRouteName === 'string' && backRouteName) {
    void router.push({ name: backRouteName })
    return
  }
  router.back()
}

function usageClass(val?: number) {
  return val != null && val > 80 ? 'is-danger' : ''
}

const currentTime = ref('')
const currentDate = ref('')
let timer: ReturnType<typeof setInterval> | null = null

function updateTime() {
  const now = new Date()
  currentTime.value = now.toLocaleTimeString('zh-CN', { hour12: false })
  currentDate.value = now.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-')
}

function openGuide() {
  const guideUrl = router.resolve({ name: 'guide' }).href
  window.open(guideUrl, '_blank', 'noopener,noreferrer')
}

const serverIp = ref(window.location.hostname)

onMounted(() => {
  updateTime()
  timer = setInterval(updateTime, 1000)
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
})
</script>

<template>
  <header class="app-header">
    <div class="header-left">
      <el-button
        v-if="showBackButton"
        class="back-btn"
        link
        @click="handleBack"
      >
        <div class="back-icon-wrap">
          <i class="fa fa-arrow-left" />
        </div>
        <span class="back-text">返回上一页</span>
      </el-button>
    </div>

    <div class="header-right">
      <!-- 系统监控指标 -->
      <div class="metrics-dashboard" @click="router.push('/hardware')">
        <el-tooltip content="CPU 使用率" placement="bottom">
          <div class="metric-badge">
            <i class="fa fa-microchip icon cpu" />
            <span class="value" :class="usageClass(metrics.cpu_percent)">
              {{ metrics.cpu_percent ?? '--' }}<small>%</small>
            </span>
          </div>
        </el-tooltip>

        <el-tooltip content="内存 使用率" placement="bottom">
          <div class="metric-badge">
            <i class="fa fa-database icon mem" />
            <span class="value" :class="usageClass(metrics.memory_percent)">
              {{ metrics.memory_percent ?? '--' }}<small>%</small>
            </span>
          </div>
        </el-tooltip>

        <el-tooltip content="磁盘 使用率" placement="bottom">
          <div class="metric-badge">
            <i class="fa fa-hdd-o icon disk" />
            <span class="value" :class="usageClass(metrics.disk_percent)">
              {{ metrics.disk_percent ?? '--' }}<small>%</small>
            </span>
          </div>
        </el-tooltip>
      </div>

      <div class="divider"></div>

      <!-- 时间日期与服务器IP -->
      <div class="system-info">
        <div class="info-item">
          <i class="fa fa-server" />
          <span>{{ serverIp }}</span>
        </div>
        <div class="info-item">
          <i class="fa fa-calendar" />
          <span>{{ currentDate }}</span>
        </div>
        <div class="info-item time-item">
          <i class="fa fa-clock-o" />
          <span>{{ currentTime }}</span>
        </div>
      </div>

      <div class="divider document-divider"></div>

      <el-tooltip content="使用文档" placement="bottom">
        <button
          type="button"
          class="documentation-btn"
          aria-label="打开使用文档"
          @click="openGuide"
        >
          <i class="fa fa-book" aria-hidden="true" />
        </button>
      </el-tooltip>
    </div>
  </header>
</template>

<style scoped lang="scss">
.app-header {
  height: var(--header-height);
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.04);
  box-shadow: 0 1px 12px rgba(0, 0, 0, 0.02);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  flex-shrink: 0;
  position: sticky;
  top: 0;
  z-index: 50;
}

.header-left {
  .back-btn {
    display: flex;
    align-items: center;
    color: #64748b;
    font-weight: 500;
    transition: all 0.2s;

    .back-icon-wrap {
      width: 28px;
      height: 28px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f1f5f9;
      border-radius: 8px;
      margin-right: 8px;
      transition: all 0.2s;
    }

    &:hover {
      color: var(--primary-color);
      
      .back-icon-wrap {
        background: rgba(79, 70, 229, 0.1);
        color: var(--primary-color);
      }
    }
  }
}

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

.metrics-dashboard {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  padding: 4px 6px;
  border-radius: 12px;
  transition: background 0.2s;

  &:hover {
    background: #f8fafc;
  }

  .metric-badge {
    display: flex;
    align-items: center;
    background: #f1f5f9;
    padding: 4px 10px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 600;
    color: #475569;
    border: 1px solid transparent;
    transition: all 0.2s;

    &:hover {
      background: #fff;
      border-color: #e2e8f0;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    }

    .icon {
      margin-right: 6px;
      font-size: 14px;

      &.cpu { color: var(--primary-color); }
      &.mem { color: var(--success-color); }
      &.disk { color: var(--warning-color); }
    }

    .value {
      small {
        font-size: 10px;
        color: #94a3b8;
        margin-left: 2px;
      }
      
      &.is-danger {
        color: var(--danger-color);
        animation: pulse 2s infinite;
      }
    }
  }
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.6; }
  100% { opacity: 1; }
}

.divider {
  width: 1px;
  height: 24px;
  background-color: #e2e8f0;
}

.system-info {
  display: flex;
  align-items: center;
  gap: 16px;
  color: #64748b;
  font-size: 13px;
  font-weight: 500;
  background: #f8fafc;
  padding: 6px 12px;
  border-radius: 8px;
  border: 1px solid #f1f5f9;

  .info-item {
    display: flex;
    align-items: center;
    gap: 6px;

    i {
      color: #94a3b8;
    }
  }

  .time-item {
    color: #475569;
    font-weight: 600;
    min-width: 80px;
    font-variant-numeric: tabular-nums;
    i {
      color: var(--primary-color);
    }
  }
}

.documentation-btn {
  width: 40px;
  height: 40px;
  padding: 0;
  border: 1px solid #e2e8f0;
  border-radius: 10px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  flex: 0 0 auto;
  background: #fff;
  color: #64748b;
  cursor: pointer;
  font-size: 17px;
  transition: color 180ms ease, border-color 180ms ease, background-color 180ms ease, box-shadow 180ms ease;

  &:hover {
    border-color: rgba(79, 70, 229, 0.28);
    background: #eef2ff;
    color: var(--primary-color);
    box-shadow: 0 4px 12px rgba(79, 70, 229, 0.1);
  }

  &:focus-visible {
    outline: 3px solid rgba(79, 70, 229, 0.2);
    outline-offset: 2px;
  }
}

@media (max-width: 1280px) {
  .header-right {
    gap: 12px;
  }

  .system-info .info-item:first-child {
    display: none;
  }
}

@media (max-width: 1040px) {
  .system-info,
  .header-right > .divider:not(.document-divider) {
    display: none;
  }
}
</style>
