import { useEffect, useState, useRef, useCallback } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { Layout, Button, Space, message, Spin, Typography, Modal } from 'antd'
import { ArrowLeftOutlined, UnorderedListOutlined } from '@ant-design/icons'

import { projectService } from '@/services/projectService'
import { useProjectStore } from '@/stores/projectStore'
import { ContextPanel } from '@/components/Workspace/ContextPanel'
import { SmartCanvas } from '@/components/Workspace/SmartCanvas'
import { DirectorInbox } from '@/components/Workspace/DirectorInbox'
import { EpisodeSidebar } from '@/components/Workspace/EpisodeSidebar'
import { Episode } from '@/services/projectService'

const { Header, Sider } = Layout;
const { Text } = Typography;

export const ProjectWorkspace: React.FC = () => {
  const navigate = useNavigate()
  const { id: projectId } = useParams<{ id: string }>()

  // 调试：确认组件已加载
  console.log('=== ProjectWorkspace component loaded ===')
  console.log('projectId:', projectId)

  const [project, setProject] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [streaming, setStreaming] = useState(false)
  const [canvasContent, setCanvasContent] = useState<string>('')
  const [agentStatus, setAgentStatus] = useState<'idle' | 'planning' | 'writing' | 'reviewing'>('idle')
  const [agentPlan, setAgentPlan] = useState<string[]>([])
  const [inboxItems, setInboxItems] = useState<any[]>([])
  const [chatHistory, setChatHistory] = useState<{role: 'user' | 'agent', content: string}[]>([])
  const [annotations, setAnnotations] = useState<any[]>([])
  const [activeStates, setActiveStates] = useState<any[]>([
    { type: 'time', value: '初始状态' },
    { type: 'location', value: '未知地点' }
  ])

  // 记忆库状态
  const [memoryItems, setMemoryItems] = useState<any[]>([])

  // 剧集相关状态
  const [currentEpisode, setCurrentEpisode] = useState<Episode | null>(null)
  const [showEpisodeSidebar, setShowEpisodeSidebar] = useState(true)

  // 布局宽度状态 - 优化后的默认比例
  const [sidebarWidth, setSidebarWidth] = useState(260);
  const [contextWidth, setContextWidth] = useState(300);
  const [canvasWidth, setCanvasWidth] = useState(600);

  // 拖拽相关 Refs
  const isResizingRef = useRef<'sidebar' | 'context' | 'canvasRight' | null>(null);
  const startXRef = useRef(0);
  const startWidthRef = useRef(0);

  // 拖拽处理函数
  const handleMouseMove = useCallback((e: MouseEvent) => {
    if (!isResizingRef.current) return;

    const deltaX = e.clientX - startXRef.current;

    if (isResizingRef.current === 'sidebar') {
      const newWidth = Math.max(200, Math.min(500, startWidthRef.current + deltaX));
      console.log('Resizing sidebar:', newWidth);
      setSidebarWidth(newWidth);
    } else if (isResizingRef.current === 'context') {
      const newWidth = Math.max(250, Math.min(600, startWidthRef.current + deltaX));
      console.log('Resizing context:', newWidth);
      setContextWidth(newWidth);
    } else if (isResizingRef.current === 'canvasRight') {
      // Canvas 右侧手柄：向左拖动增加宽度
      const newWidth = Math.max(300, Math.min(900, startWidthRef.current - deltaX));
      console.log('Resizing canvas:', newWidth);
      setCanvasWidth(newWidth);
    }
  }, []);

  const handleMouseUp = useCallback(() => {
    console.log('=== handleMouseUp called, was resizing:', isResizingRef.current);
    isResizingRef.current = null;
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
    document.body.style.userSelect = '';
    document.body.style.cursor = '';
  }, [handleMouseMove]);

  const startResize = (type: 'sidebar' | 'context' | 'canvasRight', e: React.MouseEvent) => {
    e.preventDefault();
    console.log('=== startResize called ===', type, e.clientX);
    isResizingRef.current = type;
    startXRef.current = e.clientX;
    startWidthRef.current = type === 'sidebar' ? sidebarWidth
                          : type === 'context' ? contextWidth
                          : canvasWidth;

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
    document.body.style.userSelect = 'none';
    document.body.style.cursor = 'col-resize';
  };

  // AI 辅助相关状态
  const [availableSkills, setAvailableSkills] = useState<any[]>([])

  const [wsConnected, setWsConnected] = useState(false);

  // WebSocket refs
  const wsRef = useRef<WebSocket | null>(null);
  const reconnectTimeoutRef = useRef<number | null>(null);

  const loadProject = async () => {
    if (!projectId) {
      setLoading(false);
      return;
    }

    setLoading(true)
    try {
      const data = await projectService.getProject(projectId)
      setProject(data)

      // 加载可用的 Skills
      await loadAvailableSkills()
    } catch (error) {
      message.error(`加载项目失败: ${(error as Error).message}`)
    } finally {
      setLoading(false)
    }
  }

  // 加载可用的 Skills
  const loadAvailableSkills = async () => {
    try {
      const response = await fetch('/api/v1/ai-assistant/available-skills')
      if (response.ok) {
        const data = await response.json()
        // 将分类的 skills 转换为列表格式
        const skillsList: any[] = []
        Object.entries(data.skills || {}).forEach(([category, skills]: [string, any]) => {
          skills.forEach((skill: any) => {
            skillsList.push({
              ...skill,
              category
            })
          })
        })
        setAvailableSkills(skillsList)
      }
    } catch (error) {
      console.error('加载 Skills 失败:', error)
      // 失败时设置空数组，不影响其他功能
      setAvailableSkills([])
    }
  }

  // 加载剧集内容
  const loadEpisodeContent = async (episodeNumber: number) => {
    if (!projectId) return;
    try {
      const response = await projectService.getEpisode(projectId, episodeNumber);
      const episode = response.data || response;
      console.log('[ProjectWorkspace] Loading episode:', episode);
      setCurrentEpisode(episode);
      setCanvasContent(episode.content || '');
      console.log('Loaded episode content:', episode.id, episode.content?.length || 0, 'chars');
    } catch (error) {
      message.error(`加载剧集内容失败: ${(error as Error).message}`);
    }
  }

  useEffect(() => {
    loadProject()

    return () => {
        if (reconnectTimeoutRef.current) {
            clearTimeout(reconnectTimeoutRef.current);
        }
        if (wsRef.current) {
            wsRef.current.close();
        }
    }
  }, [projectId])

  // 当项目加载完成后，自动选择并加载第一集
  useEffect(() => {
    if (project && !loading && projectId && !currentEpisode) {
      // 获取剧集列表并自动选择第一集
      const loadFirstEpisode = async () => {
        try {
          const response = await projectService.listEpisodes(projectId);
          const episodes = response.data || response;
          if (episodes && episodes.length > 0) {
            // 找到第一个pending或completed状态的剧集，优先pending状态
            const firstEpisode = episodes.find((ep: any) => ep.status === 'pending') ||
                                 episodes.find((ep: any) => ep.status === 'completed') ||
                                 episodes[0];
            if (firstEpisode) {
              await loadEpisodeContent(firstEpisode.number);
            }
          }
        } catch (error) {
          console.error('加载第一集失败:', error);
          // 如果加载失败，创建一个临时的第一集对象作为默认显示
          console.log('使用临时剧集对象显示');
          setCurrentEpisode({
            id: 'temp',
            projectId: projectId,
            number: 1,
            title: '第1集',
            status: 'pending',
            content: '',
            issues: [],
            createdAt: new Date().toISOString()
          });
        }
      };

      loadFirstEpisode();
    }
  }, [project, loading, projectId]); // 移除currentEpisode依赖，避免无限循环

  // WebSocket Connection Logic
  const connectWebSocket = useCallback(() => {
    if (!projectId) return;

    // Close existing connection if any
    if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
      console.log('Closing existing WebSocket connection');
      wsRef.current.close();
    }

    // Use relative URL which will be proxied by Vite
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const host = window.location.host; // e.g. localhost:5173
    const wsUrl = `${protocol}//${host}/ws/projects/${projectId}/execute`;

    console.log('Connecting to WebSocket:', wsUrl);
    const ws = new WebSocket(wsUrl);

    ws.onopen = () => {
      console.log('WebSocket Connected');
      setWsConnected(true);
      message.success('已连接到 Agent Runtime');
    };

    ws.onmessage = (event) => {
      try {
        const msg = JSON.parse(event.data);
        handleWebSocketMessage(msg);
      } catch (e) {
        console.error('Failed to parse WS message:', e);
      }
    };

    ws.onclose = () => {
      console.log('WebSocket Disconnected');
      setWsConnected(false);
      // Clear ref to allow reconnection
      if (wsRef.current === ws) {
        wsRef.current = null;
      }
    };

    ws.onerror = (error) => {
      console.error('WebSocket Error:', error);
      // Don't close here, let onclose handle it
    };

    wsRef.current = ws;
  }, [projectId]); // Only depend on projectId

  useEffect(() => {
    if (projectId && !loading) {
        connectWebSocket();
    }
    // Cleanup on unmount or projectId change
    return () => {
        if (reconnectTimeoutRef.current) {
            clearTimeout(reconnectTimeoutRef.current);
        }
        if (wsRef.current) {
            wsRef.current.close();
            wsRef.current = null;
        }
    };
  }, [projectId, loading, connectWebSocket]);

  const handleInboxAction = (itemId: string, action: 'approve' | 'reject') => {
    // Optimistic update
    setInboxItems(prev => prev.filter(item => item.id !== itemId));
    
    // Send to backend
    if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
        wsRef.current.send(JSON.stringify({
            type: 'inbox_action',
            itemId,
            action
        }));
    }
    
    message.success(action === 'approve' ? '已批准' : '已拒绝');
  };

  const handleWebSocketMessage = async (msg: any) => {
    console.log('Received:', msg);
    
    switch (msg.type) {
        case 'connected':
            break;
        case 'history':
            if (msg.messages) {
                setChatHistory(msg.messages);
            }
            break;
        case 'thinking':
            // Optional: show thinking indicator in chat
            break;
        case 'text':
            setChatHistory(prev => {
                const lastMsg = prev[prev.length - 1];
                // 如果上一条消息也是 agent 发送的，则认为是流式输出，追加内容
                if (lastMsg && lastMsg.role === 'agent') {
                    const newHistory = [...prev];
                    newHistory[newHistory.length - 1] = {
                        ...lastMsg,
                        content: lastMsg.content + msg.content
                    };
                    return newHistory;
                }
                // 否则添加新消息
                return [...prev, { role: 'agent', content: msg.content }];
            });
            break;
        case 'plan_update':
            if (msg.plan) {
                setAgentPlan(msg.plan);
            }
            if (msg.status) {
                setAgentStatus(msg.status);
            }
            break;
        case 'review_request':
            setInboxItems(prev => [...prev, {
                id: msg.id || Date.now().toString(),
                type: 'review',
                title: msg.title || '需要审核',
                description: msg.description,
                status: 'pending',
                timestamp: Date.now()
            }]);
            break;
        case 'review_complete':
            // 处理审核卡片推送
            const reviewData = msg.data || {};
            setInboxItems(prev => [...prev, {
                id: `review_${reviewData.episode_number}_${Date.now()}`,
                type: 'review_card',
                title: `EP${reviewData.episode_number} 审核完成`,
                description: `质量评分: ${reviewData.overall_score?.toFixed(1) || 0} | ${reviewData.passed ? '通过' : '未通过'}`,
                status: reviewData.passed ? 'approved' : 'needs-review',
                timestamp: Date.now(),
                reviewData: reviewData
            }]);

            // 如果有严重问题，显示通知
            if (reviewData.high_severity_count > 0) {
                message.warning(
                    `EP${reviewData.episode_number} 发现 ${reviewData.high_severity_count} 个严重问题，请查看审核详情`
                );
            } else if (reviewData.passed) {
                message.success(
                    `EP${reviewData.episode_number} 审核通过，质量评分: ${reviewData.overall_score?.toFixed(1) || 0}`
                );
            }
            break;
        case 'memory_hit':
            // 添加到记忆库
            if (msg.data) {
                setMemoryItems(prev => [...prev, {
                    type: msg.data.memory_type || 'timeline',
                    title: msg.data.title || '记忆更新',
                    description: msg.data.description || JSON.stringify(msg.data.data),
                    timestamp: Date.now()
                }]);
            }
            break;
        case 'memory_update':
            // 从 update_memory 工具触发的记忆更新
            if (msg.data) {
                setMemoryItems(prev => [...prev, {
                    type: msg.data.type || msg.data.memory_type || 'timeline',
                    title: msg.data.title || '记忆更新',
                    description: msg.data.description || '',
                    timestamp: msg.data.timestamp || Date.now(),
                    character: msg.data.character,
                    state: msg.data.state
                }]);
            }
            break;
        case 'annotation_add':
            setAnnotations(prev => [...prev, msg.annotation]);
            break;
        case 'context_update':
            if (msg.states) {
                setActiveStates(msg.states);
            }
            break;
        case 'tool_call':
            const toolData = msg.data || {};
            const toolName = toolData.name || msg.name;

            if (toolName === 'update_canvas' || toolName === 'write_file') {
                setStreaming(true);
                setAgentStatus('writing');
                // 更新本地剧集状态为创作中
                setCurrentEpisode(prev => prev ? { ...prev, status: 'writing' } : null);
            } else {
                setAgentStatus('planning');
            }
            break;
        case 'tool_result':
            setStreaming(false);
            break;
        case 'canvas_update':
            if (msg.content) {
                setCanvasContent(msg.content);
                // 自动保存到当前剧集
                if (currentEpisode && currentEpisode.id && projectId) {
                    // 调用 API 保存到后端
                    projectService.updateEpisode(projectId, currentEpisode.number, {
                        content: msg.content,
                        status: 'draft'
                    }).then(() => {
                        console.log('Content auto-saved to episode:', currentEpisode.id);
                        // 更新本地剧集状态为草稿
                        setCurrentEpisode(prev => prev ? { ...prev, status: 'draft' } : null);
                        // 刷新剧集列表
                        useProjectStore.getState().fetchEpisodes(projectId);
                    }).catch((error) => {
                        console.error('Failed to auto-save content:', error);
                    });
                }
            }
            break;
        case 'episode_saved':
            // Agent 保存剧集后的确认
            message.success(`剧集 ${msg.episode_number || ''} 已自动保存`);
            // 刷新剧集列表
            if (projectId) {
                useProjectStore.getState().fetchEpisodes(projectId);
            }
            // 如果保存的是当前剧集，更新画布内容
            if (currentEpisode && currentEpisode.number === msg.episode_number) {
                // 重新获取剧集内容
                loadEpisodeContent(currentEpisode.number);
            }
            break;
        case 'episode_updated':
            // 剧集信息更新（如标题）
            console.log('[ProjectWorkspace] episode_updated:', msg.data);
            if (msg.data) {
                // 1. 本地更新 Store 中的剧集列表
                useProjectStore.getState().updateEpisodeInList(msg.data);
                
                // 2. 如果更新的是当前剧集，同步更新当前剧集状态
                if (currentEpisode && msg.data.number === currentEpisode.number) {
                    setCurrentEpisode(prev => ({ ...prev, ...msg.data } as Episode));
                }
            }
            break;
        case 'done':
            setAgentStatus('idle');
            setStreaming(false);
            break;
        case 'error':
            message.error(msg.data?.message || 'Unknown error');
            setAgentStatus('idle');
            break;
    }
  };

  const handleDirectorMessage = (msg: string) => {
    console.log('=== handleDirectorMessage called ===', msg);

    // 立即更新状态 - 显示停止按钮
    if (msg.includes('开始') || msg.includes('生成') || msg.includes('创作') || msg.includes('辅助')) {
      setAgentStatus('planning');
      // 如果是开始创作，更新本地剧集状态为创作中
      if (msg.includes('创作') || msg.includes('完整内容')) {
        setCurrentEpisode(prev => prev ? { ...prev, status: 'writing' } : null);
      }
    }

    // Optimistically update chat history
    setChatHistory(prev => [...prev, { role: 'user', content: msg }]);

    // Send message to backend via WebSocket
    if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
        const messagePayload = JSON.stringify({
            type: 'chat_message',
            content: msg,
            episodeNumber: currentEpisode?.number,
            episodeTitle: currentEpisode?.title
        });
        console.log('Sending message:', messagePayload);

        wsRef.current.send(messagePayload);
        console.log('Message sent successfully');
    } else {
        console.error('WebSocket not ready');
        message.error('Agent 连接未就绪');
        setAgentStatus('idle');
    }
  }

  // 停止 Agent 处理函数
  const handleStopAgent = () => {
    console.log('=== handleStopAgent called ===');

    if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
        const stopPayload = JSON.stringify({
            type: 'stop_agent'
        });
        wsRef.current.send(stopPayload);
        console.log('Stop command sent');

        // 立即更新 UI 状态
        setAgentStatus('idle');
        setStreaming(false);

        // 添加系统消息到聊天记录
        setChatHistory(prev => [...prev, {
            role: 'agent',
            content: '⚠️ Agent 已被用户停止'
        }]);

        message.info('Agent 已停止');
    } else {
        console.error('WebSocket not ready');
        message.error('无法停止：Agent 连接未就绪');
    }
  }

  // 画布内容变更处理
  const handleContentChange = (content: string) => {
    setCanvasContent(content);
  }

  // 画布内容保存处理
  const handleContentSave = async (content: string) => {
    if (!currentEpisode || !projectId) {
      message.warning('请先选择要保存的剧集');
      return;
    }

    try {
      // 调用后端 API 保存剧集内容
      await projectService.updateEpisode(projectId, currentEpisode.number, {
        content: content,
        status: 'draft'
      });
      message.success('内容已保存');

      // 刷新剧集列表
      useProjectStore.getState().fetchEpisodes(projectId);
    } catch (error) {
      message.error(`保存失败: ${(error as Error).message}`);
    }
  }

  // 确认剧集完成处理
  const handleConfirmComplete = async () => {
    if (!currentEpisode || !projectId) {
      message.warning('请先选择要完成的剧集');
      return;
    }

    // 确认对话框
    Modal.confirm({
      title: '确认完成剧集',
      content: `确认将《${currentEpisode.title || `第${currentEpisode.number}集`}》标记为已完成状态？完成后将不能再编辑内容。`,
      okText: '确认完成',
      cancelText: '取消',
      okType: 'primary',
      okButtonProps: { style: { backgroundColor: '#52c41a', borderColor: '#52c41a' } },
      onOk: async () => {
        try {
          // 调用后端 API 更新剧集状态为 completed
          await projectService.updateEpisode(projectId, currentEpisode.number, {
            content: canvasContent,
            status: 'completed'
          });
          message.success('剧集已标记为完成');

          // 更新当前剧集状态
          setCurrentEpisode(prev => prev ? { ...prev, status: 'completed' } : null);

          // 刷新剧集列表
          useProjectStore.getState().fetchEpisodes(projectId);
        } catch (error) {
          message.error(`操作失败: ${(error as Error).message}`);
        }
      }
    });
  }

  // 剧集标题变更处理
  const handleTitleChange = async (newTitle: string) => {
    if (!currentEpisode || !projectId) return;

    try {
      // 1. 发送 WebSocket 消息通知后端更新标题
      if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
        wsRef.current.send(JSON.stringify({
          type: 'update_episode_title',
          episodeNumber: currentEpisode.number,
          title: newTitle
        }));
      }

      // 2. 调用 API 更新标题
      const response = await projectService.updateEpisode(projectId, currentEpisode.number, {
        title: newTitle
      });
      
      const updatedEpisode = response.data || response;
      
      // 3. 本地同步更新状态
      setCurrentEpisode(updatedEpisode);
      
      // 4. 刷新剧集列表同步显示
      useProjectStore.getState().updateEpisodeInList(updatedEpisode);
      
      message.success('标题已更新');
    } catch (error) {
      console.error('Failed to update title:', error);
      message.error('更新标题失败');
    }
  }

  // AI 辅助修改处理
  const handleAIAssist = async (content: string, options?: { skills?: any[]; customPrompt?: string; injectAgent?: boolean }) => {
    if (!currentEpisode || !projectId) {
      message.warning('请先选择要修改的剧集');
      return;
    }

    // 如果启用了 Agent 注入，通过 WebSocket 发送请求（用户看不到注入内容）
    if (options?.injectAgent !== false) {
      // 立即更新状态，显示停止按钮
      setAgentStatus('planning');

      // 构建优化的提示词，确保Agent使用write_to_canvas工具
      let assistPrompt = '请帮我优化当前剧集内容。\n\n';

      // 如果有自定义提示词，添加到前面
      if (options?.customPrompt) {
        assistPrompt = `${options.customPrompt}\n\n`;
      }

      assistPrompt += `当前剧集：EP${currentEpisode.number} ${currentEpisode.title ? '- ' + currentEpisode.title : ''}\n\n`;

      // 添加当前内容摘要
      assistPrompt += `当前内容（约${content.length}字）：\n${content.substring(0, 1000)}${content.length > 1000 ? '...' : ''}\n\n`;

      // 如果有选择的 Skills，添加到提示中
      if (options?.skills && options.skills.length > 0) {
        assistPrompt += '请应用以下 Skills 指导进行优化：\n';
        options.skills.forEach(skill => {
          assistPrompt += `- ${skill.name}: ${skill.description}\n`;
        });
        assistPrompt += '\n';
      }

      assistPrompt += `请优化上述剧集内容，并使用 write_to_canvas 工具将完整的优化后内容直接更新到画布上（append=false，完全替换）。\n\n`;
      assistPrompt += `重要：请直接调用 write_to_canvas(content="优化后的完整内容", append=false) 工具来更新画布，不要只输出文本。`;

      // 构建用户友好的显示消息
      let displayMessage = 'AI 辅助修改';
      if (options?.customPrompt) {
        displayMessage += `：${options.customPrompt}`;
      }
      if (options?.skills && options.skills.length > 0) {
        const skillNames = options.skills.map(s => s.name).join('、');
        displayMessage += `\n应用 Skills：${skillNames}`;
      }

      // 先在聊天记录中显示用户友好的消息
      setChatHistory(prev => [...prev, { role: 'user', content: displayMessage }]);

      // 通过 WebSocket 发送 AI 辅助请求给 Agent（内部 prompt）
      if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
        wsRef.current.send(JSON.stringify({
          type: 'chat_message',
          content: assistPrompt
        }));
      } else {
        message.error('Agent 连接未就绪');
        setAgentStatus('idle');
      }
    } else {
      // 否则直接调用 AI 辅助 API
      try {
        message.loading('AI 正在辅助修改中...', 0)
        const response = await fetch('/api/v1/ai-assistant/optimize-episode', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            projectId,
            episodeNumber: currentEpisode.number,
            content,
            skills: options?.skills,
            customPrompt: options?.customPrompt
          })
        })

        if (response.ok) {
          const data = await response.json()
          if (data.success && data.optimizedContent) {
            setCanvasContent(data.optimizedContent)
            message.success('AI 辅助修改完成')
          } else {
            message.error('AI 辅助修改失败')
          }
        } else {
          message.error('AI 辅助请求失败')
        }
      } catch (error) {
        console.error('AI 辅助失败:', error)
        message.error('AI 辅助请求出错')
      } finally {
        message.destroy()
      }
    }
  }

  if (loading) {
    return (
      <div style={{ padding: '24px', textAlign: 'center', marginTop: '100px' }}>
        <Spin size="large" tip="正在初始化数字化片场..." />
      </div>
    )
  }

  if (!project) {
    return (
      <div style={{ padding: '24px', textAlign: 'center', marginTop: '100px' }}>
        <Text type="danger">项目加载失败或不存在</Text>
        <br />
        <Button onClick={() => navigate('/projects')} style={{ marginTop: '16px' }}>
          返回项目列表
        </Button>
      </div>
    )
  }

  return (
    <Layout style={{ height: '100vh', background: '#f5f5f5' }}>
      <Header style={{
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        padding: '0 24px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
        height: '56px'
      }}>
        <Space>
          <Button
            type="text"
            icon={<ArrowLeftOutlined style={{ color: '#fff' }} />}
            onClick={() => navigate('/projects')}
            style={{ color: '#fff' }}
          />
          <Text strong style={{ fontSize: '18px', color: '#fff' }}>{project?.name}</Text>
          <div style={{
            background: 'rgba(255,255,255,0.2)',
            padding: '4px 12px',
            borderRadius: '12px',
            fontSize: '12px',
            color: '#fff'
          }}>
            {wsConnected ? '● Agent 在线' : '○ Agent 离线'}
          </div>
          <Button
            type="text"
            icon={<UnorderedListOutlined />}
            onClick={() => setShowEpisodeSidebar(!showEpisodeSidebar)}
            style={{
              color: '#fff',
              background: showEpisodeSidebar ? 'rgba(255,255,255,0.2)' : 'transparent',
              borderRadius: '6px'
            }}
          >
            剧集列表
          </Button>
        </Space>

        <Space>
          <Button style={{ borderRadius: '6px' }}>导出剧本</Button>
          <Button type="primary" style={{
            background: '#fff',
            color: '#667eea',
            borderRadius: '6px',
            border: 'none'
          }}>
            发布
          </Button>
        </Space>
      </Header>

      <Layout style={{ display: 'flex', flexDirection: 'row', overflow: 'hidden', background: '#fafafa' }}>
        {/* 剧集管理侧边栏 */}
        {showEpisodeSidebar && (
          <>
            <Sider width={sidebarWidth} style={{
              background: '#fff',
              borderRight: '1px solid #e8e8e8',
              flexShrink: 0,
              boxShadow: '2px 0 8px rgba(0,0,0,0.04)'
            }}>
              <EpisodeSidebar
                projectId={projectId!}
                onEpisodeSelect={(episode) => {
                  loadEpisodeContent(episode.number);
                }}
                currentEpisodeId={currentEpisode?.id}
                onSendMessage={handleDirectorMessage}
              />
            </Sider>
            {/* 拖拽手柄 - Sidebar */}
            <div
              style={{
                width: '4px',
                cursor: 'col-resize',
                backgroundColor: '#e8e8e8',
                height: '100%',
                zIndex: 1000,
                transition: 'all 0.2s',
                flexShrink: 0,
                userSelect: 'none',
                position: 'relative'
              }}
              onMouseDown={(e) => startResize('sidebar', e)}
              onMouseEnter={(e) => {
                e.currentTarget.style.backgroundColor = '#667eea';
                e.currentTarget.style.width = '6px';
                e.currentTarget.style.boxShadow = '0 0 8px rgba(102, 126, 234, 0.4)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = '#e8e8e8';
                e.currentTarget.style.width = '4px';
                e.currentTarget.style.boxShadow = 'none';
              }}
            />
          </>
        )}

        {/* 左侧：Context Panel */}
        <ContextPanel
          project={project}
          loading={loading}
          activeStates={activeStates}
          memoryItems={memoryItems}
          width={contextWidth}
          onNavigateToSettings={() => navigate(`/projects/${projectId}`, { state: { activeTab: 'global-generation' } })}
        />

        {/* 拖拽手柄 - Context/Canvas 分隔线 */}
        <div
          style={{
            width: '4px',
            cursor: 'col-resize',
            backgroundColor: '#e8e8e8',
            height: '100%',
            zIndex: 1000,
            transition: 'all 0.2s',
            flexShrink: 0,
            userSelect: 'none',
            position: 'relative'
          }}
          onMouseDown={(e) => startResize('context', e)}
          onMouseEnter={(e) => {
            e.currentTarget.style.backgroundColor = '#667eea';
            e.currentTarget.style.width = '6px';
            e.currentTarget.style.boxShadow = '0 0 8px rgba(102, 126, 234, 0.4)';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.backgroundColor = '#e8e8e8';
            e.currentTarget.style.width = '4px';
            e.currentTarget.style.boxShadow = 'none';
          }}
        />

        {/* 中间：Smart Canvas */}
        <div style={{
          width: canvasWidth,
          flexShrink: 0,
          display: 'flex',
          flexDirection: 'column',
          background: '#fff',
          boxShadow: '0 0 20px rgba(0,0,0,0.05)'
        }}>
          <SmartCanvas
            content={canvasContent}
            streaming={streaming}
            annotations={annotations}
            episodeTitle={currentEpisode?.title || (currentEpisode?.number ? `第${currentEpisode.number}集` : '未命名草稿')}
            episodeNumber={currentEpisode?.number || null}
            episodeStatus={currentEpisode?.status as 'pending' | 'draft' | 'writing' | 'completed' | undefined}
            onStartGenerate={() => {
              handleDirectorMessage(`开始生成第${currentEpisode?.number}集大纲`);
            }}
            onStartWriting={() => {
              handleDirectorMessage(`开始创作第${currentEpisode?.number}集完整内容`);
            }}
            onContentChange={handleContentChange}
            onContentSave={handleContentSave}
            onAIAssist={handleAIAssist}
            onTitleChange={handleTitleChange}
            onConfirmComplete={handleConfirmComplete}
            availableSkills={availableSkills}
            projectId={projectId}
          />
        </div>

        {/* Canvas 右侧拖拽手柄 */}
        <div
          style={{
            width: '4px',
            cursor: 'col-resize',
            backgroundColor: '#e8e8e8',
            height: '100%',
            zIndex: 1000,
            transition: 'all 0.2s',
            flexShrink: 0,
            userSelect: 'none',
            position: 'relative'
          }}
          onMouseDown={(e) => startResize('canvasRight', e)}
          onMouseEnter={(e) => {
            e.currentTarget.style.backgroundColor = '#667eea';
            e.currentTarget.style.width = '6px';
            e.currentTarget.style.boxShadow = '0 0 8px rgba(102, 126, 234, 0.4)';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.backgroundColor = '#e8e8e8';
            e.currentTarget.style.width = '4px';
            e.currentTarget.style.boxShadow = 'none';
          }}
        />

        {/* 右侧：Director Inbox */}
        <DirectorInbox
            onSendMessage={handleDirectorMessage}
            onStopAgent={handleStopAgent}
            onInboxAction={handleInboxAction}
            onNavigateToReview={(episodeNum) => navigate(`/projects/${projectId}/review/results?episode=${episodeNum}`)}
            agentStatus={agentStatus}
            agentPlan={agentPlan}
            inboxItems={inboxItems}
            chatHistory={chatHistory}
        />
      </Layout>
    </Layout>
  )
}
