<script setup>
import { ref, computed, onMounted, watch, nextTick, onUnmounted, markRaw } from 'vue';
import { VueFlow, useVueFlow, Panel } from '@vue-flow/core';
import { Controls, ControlButton } from '@vue-flow/controls';
import { MiniMap } from '@vue-flow/minimap';
import { Background } from '@vue-flow/background';
import { useMessage, NButton, NSpace } from 'naive-ui';
import { useFlowStore } from './store/flowStore.js';
import { flowExecutor } from './executors/flowExecutor.js';
import NodePalette from './components/Sidebar/NodePalette.vue';
import ExecutionResults from './components/ExecutionResults.vue';
import { getNodeComponents, getNodeMetadataByType, preloadNodeMetadata } from './utils/nodeMetadata.js';
import { t } from '@/shared/i18n'

// Props
const props = defineProps({
  initialValue: {
    type: Object,
    default: () => ({})
  },
  agentId: {
    type: String,
    default: ''
  }
})

const store = useFlowStore();
const message = useMessage();

const vueFlowInstance = ref(null);

const selectedNode = ref(null);
const selectedEdge = ref(null);
const showSidebar = ref(true);
const draggedNodeType = ref(null);

const showTemplateData = ref(false);
const openTemplateData = () => { showTemplateData.value = true; };
const closeTemplateData = () => { showTemplateData.value = false; };

// 执行结果显示 + 最小化的视口保存/恢复
const showExecutionResults = ref(false);
const savedViewport = ref(null);

const toggleExecutionResults = async () => { 
  if (!showExecutionResults.value) {
    // 进入执行结果前保存视口
    try {
      const obj = toObject?.();
      if (obj && obj.viewport) savedViewport.value = { ...obj.viewport };
    } catch (e) {}
    showExecutionResults.value = true; 
  } else {
    // 返回流程后恢复视口
    showExecutionResults.value = false; 
    await nextTick();
    try {
      if (savedViewport.value) {
        setViewport?.(savedViewport.value);
      } else if (store.nodes.length > 0) {
        fitView({ padding: 0.7 });
      }
    } catch (e) {}
  }
};
const closeExecutionResults = async () => { 
  showExecutionResults.value = false; 
  await nextTick();
  try {
    if (savedViewport.value) {
      setViewport?.(savedViewport.value);
    } else if (store.nodes.length > 0) {
      fitView({ padding: 0.7 });
    }
  } catch (e) {}
};

const isExecuting = ref(false);
const executionResult = ref(null);
const executionHistory = ref([]);

// 全屏相关
const isFullscreen = ref(false);
const flowBuilderRoot = ref(null);

// 动态 Teleport 目标
const nodePropertyTeleportTarget = computed(() => {
  if (isFullscreen.value && flowBuilderRoot.value) {
    return flowBuilderRoot.value;
  }
  return 'body';
});

const toggleFullscreen = () => {
  const el = flowBuilderRoot.value;
  if (!el) return;
  if (!isFullscreen.value) {
    if (el.requestFullscreen) {
      el.requestFullscreen();
    } else if (el.webkitRequestFullscreen) {
      el.webkitRequestFullscreen();
    } else if (el.mozRequestFullScreen) {
      el.mozRequestFullScreen();
    } else if (el.msRequestFullscreen) {
      el.msRequestFullscreen();
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    }
  }
};

const fullscreenChangeHandler = () => {
  isFullscreen.value = !!(
    document.fullscreenElement ||
    document.webkitFullscreenElement ||
    document.mozFullScreenElement ||
    document.msFullscreenElement
  );
};

// 在 setup 顶部调用 useVueFlow
const { fitView, setViewport, toObject } = useVueFlow();

// 添加 onPaneReady 钩子
const onPaneReady = () => {
  if (store.nodes.length > 0) {
    fitView({ padding: 0.7 });
  }
};

// 节点组件映射（响应式）
const nodeTypes = ref({});
const nodeTypesLoaded = ref(false);

