<script setup>
import { ref, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import { setDevToken, getDevToken } from '@gold/utils/token-manager'

const token = ref('')
const isVisible = ref(true)

// 从 sessionStorage 恢复 token
onMounted(() => {
  const saved = getDevToken()
  if (saved) {
    token.value = saved
  }
})

// 保存 token
const handleSave = () => {
  if (token.value.trim()) {
    setDevToken(token.value)
    message.success('Token 已保存')
  } else {
    setDevToken('')
    message.success('Token 已清除')
  }
}

// 监听输入变化，自动保存（防抖）
let saveTimer = null
watch(token, () => {
  clearTimeout(saveTimer)
  saveTimer = setTimeout(() => {
    if (token.value.trim()) {
      setDevToken(token.value)
    }
  }, 500)
})
</script>

<template>
  <div v-if="isVisible" class="token-input-wrapper">
    <div class="token-input-label">Dev Token</div>
    <input
      v-model="token"
      type="password"
      placeholder="输入测试 token"
      class="token-input"
      @keyup.enter="handleSave"
    />
    <button class="token-btn" @click="handleSave">保存</button>
  </div>
</template>

<style scoped>
.token-input-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.token-input-label {
  font-size: 12px;
  color: var(--color-text-secondary);
  white-space: nowrap;
}

.token-input {
  width: 200px;
  height: 28px;
  padding: 0 8px;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  background: var(--color-surface);
  color: var(--color-text);
  font-size: 12px;
  outline: none;
  transition: all 0.2s;
}

.token-input:focus {
  border-color: var(--color-primary);
  box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.1);
}

.token-btn {
  height: 28px;
  padding: 0 12px;
  border: 1px solid var(--color-primary);
  border-radius: 4px;
  background: transparent;
  color: var(--color-primary);
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.token-btn:hover {
  background: var(--color-primary);
  color: #fff;
}
</style>

