<script setup lang="ts">
import { ref, watch } from 'vue'
import type { SceneNode } from '@engine/types'
import { useEditorStore } from '../stores/editorStore'

const props = defineProps<{
  scene: SceneNode | null
  sceneList: { id: string; label: string }[]
}>()

const emit = defineEmits<{
  deleteScene: [id: string]
  close: []
}>()

const store = useEditorStore()
const jsonText = ref('')
const errorMsg = ref('')
const saved = ref(false)
const showAcceptReject = ref(false)
const preAIValue = ref('')

watch(() => store.aiResult, (result) => {
  if (!result) return
  preAIValue.value = jsonText.value
  jsonText.value = result
  showAcceptReject.value = true
  errorMsg.value = ''
})

function acceptAI() {
  showAcceptReject.value = false
  jsonText.value = jsonText.value
  store.setAIResult('')
  onBlur()
}

function rejectAI() {
  jsonText.value = preAIValue.value
  showAcceptReject.value = false
  store.setAIResult('')
}

watch(() => [props.scene, store.gameData] as const, () => {
  errorMsg.value = ''
  saved.value = false
  if (props.scene) {
    jsonText.value = JSON.stringify(props.scene, null, 2)
  } else if (Object.keys(store.gameData.scenes).length > 0) {
    const { scenes, ...rest } = store.gameData
    jsonText.value = JSON.stringify(rest, null, 2)
  } else {
    jsonText.value = ''
  }
}, { immediate: true, deep: true })

function onBlur() {
  errorMsg.value = ''
  try {
    const parsed = JSON.parse(jsonText.value)
    if (props.scene) {
      store.updateScene(props.scene.id, parsed)
    } else {
      const { scenes } = store.gameData
      store.gameData = { ...parsed, scenes }
      store.startSceneId = parsed.startScene || store.startSceneId
      store.autoSave()
    }
    saved.value = true
    setTimeout(() => { saved.value = false }, 2000)
  } catch (e: any) {
    errorMsg.value = e.message
  }
}
</script>

<template>
  <div class="node-editor" v-if="scene || jsonText">
    <div class="editor-header">
      <h3>{{ scene ? scene.id : '全局配置' }}</h3>
      <div class="header-actions">
        <span v-if="showAcceptReject" class="ai-actions">
          <button class="ai-accept-btn" @click.stop="acceptAI">接受</button>
          <button class="ai-reject-btn" @click.stop="rejectAI">撤销</button>
        </span>
        <span v-else-if="saved" class="saved-hint">已保存</span>
        <span v-if="errorMsg" class="error-hint">JSON 错误: {{ errorMsg }}</span>
        <button class="icon-btn" @click="store.showAIPanel = true" title="AI 助手">🤖</button>
        <button v-if="scene" class="icon-btn danger" @click="emit('deleteScene', scene.id)" title="删除场景">🗑</button>
        <button v-if="scene" class="icon-btn" @click="emit('close')" title="关闭">✕</button>
      </div>
    </div>

    <textarea
      class="json-area"
      :class="{ error: errorMsg }"
      :value="jsonText"
      @input="jsonText = ($event.target as HTMLTextAreaElement).value"
      @blur="onBlur"
      spellcheck="false"
    ></textarea>
  </div>

  <div class="node-editor empty-state" v-else-if="Object.keys(store.gameData.scenes).length === 0">
    <p>加载或新建场景后开始编辑</p>
  </div>
</template>

<style scoped>
.node-editor {
  width: 340px;
  height: 100%;
  background: #141428;
  border-left: 1px solid rgba(255,255,255,0.08);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.empty-state {
  align-items: center;
  justify-content: center;
  color: #555;
  font-size: 14px;
}

.editor-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 16px;
  border-bottom: 1px solid rgba(255,255,255,0.06);
  flex-shrink: 0;
}

.editor-header h3 {
  font-size: 16px;
  font-weight: 500;
  color: #ddd;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 0;
}

.saved-hint {
  font-size: 11px;
  color: #4caf50;
}

.error-hint {
  font-size: 11px;
  color: #e74c3c;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.icon-btn {
  background: none;
  border: 1px solid rgba(255,255,255,0.12);
  color: #888;
  width: 28px;
  height: 28px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  flex-shrink: 0;
}

.icon-btn:hover { color: #ddd; border-color: rgba(255,255,255,0.25); }
.icon-btn.danger:hover { color: #e74c3c; border-color: #e74c3c; }

.ai-actions {
  display: flex;
  gap: 4px;
}

.ai-accept-btn {
  padding: 3px 8px;
  font-size: 11px;
  color: #fff;
  background: #4caf50;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}
.ai-accept-btn:hover { background: #388e3c; }

.ai-reject-btn {
  padding: 3px 8px;
  font-size: 11px;
  color: #fff;
  background: #e74c3c;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}
.ai-reject-btn:hover { background: #c62828; }

.json-area {
  flex: 1;
  padding: 14px 16px;
  background: #0a0a1a;
  color: #ccc;
  border: none;
  outline: none;
  font-family: 'Menlo', 'Monaco', 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
  resize: none;
  tab-size: 2;
}

.json-area.error {
  border-left: 3px solid #e74c3c;
}
</style>