// 预加载节点元数据
onMounted(async () => {
  try {
    await preloadNodeMetadata();
    // 更新节点组件映射
    const components = getNodeComponents();
    nodeTypes.value = markRaw(components);
    nodeTypesLoaded.value = true;
    
    // 节点元数据加载完成后，再初始化流程数据
    await nextTick();
    initFlowData();
    store.saveToHistory();
  } catch (error) {
    console.error('节点元数据加载失败:', error);
    // 即使失败也要设置加载完成状态，避免无限等待
    nodeTypesLoaded.value = true;
  }
});

// 获取节点颜色函数
const getNodeColor = (nodeType) => {
  const metadata = getNodeMetadataByType(nodeType);
  return metadata ? metadata.color : '#6b7280';
};

// 计算属性
const nodes = computed(() => store.nodes);
const edges = computed(() => store.edges);
const hasSelection = computed(() => selectedNode.value || selectedEdge.value);

// 节点选择处理
const onNodeClick = (event) => {
  selectedNode.value = event.node;
  selectedEdge.value = null;
  // 不弹窗
};

// 监听自定义节点的 edit-node 事件
function onEditNode(nodeId) {
  // 删除这个函数，因为节点组件现在自己处理编辑
}

// 边选择处理
const onEdgeClick = (event) => {
  selectedEdge.value = event.edge;
  selectedNode.value = null;
};

// 取消选择
const onPaneClick = () => {
  selectedNode.value = null;
  selectedEdge.value = null;
};

// 连接处理
const onConnect = (params) => {
  
  // 基本验证
  if (!params.source || !params.target) {
    return;
  }
  
  // 检查 handle 类型，禁止输出连输出
  const sourceHandle = params.sourceHandle || 'output';
  const targetHandle = params.targetHandle || 'input';
  if (sourceHandle === 'output' && targetHandle === 'output') {
    showBubbleTip(t('Output cannot connect to output'), 'error');
    return;
  }

  // 检查是否已经存在相同的连接
  if (store.hasConnection(params.source, params.target, sourceHandle, targetHandle)) {
    // 如果已存在相同的连接，显示提示并返回
    showBubbleTip(t('Connection already exists, please do not repeat'), 'error');
    return;
  }
  
  // 检查是否形成自环（节点连接到自己）
  if (params.source === params.target) {
    showBubbleTip(t('A node cannot connect to itself'), 'error');
    return;
  }
  
  const edge = {
    id: `edge-${Date.now()}`,
    source: params.source,
    target: params.target,
    sourceHandle: sourceHandle,
    targetHandle: targetHandle,
    type: 'smoothstep', // 现代平滑线
    animated: true,
    style: { 
      stroke: '#6366f1', 
      strokeWidth: 2.5,
      filter: 'drop-shadow(0 2px 8px #6366f133)'
    },
    markerEnd: {
      type: 'arrowclosed',
      color: '#6366f1'
    }
  };
  
  store.addEdge(edge);
  // 不再自动生成依赖声明（inputs），只保留连线本身
  store.markDirty();
};

// 连接开始处理
const onConnectStart = (event) => {
  
};

// 连接结束处理  
const onConnectEnd = (event) => {
  
};

// 节点拖拽处理
const onNodeDragStop = (event) => {
  store.updateNodePosition(event.node.id, event.node.position);
  store.markDirty();
};

// 删除选中元素
const deleteSelected = () => {
  if (selectedNode.value) {
    store.removeNode(selectedNode.value.id);
    selectedNode.value = null;
  }
  if (selectedEdge.value) {
    store.removeEdge(selectedEdge.value.id);
    selectedEdge.value = null;
  }
  store.markDirty();
};

// 拖放处理
const onDragOver = (event) => {
  event.preventDefault();
  event.dataTransfer.dropEffect = 'move';
};

// 新建节点时自动错开位置，避免重叠
let nodeCount = 0;
const getNextNodePosition = () => {
  const baseX = 100, baseY = 100, offset = 60;
  const x = baseX + (nodeCount % 5) * offset;
  const y = baseY + Math.floor(nodeCount / 5) * offset;
  nodeCount++;
  return { x, y };
};

