<template>
  <Transition name="fade">
    <div v-if="visible" class="remote-input-panel">
      <span class="input-text">{{ displayValue }}</span>
    </div>
  </Transition>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useEvent } from "../../composables/useEvent.js";
import { debounce } from "../../utils/common.js";

const emit = defineEmits(["complete"]);

// 内部状态
const visible = ref(false);
const inputValue = ref([]);

// 显示的文本
const displayValue = computed(() => {
  return inputValue.value.join("");
});

// 关闭面板的函数（防抖）
const closePanel = debounce(() => {
  visible.value = false;
  inputValue.value = [];
  emit("complete", displayValue.value);
}, 3000);

// 处理数字输入
const handleDigit = (digit) => {
  // 显示面板
  visible.value = true;

  if (inputValue.value.length == 3) {
    // 超过3位，删除最前面的数字
    inputValue.value.shift();
  }
  // 添加数字
  inputValue.value.push(digit);

  // 重置定时器
  closePanel();
};

onMounted(() => {
  // 注册数字键事件（0-9）
  useEvent("keyup", (e) => {
    if (e.key >= "0" && e.key <= "9") {
      handleDigit(e.key);
    }
  });
});
</script>

<style scoped>
.remote-input-panel {
  position: fixed;
  top: 20px;
  right: 20px;
  min-width: 60px;
  height: 44px;
  padding: 0 16px;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 160;
  backdrop-filter: blur(4px);
}

.input-text {
  font-size: 24px;
  font-weight: bold;
  color: #fff;
  font-family: monospace;
  letter-spacing: 4px;
}

/* 淡入淡出动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
