<template>
  <div class="version-history">
    <!-- 顶部操作栏 -->
    <div class="version-header">
      <div class="header-right">
        <a-button type="text" size="small" @click="handleRefresh" :loading="refreshing">
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>
        <a-button type="text" size="small" @click="handleOpenExternal">
          <template #icon><icon-export /></template>
          在浏览器打开
        </a-button>
      </div>
    </div>

    <!-- iframe 嵌入远程页面 -->
    <div class="iframe-wrapper">
      <iframe
        ref="iframeRef"
        :src="iframeSrc"
        class="version-iframe"
        frameborder="0"
        @load="onIframeLoad"
      />
      <div v-if="loading" class="iframe-loading">
        <a-spin size="32" />
        <p>加载中...</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { IconRefresh, IconExport } from '@arco-design/web-vue/es/icon'

// ==================== 常量 ====================
const BASE_URL = 'https://c.1216.top/u-desk/version.html'

// ==================== 状态 ====================
const currentVersion = ref('')
const loading = ref(true)
const refreshing = ref(false)
const iframeRef = ref<HTMLIFrameElement | null>(null)

// ==================== 计算属性 ====================
const iframeSrc = computed(() => {
  if (currentVersion.value) {
    return `${BASE_URL}?v=${currentVersion.value}&vis=u-desk`
  }
  return `${BASE_URL}?vis=u-desk`
})

// ==================== 操作 ====================
function handleRefresh(): void {
  refreshing.value = true
  loading.value = true
  if (iframeRef.value) {
    iframeRef.value.src = iframeSrc.value
  }
}

function handleOpenExternal(): void {
  window.open(iframeSrc.value, '_blank')
}

function onIframeLoad(): void {
  loading.value = false
  refreshing.value = false
}

// ==================== 生命周期 ====================
onMounted(async () => {
  try {
    const result = await window.go?.main?.App?.GetCurrentVersion?.()
    if (result?.success) {
      currentVersion.value = result.data?.version || ''
    }
  } catch {
    // Wails 未就绪时忽略
  }
})
</script>

<style scoped>
.version-history {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0 4px;
}

/* ====== 顶部栏 ====== */
.version-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 8px;
  flex-shrink: 0;
}

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

/* ====== iframe ====== */
.iframe-wrapper {
  flex: 1;
  position: relative;
  min-height: 0;
}

.version-iframe {
  width: 100%;
  height: 100%;
  border: none;
  border-radius: 8px;
  background: var(--color-bg-1);
}

.iframe-loading {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  color: var(--color-text-3);
  background: var(--color-bg-1);
  border-radius: 8px;
}
</style>