const onDrop = (event) => {
  event.preventDefault();
  const type = event.dataTransfer.getData('application/vueflow');
  if (!type) return;
  // 获取 vue-flow 容器的 boundingRect
  const container = document.querySelector('.vue-flow-container');
  let position = { x: 100, y: 100 };
  if (container && vueFlowInstance.value && typeof vueFlowInstance.value.project === 'function') {
    const rect = container.getBoundingClientRect();
    const xInContainer = event.clientX - rect.left;
    const yInContainer = event.clientY - rect.top;
    position = vueFlowInstance.value.project({ x: xInContainer, y: yInContainer });
    // 加微小随机偏移，防止重叠
    position.x += Math.random() * 20 - 10;
    position.y += Math.random() * 20 - 10;
  }
  const newNode = {
    id: `${type}-${Date.now()}`,
    type,
    position,
    data: {
      ...getDefaultNodeData(type)
    }
  };
  store.addNode(newNode);
  store.markDirty();
  // 拖拽也加入最近使用
  try {
    let recent = JSON.parse(localStorage.getItem('ai-agent-node-recent') || '[]');
    recent = [type, ...recent.filter(t => t !== type)].slice(0, 12);
    localStorage.setItem('ai-agent-node-recent', JSON.stringify(recent));
    window.dispatchEvent(new Event('recent-node-updated'));
  } catch(e) {}
};

// 获取默认节点数据
const getDefaultNodeData = (type) => {
  // 只返回结构，不做任何参数内容硬编码
  return {
    inputs: {},
    config: {}
  };
};

// 键盘事件处理
const onKeyDown = (event) => {
  if (event.key === 'Delete' || event.key === 'Backspace') {
    deleteSelected();
  }
};

// 生命周期
onMounted(() => {
  
  // 暴露 teleport 目标到全局，供节点组件使用
  window.nodePropertyTeleportTarget = {
    get value() {
      return nodePropertyTeleportTarget.value;
    }
  };
  
  // 添加键盘快捷键
  const handleKeyDown = (event) => {
    // 检查是否在输入框或可编辑元素中
    const isEditingText = event.target.tagName === 'INPUT' || 
                         event.target.tagName === 'TEXTAREA' || 
                         event.target.isContentEditable ||
                         event.target.closest('.form-control') ||
                         event.target.closest('input') ||
                         event.target.closest('textarea');
    
    // 如果在编辑文本，不处理删除键
    if (isEditingText && (event.key === 'Delete' || event.key === 'Backspace')) {
      return;
    }
    
    // Ctrl+Z 撤销
    if (event.ctrlKey && event.key === 'z' && !event.shiftKey) {
      event.preventDefault();
      store.undo();
    }
    // Ctrl+Y 或 Ctrl+Shift+Z 重做
    else if ((event.ctrlKey && event.key === 'y') || (event.ctrlKey && event.shiftKey && event.key === 'Z')) {
      event.preventDefault();
      store.redo();
    }
    // Delete 键删除选中的节点或边（仅当不在编辑状态时）
    else if (event.key === 'Delete' || event.key === 'Backspace') {
      deleteSelected();
    }
  };
  
  document.addEventListener('keydown', handleKeyDown);
  document.addEventListener('fullscreenchange', fullscreenChangeHandler);
  document.addEventListener('webkitfullscreenchange', fullscreenChangeHandler);
  document.addEventListener('mozfullscreenchange', fullscreenChangeHandler);
  document.addEventListener('MSFullscreenChange', fullscreenChangeHandler);
  
  // 清理事件监听器
  onUnmounted(() => {
    document.removeEventListener('keydown', handleKeyDown);
    document.removeEventListener('fullscreenchange', fullscreenChangeHandler);
    document.removeEventListener('webkitfullscreenchange', fullscreenChangeHandler);
    document.removeEventListener('mozfullscreenchange', fullscreenChangeHandler);
    document.removeEventListener('MSFullscreenChange', fullscreenChangeHandler);
  });
  
  // 加载保存的数据
  store.loadFromStorage();
  // 删除 window.openNodeProperties，因为不再需要
  window.vueFlowInstance = vueFlowInstance.value;
});

// 监听数据变化
watch(
  () => [store.nodes, store.edges],
  () => {
    store.saveToStorage();
  },
  { deep: true }
);

