<script setup lang="ts">
import { ref, nextTick, computed } from "vue";

const props = defineProps(["data"]);

// 标题内容：独立字段 data.title，未设置时展示占位
const title = ref<string>(props.data?.title ?? "");
const isEditing = ref(false);
const editValue = ref("");
const inputRef = ref<HTMLInputElement | null>(null);

const displayText = computed(() => title.value || "");

const startEdit = () => {
  editValue.value = title.value;
  isEditing.value = true;
  nextTick(() => {
    inputRef.value?.focus();
  });
};

// 失焦保存：非空才写回 data.title，避免空标题覆盖
const saveEdit = () => {
  const val = editValue.value.trim();
  if (val) {
    title.value = val;
    if (props.data) props.data.title = val;
  }
  isEditing.value = false;
};

const onKeydown = (e: KeyboardEvent) => {
  if (e.key === "Enter") {
    e.preventDefault();
    saveEdit();
  } else if (e.key === "Escape") {
    isEditing.value = false;
  }
};

// 编辑态阻止冒泡，避免在标题上按下鼠标触发节点拖拽
const stopDragPropagation = (e: Event) => {
  e.stopPropagation();
};
</script>

<template>
  <div class="node-title">
    <div
      v-if="!isEditing"
      class="title-display"
      :class="{ placeholder: !displayText }"
      @click.stop="startEdit"
      :title="displayText || '双击编辑标题'"
    >
      {{ displayText || "未命名" }}
    </div>
    <input
      v-else
      ref="inputRef"
      v-model="editValue"
      class="title-input"
      type="text"
      placeholder="输入标题"
      @blur="saveEdit"
      @keydown="onKeydown"
      @mousedown.stop="stopDragPropagation"
      @pointerdown.stop="stopDragPropagation"
    />
  </div>
</template>

<style scoped lang="scss">
.node-title {
  width: 240px;
  box-sizing: border-box;
  margin-bottom: 2px;
  overflow: hidden;
}

.title-display {
  font-size: 13px;
  color: #ccc;
  line-height: 1.4;
  padding: 2px 6px;
  border-radius: 4px;
  cursor: move;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: background 0.2s;

  &.placeholder {
    color: #666;
    font-style: italic;
  }
}

.title-input {
  width: 100%;
  box-sizing: border-box;
  font-size: 13px;
  color: #fff;
  line-height: 1.4;
  padding: 2px 6px;
  background: none;
  border: 1px solid #409eff;
  border-radius: 4px;
  outline: none;

  &:focus {
    border: none;
  }

  &::placeholder {
    color: #555;
  }
}
</style>
