<template>
  <div class="root-node-wrapper">
    <!-- 左侧连接点（输入） -->
    <Handle type="target" :position="Position.Left" id="left" />
    <!-- 右侧连接点（输出） -->
    <Handle type="source" :position="Position.Right" id="right" />
    <!-- 底部连接点（用于分支） -->
    <Handle type="source" :position="Position.Bottom" id="bottom" />

    <el-card class="root-node-card" :shadow="true">
      <!-- 目标内容 -->
      <div class="goal-content">
        <div class="goal-label">初始目标</div>
        <div class="goal-text">{{ goal }}</div>
      </div>
    </el-card>

    <!-- 底部添加按钮 -->
    <div v-if="!isAddingBranch" class="external-add-btn" @click="startAddBranch">
      <el-icon :size="20" color="#409eff">
        <CirclePlus />
      </el-icon>
    </div>

    <!-- 取消按钮（输入框显示时） -->
    <div v-else class="external-add-btn cancel-btn" @click="cancelAddBranch">
      <el-icon :size="20" color="#f56c6c">
        <Remove />
      </el-icon>
    </div>

    <!-- 外部输入框 -->
    <div v-if="isAddingBranch" class="external-input-container">
      <el-input
        v-model="branchInput"
        placeholder="输入分支需求..."
        size="small"
        @keydown="handleBranchKeydown"
        ref="branchInputRef"
        class="branch-input"
      >
        <template #suffix>
          <svg-icon
            icon-class="paper-plane"
            size="16px"
            color="#409eff"
            class="submit-icon"
            :class="{ 'is-disabled': !branchInput.trim() }"
            @click="submitBranch"
          />
        </template>
      </el-input>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { CirclePlus, Remove } from '@element-plus/icons-vue'
import { Handle, Position } from '@vue-flow/core'
import SvgIcon from '@/components/SvgIcon/index.vue'
interface RootNodeData {
  goal: string
  initialInput?: string[] | string
  isRoot?: boolean
}

const props = defineProps<{
  id: string
  data: RootNodeData
  isAddingBranch?: boolean
  [key: string]: any
}>()

const emit = defineEmits<{
  (e: 'add-branch', nodeId: string, branchContent: string): void
  (e: 'start-add-branch', nodeId: string): void
  (e: 'cancel-add-branch'): void
}>()

const goal = computed(() => props.data.goal || '')

const initialInput = computed(() => props.data.initialInput)

const displayInput = computed(() => {
  if (!initialInput.value) return false
  if (Array.isArray(initialInput.value)) {
    return initialInput.value.length > 0
  }
  return initialInput.value.trim().length > 0
})

// 分支添加相关状态（使用父组件传入的 prop）
const branchInput = ref('')
const branchInputRef = ref<InstanceType<typeof HTMLInputElement>>()

// 计算属性，使用父组件传入的状态
const isAddingBranch = computed(() => props.isAddingBranch || false)

// 分支添加相关方法
const startAddBranch = () => {
  emit('start-add-branch', props.id)
  branchInput.value = ''
  nextTick(() => {
    branchInputRef.value?.focus()
  })
}

const cancelAddBranch = () => {
  emit('cancel-add-branch')
  branchInput.value = ''
}

const submitBranch = () => {
  if (branchInput.value.trim()) {
    emit('add-branch', props.id, branchInput.value.trim())
    branchInput.value = ''
  }
}

const handleBranchKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    event.preventDefault()
    submitBranch()
  } else if (event.key === 'Escape') {
    cancelAddBranch()
  }
}
</script>

<style scoped lang="scss">
.root-node-card {
  width: 200px;
  min-height: 100px;
  background: var(--color-bg-three);
  border: 2px solid #409eff;
  box-sizing: border-box;
  transition: all 0.2s ease;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);

  &:hover {
    box-shadow: 0 6px 16px rgba(64, 158, 255, 0.3);
    transform: translateY(-2px);
  }

  :deep(.el-card__body) {
    padding: 16px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    position: relative;
  }
}

.root-badge {
  position: absolute;
  top: -10px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
}

.goal-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 4px;
}

.goal-content {
  text-align: center;
}

.goal-label {
  font-size: 12px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 6px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.goal-text {
  font-size: 14px;
  font-weight: 600;
  color: var(--color-text-title-header);
  line-height: 1.6;
  word-break: break-word;
  white-space: pre-wrap;
}

.initial-input {
  margin-top: 4px;
}

.input-divider {
  height: 1px;
  background: linear-gradient(to right, transparent, #409eff, transparent);
  margin: 8px 0;
}

.input-label {
  font-size: 12px;
  font-weight: bold;
  color: var(--color-text-secondary);
  margin-bottom: 6px;
}

.input-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;
}

.input-text {
  font-size: 13px;
  color: var(--color-text-secondary);
  text-align: center;
  word-break: break-word;
  line-height: 1.5;
}

// 节点包装器
.root-node-wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

// 外部添加按钮
.external-add-btn {
  position: absolute;
  bottom: -20px;
  left: 50%;
  transform: translateX(-50%);
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #fff;
  border: 2px solid #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);

  &:hover {
    background: #409eff;
    transform: translateX(-50%) scale(1.1);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);

    .el-icon {
      color: #fff;
    }
  }

  &:active {
    transform: translateX(-50%) scale(0.95);
  }

  // 取消按钮样式
  &.cancel-btn {
    border-color: #f56c6c;
    box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);

    &:hover {
      background: #f56c6c;
      box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
    }
  }
}

// 外部输入容器
.external-input-container {
  position: absolute;
  bottom: -80px;
  left: 50%;
  transform: translateX(-50%);
  width: 260px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  z-index: 100;
  animation: slideDown 0.2s ease-out;

  &::before {
    content: '';
    position: absolute;
    top: -6px;
    left: 50%;
    transform: translateX(-50%);
    width: 12px;
    height: 12px;
    background: #fff;
    border-left: 1px solid #dcdfe6;
    border-top: 1px solid #dcdfe6;
    transform: translateX(-50%) rotate(45deg);
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

.branch-input {
  width: 100%;

  :deep(.el-input__wrapper) {
    background: transparent;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    box-shadow: none;

    &:hover {
      border-color: #c0c4cc;
    }

    &.is-focus {
      border-color: #409eff;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    }

    .el-input__inner {
      font-size: 13px;
      color: var(--color-text-primary);
      padding-right: 40px;
    }
  }
}

// 提交图标样式
.submit-icon {
  cursor: pointer;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;

  &:hover:not(.is-disabled) {
    transform: scale(1.1);
  }

  &:active:not(.is-disabled) {
    transform: scale(0.95);
  }

  &.is-disabled {
    opacity: 0.4;
    cursor: not-allowed;
  }
}
</style>