// 流程执行操作
const executeFlow = async () => {
  if (isExecuting.value) {
    message.warning(t('Flow is executing, please wait'));
    return;
  }

  try {
    isExecuting.value = true;
    executionResult.value = null;
    executionHistory.value = [];

    const agentName = props.agentId.trim()

    // 执行流程，传递智能体信息
    const result = await flowExecutor.executeFlow(
      store.nodes,
      store.edges,
      { agent_name: agentName }
    );

    executionResult.value = result;
    executionHistory.value = result.history || [];

    if (result.success) {
      // 不再弹出顶部提示，只保留主弹窗
    } else {
      // 不再弹出顶部提示，只保留主弹窗
    }
  } catch (error) {
    message.error(t('Execution error') + `: ${error.message}`);
    } finally {
      isExecuting.value = false;
      // 执行完成后自动切换到执行结果画面
      if (executionResult.value) {
        showExecutionResults.value = true;
      }
    }
};

// 工具栏操作
const resetFlow = () => {
  // 保存当前状态到历史记录，以便撤销
  store.saveToHistory()
  // 重置流程数据
  store.resetFlow()
  // 清空选择状态
  selectedNode.value = null
  selectedEdge.value = null
};

// 删除Redo和验证流程按钮

const toggleSidebar = () => {
  showSidebar.value = !showSidebar.value;
};

// 获取流程数据
const getFlowData = () => {
  return store.getFlowData();
};

// 初始化流程数据
const initFlowData = () => {
  // 始终使用props.initialValue，即使是空对象
  if (props.initialValue !== undefined) {
    store.loadFlowData(props.initialValue)
    return
  }
  
  // 只有在没有props数据时才从localStorage加载
  store.loadFromStorage()
}

// 暴露方法给父组件
defineExpose({
  getFlowData
});

// 删除 updateNodeData 函数，因为不再需要

// 状态提示相关
const showSaveStatus = ref(false);
const saveStatusText = ref('');
let saveStatusTimer = null;

// 监听 hasUnsavedChanges 变化，控制提示显示与自动消失
watch(
  () => store.hasUnsavedChanges,
  (val, oldVal) => {
    // 只有用户有过编辑操作后才显示
    if (oldVal !== undefined) {
      showSaveStatus.value = true;
      saveStatusText.value = val ? t('Unsaved') : t('Saved');
      if (saveStatusTimer) clearTimeout(saveStatusTimer);
      saveStatusTimer = setTimeout(() => {
        showSaveStatus.value = false;
      }, 3000);
    }
  }
);

const showCopyTip = ref(false);

// 复制流程数据到剪贴板
const copyTemplateData = async () => {
  try {
    const text = JSON.stringify({ nodes: nodes.value, edges: edges.value }, null, 2);
    await navigator.clipboard.writeText(text);
    showCopyTip.value = true;
    setTimeout(() => { showCopyTip.value = false; }, 2000);
  } catch (e) {
    message.error(t('Copy failed, please copy manually'));
  }
};

const bubbleTip = ref({ show: false, text: '', timeout: null, type: '' });
const showBubbleTip = (msg, type = '') => {
  bubbleTip.value.text = msg;
  bubbleTip.value.type = type;
  bubbleTip.value.show = true;
  if (bubbleTip.value.timeout) clearTimeout(bubbleTip.value.timeout);
  bubbleTip.value.timeout = setTimeout(() => {
    bubbleTip.value.show = false;
    bubbleTip.value.type = '';
  }, 2000);
};
</script>

<template>
  <div class="ai-agent-flow-builder" :class="{ fullscreen: isFullscreen }" ref="flowBuilderRoot">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <span class="node-count">
          {{ t('Nodes') }}: {{ nodes.length }}  {{ t('Edges') }}: {{ edges.length }}
        </span>
      </div>
      <div class="toolbar-right">
        <n-space :size="6" align="center" class="ni-toolbar" wrap>
          <n-button v-if="store.canUndo" quaternary size="small" type="default" class="ni-btn" :title="t('Undo')" @click="store.undo">
            <i class="fa fa-undo"></i>
            {{ t('Undo') }}
          </n-button>
          <n-button quaternary size="small" type="error" class="ni-btn" @click="resetFlow">
            <i class="fa fa-refresh"></i>
            {{ t('Reset') }}
          </n-button>
          <n-button quaternary size="small" type="info" class="ni-btn" @click="openTemplateData">
            <i class="fa fa-code"></i>
            {{ t('View Data') }}
          </n-button>
          <n-button quaternary size="small" type="info" class="ni-btn" @click="toggleExecutionResults">
            <i class="fa fa-list-alt"></i>
            {{ showExecutionResults ? t('Back to Flow') : t('Execution Results') }}
          </n-button>
          <n-button quaternary size="small" type="success" class="ni-btn" :disabled="isExecuting" @click="executeFlow">
            <i class="fa fa-play"></i>
            {{ isExecuting ? t('Executing...') : t('Execute') }}
          </n-button>
          <n-button quaternary size="small" type="default" class="ni-btn ni-btn-neutral" @click="fitView">
            <i class="fa fa-expand"></i>
            {{ t('Fit View') }}
          </n-button>
          <n-button quaternary size="small" type="success" class="ni-btn" @click="toggleSidebar">
            <i class="fa fa-plus"></i>
            {{ t('Add Node') }}
          </n-button>
          <n-button quaternary size="small" type="default" class="ni-btn ni-btn-neutral" @click="toggleFullscreen">
            <i :class="isFullscreen ? 'fa fa-compress' : 'fa fa-arrows-alt'"></i>
            {{ isFullscreen ? t('Exit Fullscreen') : t('Fullscreen') }}
          </n-button>
        </n-space>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 执行结果全屏显示 -->
      <div v-if="showExecutionResults" class="execution-results-container">
        <ExecutionResults 
          :executionResult="executionResult"
          :executionHistory="executionHistory"
          @close="closeExecutionResults"
        />
      </div>
      
      <!-- 正常内容（当不显示执行结果时） -->
      <template v-else>
        <!-- Vue Flow 容器 -->
        <div class="flow-container">
        <!-- 状态提示：右上角绝对定位 -->
        <div v-if="showSaveStatus" class="status-indicator-fixed">
          <div v-if="store.hasUnsavedChanges" class="unsaved-indicator">
            <i class="fa fa-circle text-warning"></i>
            {{ saveStatusText }}
          </div>
          <div v-else class="saved-indicator">
            <i class="fa fa-check-circle text-success"></i>
            {{ saveStatusText }}
          </div>
        </div>
        <!-- 气泡提示，和保存提示同级同位 -->
        <transition name="fade">
          <div v-if="bubbleTip.show" :class="['bubble-tip-global', bubbleTip.type]">
            <template v-if="bubbleTip.type === 'error'">
              <i class="fa fa-exclamation-circle" style="margin-right:6px;"></i>
            </template>
            <template v-else-if="bubbleTip.type === 'warn'">
              <i class="fa fa-exclamation-triangle" style="margin-right:6px;"></i>
            </template>
            <template v-else>
              <i class="fa fa-check-circle" style="margin-right:6px;"></i>
            </template>
            {{ bubbleTip.text }}
          </div>
        </transition>
        <VueFlow
          v-if="nodeTypesLoaded"
          ref="vueFlowInstance"
          :nodes="nodes"
          :edges="edges"
          :node-types="nodeTypes"
          class="vue-flow-container"
          @node-click="onNodeClick"
          @edge-click="onEdgeClick"
          @pane-click="onPaneClick"
          @connect="onConnect"
          @connect-start="onConnectStart"
          @connect-end="onConnectEnd"
          @node-drag-stop="onNodeDragStop"
          @drop="onDrop"
          @dragover="onDragOver"
          @edit-node="onEditNode"
          :min-zoom="0.2"
          :max-zoom="4"
          nodes-connectable
          nodes-draggable
          edges-updatable
          delete-key-code="Delete"
          :default-edge-options="{
            type: 'smoothstep', // 现代平滑线
            animated: true,
            style: {
              stroke: '#6366f1',
              strokeWidth: 2.5,
              filter: 'drop-shadow(0 2px 8px #6366f133)'
            },
            markerEnd: { type: 'arrowclosed', color: '#6366f1' }
          }"
          :connection-line-type="'smoothstep'"
          :connection-line-style="{ stroke: '#94a3b8', strokeWidth: 2, strokeDasharray: '5,5' }"
          @pane-ready="onPaneReady"
        >
          <!-- 背景 -->
          <Background pattern="dots" :gap="20" />
          
          <!-- 控制面板 -->
          <Controls>
            <ControlButton 
              v-if="hasSelection"
              @click="deleteSelected"
              :title="t('Delete Selected')"
            >
              <i class="fa fa-trash"></i>
            </ControlButton>
          </Controls>
          
          <!-- 小地图 -->
          <MiniMap 
            :node-stroke-width="3"
            :node-color="(node) => {
              return getNodeColor(node.type);
            }"
          />
          
          <!-- 顶部面板 -->
          <!-- Panel position="top-center" class="status-panel" 移除 -->
        </VueFlow>
        
        <!-- 加载提示 -->
        <div v-else class="loading-container">
          <div class="loading-spinner">
            <i class="fa fa-spinner fa-spin"></i>
            <p>正在加载节点类型...</p>
          </div>
        </div>
      </div>
      <!-- 调试：显示 edges 和 nodes 的 JSON -->
      <!-- 模板数据弹窗 -->
      <div v-if="showTemplateData" class="template-data-modal">
        <div class="template-data-content">
          <div class="template-data-header">
            <span>{{ t('Flow Data') }}</span>
            <div style="display: flex; align-items: center; gap: 8px;">
              <button 
                class="copy-btn" 
                @click="copyTemplateData"
                :title="t('Copy')"
              >
                <i class="fa fa-copy"></i>
              </button>
              <button class="close-btn" @click="closeTemplateData">×</button>
            </div>
          </div>
          <pre style="max-height:60vh;overflow:auto;background:#f3f4f6;color:#222;font-size:12px;">
{{ JSON.stringify({ nodes, edges }, null, 2) }}
          </pre>
          <transition name="fade">
            <div v-if="showCopyTip" class="copy-tip">{{ t('Copied') }}</div>
          </transition>
        </div>
        <div class="template-data-mask" @click="closeTemplateData"></div>
      </div>


        <!-- 侧边栏 -->
        <div v-if="showSidebar" class="sidebar">
          <div class="sidebar-content">
            <!-- 只显示节点面板 -->
            <NodePalette class="node-palette" />
          </div>
        </div>

        <!-- 节点属性弹窗 -->
        <!-- 移除 NodeProperties 组件 -->
      </template>
    </div>
  </div>
</template>

<style scoped>
.ai-agent-flow-builder {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #f8fafc;
}
.ai-agent-flow-builder.fullscreen {
  position: fixed !important;
  top: 0; left: 0; right: 0; bottom: 0;
  width: 100vw;
  height: 100vh;
  z-index: 99999;
  background: #f8fafc;
  box-shadow: none;
}

.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #e5e7eb;
  flex-shrink: 0;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.toolbar-left h4 {
  margin: 0;
  font-size: 1.125rem;
  font-weight: 600;
  color: #1f2937;
}

.node-count {
  font-size: 0.875rem;
  color: #6b7280;
}

.toolbar-right {
  display: flex;
  gap: 8px;
}

/* Naive 轻量按钮的额外可读性间距与对齐处理 */
:global(.ni-toolbar .ni-btn) {
  padding: 4px 12px; /* 更舒适的内边距 */
  border-radius: 8px; /* 柔和圆角 */
  min-height: 28px;
  line-height: 1.1;
}
:global(.ni-toolbar) {
  row-gap: 6px;
}

/* 图标与文字保持舒适间距 */
:global(.ni-btn i) {
  margin-right: 6px;
  line-height: 1;
}

/* 悬浮反转：背景 = 原文字色，文字/图标 = 白色 */
:global(.ni-btn.n-button--default-type:hover) {
  background: #475569; /* slate-600 */
  color: #fff !important;
}
:global(.ni-btn.n-button--primary-type:hover) {
  background: #3b82f6; /* blue-500 */
  color: #fff !important;
}
:global(.ni-btn.n-button--info-type:hover) {
  background: #0ea5e9; /* sky-500 */
  color: #fff !important;
}
:global(.ni-btn.n-button--success-type:hover) {
  background: #22c55e; /* green-500 */
  color: #fff !important;
}
:global(.ni-btn.n-button--error-type:hover) {
  background: #ef4444; /* red-500 */
  color: #fff !important;
}

/* 让 Naive UI 的内部 label、icon 继承颜色 */
:global(.ni-btn .n-button__content),
:global(.ni-btn .n-button__icon),
:global(.ni-btn .n-button__label) {
  color: inherit;
}

/* hover 背景反转后也保持圆角与内边距 */
:global(.ni-btn:hover) {
  border-radius: 8px;
}

/* 中性色（黑/深灰）默认态：文字黑色 */
:global(.ni-btn-neutral) { color: #111827; } /* zinc-900 近黑 */
:global(.ni-btn-neutral i) { color: inherit; }
/* 中性色 hover 反转：背景黑，文字白 */
:global(.ni-btn-neutral:hover) {
  background: #111827;
  color: #fff !important;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.execution-results-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* Vue Flow Handle基础样式 - 避免冲突 */
:deep(.vue-flow__handle) {
  width: 14px !important;
  height: 14px !important;
  background: #fff !important;
  border: 2.5px solid #6366f1 !important;
  box-shadow: 0 2px 8px rgba(99,102,241,0.15) !important;
  border-radius: 50% !important;
  cursor: crosshair !important;
  z-index: 10 !important;
  pointer-events: auto !important;
  transition: box-shadow 0.2s, border-color 0.2s;
}

:deep(.vue-flow__handle:hover) {
  box-shadow: 0 0 0 4px #6366f133 !important;
  border-color: #4338ca !important;
}

:deep(.vue-flow__handle.connecting) {
  animation: handle-pulse 1s infinite !important;
  cursor: crosshair !important;
}

:deep(.vue-flow__handle.connectingfrom) {
  animation: handle-pulse 1s infinite !important;
  cursor: crosshair !important;
}

:deep(.vue-flow__handle.connectingto) {
  animation: handle-connecting 0.5s ease-out !important;
  cursor: crosshair !important;
}

@keyframes handle-pulse {
  0% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.3); opacity: 0.8; }
  100% { transform: scale(1); opacity: 1; }
}

@keyframes handle-connecting {
  0% { transform: scale(1); }
  50% { transform: scale(1.4); }
  100% { transform: scale(1.2); }
}

/* 连接线样式优化 */
:deep(.vue-flow__edge.animated path) {
  stroke-dasharray: 5;
  animation: dashdraw 0.5s linear infinite;
}

:deep(.vue-flow__edge.selected path) {
  stroke-width: 3;
}

:deep(.vue-flow__edge:hover path) {
  stroke-width: 3;
}

@keyframes dashdraw {
  to {
    stroke-dashoffset: -10;
  }
}

/* 连接线指示器 */
:deep(.vue-flow__connectionline) {
  stroke: #94a3b8 !important;
  stroke-width: 2 !important;
  stroke-dasharray: 5,5 !important;
}

/* 背景网格优化 */
:deep(.vue-flow__background) {
  background-color: #fafafa;
}

:deep(.vue-flow__background .react-flow__background-pattern) {
  color: #e2e8f0;
}

/* 节点样式全局覆盖 */
:deep(.vue-flow__node) {
  font-size: 14px !important;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif !important;
}

:deep(.vue-flow__node .title) {
  font-size: 14px !important;
  font-weight: 600 !important;
  letter-spacing: 0.3px !important;
}

:deep(.vue-flow__node .form-group label) {
  font-size: 11px !important;
  font-weight: 600 !important;
}

:deep(.vue-flow__node .value) {
  font-size: 13px !important;
  font-weight: 500 !important;
}

.flow-container {
  flex: 1;
  position: relative;
}

.vue-flow-container {
  height: 100%;
  background: #f8fafc;
}

.sidebar {
  width: 360px;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
}

.sidebar-tabs {
  display: flex;
  border-bottom: 1px solid #e5e7eb;
}

.tab-button {
  flex: 1;
  padding: 12px;
  border: none;
  background: transparent;
  cursor: pointer;
  font-size: 0.875rem;
  color: #6b7280;
  transition: all 0.2s;
}

.tab-button.active {
  color: #3b82f6;
  border-bottom: 2px solid #3b82f6;
  background: #f8fafc;
}

.tab-button:hover {
  background: #f3f4f6;
}

.sidebar-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.status-panel {
  background: white;
  border-radius: 6px;
  padding: 8px 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  font-size: 0.875rem;
}

.unsaved-indicator {
  color: #f59e0b;
  display: flex;
  align-items: center;
  gap: 4px;
}

.saved-indicator {
  color: #22c55e;
  display: flex;
  align-items: center;
  gap: 4px;
}

.edge-properties {
  .form-group {
    margin-bottom: 16px;
  }

  .form-group label {
    display: block;
    margin-bottom: 4px;
    font-weight: 500;
    color: #374151;
  }

  .form-control {
    width: 100%;
    padding: 8px;
    border: 1px solid #d1d5db;
    border-radius: 4px;
    font-size: 0.875rem;
  }
}

/* Vue Flow 样式覆盖 */
:deep(.vue-flow__node) {
  font-family: inherit;
}

:deep(.vue-flow__edge) {
  cursor: pointer;
}

:deep(.vue-flow__edge:hover) {
  stroke-width: 3;
}

:deep(.vue-flow__controls) {
  button {
    border: 1px solid #d1d5db;
    background: white;
    color: #374151;
    
    &:hover {
      background: #f3f4f6;
    }
  }
}

:deep(.vue-flow__minimap) {
  border: 1px solid #d1d5db;
  border-radius: 4px;
}

/* 模板数据弹窗样式 */
.template-data-modal {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.template-data-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 32px rgba(0,0,0,0.18);
  padding: 0;
  min-width: 420px;
  max-width: 90vw;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}
.template-data-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  border-bottom: 1px solid #e5e7eb;
  font-weight: 600;
  font-size: 15px;
}
.close-btn {
  background: none;
  border: none;
  font-size: 22px;
  cursor: pointer;
  color: #888;
  margin-left: 12px;
}
.template-data-content pre {
  margin: 0;
  padding: 18px 20px;
  background: #f3f4f6;
  border-radius: 0 0 8px 8px;
  font-size: 12px;
  color: #222;
  flex: 1;
}
.template-data-mask {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.18);
  z-index: -1;
}


.status-indicator-fixed {
  position: absolute;
  top: 18px;
  right: 28px;
  z-index: 20;
  background: white;
  border-radius: 6px;
  padding: 8px 14px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.10);
  font-size: 0.95rem;
  min-width: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: none;
  text-align: center;
}

.copy-btn {
  background: none;
  border: none;
  color: #6B7280;
  font-size: 18px;
  cursor: pointer;
  padding: 2px 6px;
  border-radius: 5px;
  transition: background 0.15s;
}
.copy-btn:hover {
  background: #f3f3f3;
  color: #1fc76f;
}
.copy-tip {
  position: absolute;
  top: 18px;
  right: 60px;
  background: #fff;
  color: #222;
  padding: 8px 20px;
  border-radius: 5px;
  font-size: 13px;
  opacity: 0.92;
  z-index: 10001;
  pointer-events: none;
  box-shadow: 0 2px 8px rgba(0,0,0,0.10);
  transition: opacity 0.2s;
}
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.2s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
.add-node-btn {
  color: #1A1A1A;
  background: #fff;
  transition: background 0.2s, color 0.2s;
}
.add-node-btn:hover, .add-node-btn:focus {
  background: #1fc76f;
  color: #fff;
  border-color: #1fc76f;
}
.bubble-tip-global {
  position: absolute;
  top: 18px;
  right: 28px;
  z-index: 100000;
  background: #fff;
  color: #6B7280; /* 默认红色，符合错误提示 */
  font-size: 0.95rem;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.10);
  padding: 8px 14px;
  min-width: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: none;
  text-align: center;
  font-weight: 500;
  transition: opacity 0.18s;
}
.bubble-tip-global.warn {
  color: #f59e0b;
}
.bubble-tip-global.error {
  color: #ef4444;
}
.bubble-tip-global.success {
  color: #22c55e;
}
.ai-agent-flow-builder.fullscreen .bubble-tip-global {
  z-index: 100000;
}

/* 加载提示样式 */
.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 400px;
}

.loading-spinner {
  text-align: center;
  color: #6b7280;
}

.loading-spinner i {
  font-size: 24px;
  margin-bottom: 12px;
  display: block;
}

.loading-spinner p {
  margin: 0;
  font-size: 14px;
}
</style> 