import React, { useState, useEffect, useRef } from 'react'; import { Film, Mic, Volume2, Square, Play, RefreshCw, ArrowUp, ArrowDown, Copy, Plus, Trash2, Sparkles, Wand2, Code2, Download, Smartphone, Monitor, Square as SquareIcon, Image as ImageIcon, Globe, Search, FolderOpen, Clock, CheckCircle2, Sliders, History, Cloud, Laptop, X, Lock, Link2, LayoutTemplate, Zap, Scissors, Tag, } from 'lucide-react'; import { api } from '../api'; import type { Project, ScenePacket, AssetItem, BrandKit, FrozenRecipe, AIProviderProfile, RenderJob, AspectRatio, SceneRole, } from '@olokaflow/shared'; import { Button, Badge } from './ui/primitives'; interface Props { projects: Project[]; activeProject: Project | null; catalog: any; brands: BrandKit[]; recipes: FrozenRecipe[]; profiles: AIProviderProfile[]; assets: AssetItem[]; onSelectProject: (id: string) => void; onRefreshAll: () => void; } const SCENE_ROLES: SceneRole[] = [ 'Hook', 'Problem', 'Product_Intro', 'Key_Feature', 'Benefits', 'Data_Proof', 'Social_Proof', 'CTA', ]; export const StudioWorkspaceView: React.FC = ({ projects, activeProject, catalog, brands, recipes, profiles, assets, onSelectProject, onRefreshAll, }) => { // New Project Creation Form State const [showCreateModal, setShowCreateModal] = useState(!activeProject); const [prompt, setPrompt] = useState(''); const [title, setTitle] = useState(''); const [aspectRatio, setAspectRatio] = useState('9:16'); const [creationMode, setCreationMode] = useState<'auto' | 'storyboard_review'>('auto'); const [framePresetId, setFramePresetId] = useState('editorial-clean-light'); const [voiceId, setVoiceId] = useState('Hải Đăng'); const [voiceSpeed, setVoiceSpeed] = useState(1.0); const [bgmTrackId, setBgmTrackId] = useState('bgm-corporate-pulse'); const [brandKitId, setBrandKitId] = useState(''); const [recipeId, setRecipeId] = useState(''); const [manualAssetLock, setManualAssetLock] = useState(false); const [overrideDirectorProfileId, setOverrideDirectorProfileId] = useState(''); const [overrideCoderProfileId, setOverrideCoderProfileId] = useState(''); const [creating, setCreating] = useState(false); // Active Studio State const [selectedSceneIdx, setSelectedSceneIdx] = useState(0); const [localScenes, setLocalScenes] = useState([]); const [scenesDirty, setScenesDirty] = useState(false); const [savingScenes, setSavingScenes] = useState(false); const [busySceneAction, setBusySceneAction] = useState(null); // AI Copilot Edit State const [editPrompt, setEditPrompt] = useState(''); const [editTargetIdx, setEditTargetIdx] = useState('all'); const [editingBusy, setEditingBusy] = useState(false); const [lastEditSummary, setLastEditSummary] = useState(''); // Live SSE Progress & Render State const [liveProgress, setLiveProgress] = useState<{ stage: string; progress: number; message: string; } | null>(null); const [versions, setVersions] = useState< Array<{ id: string; versionNum: number; label: string; createdAt: string }> >([]); const [renderJobs, setRenderJobs] = useState([]); const [renderingProvider, setRenderingProvider] = useState<'modal' | 'local'>('modal'); const [startingRender, setStartingRender] = useState(false); const [iframeKey, setIframeKey] = useState(1); // Modals: Media Picker & HTML Code Inspector const [mediaModalSceneIdx, setMediaModalSceneIdx] = useState(null); const [mediaModalTab, setMediaModalTab] = useState<'ai_gen' | 'url_scrape' | 'web_search' | 'library'>('library'); const [modalImagePrompt, setModalImagePrompt] = useState(''); const [modalScrapeUrl, setModalScrapeUrl] = useState(''); const [modalWebQuery, setModalWebQuery] = useState(''); const [modalMediaBusy, setModalMediaBusy] = useState(false); const [modalMediaMessage, setModalMediaMessage] = useState(''); const [showCodeModal, setShowCodeModal] = useState(false); const [rawHtmlCode, setRawHtmlCode] = useState(''); // Audio player ref for previewing voice samples or scene TTS const audioPreviewRef = useRef(null); const [playingAudioUrl, setPlayingAudioUrl] = useState(''); useEffect(() => { if (activeProject) { setLocalScenes(activeProject.scenes || []); setScenesDirty(false); if (selectedSceneIdx >= (activeProject.scenes?.length || 1)) { setSelectedSceneIdx(0); } setIframeKey((k) => k + 1); void loadProjectDetails(activeProject.id); } else { setShowCreateModal(true); } }, [activeProject?.id, activeProject?.updatedAt]); useEffect(() => { if (!activeProject) return; const evSource = new EventSource(`/api/projects/${activeProject.id}/events`); evSource.onmessage = (ev) => { try { const data = JSON.parse(ev.data); setLiveProgress(data); if ( data.status === 'ready' || data.status === 'awaiting_storyboard_review' || data.status === 'error' ) { onRefreshAll(); setIframeKey((k) => k + 1); } } catch {} }; return () => evSource.close(); }, [activeProject?.id]); useEffect(() => { if (!activeProject) return; const hasRunning = renderJobs.some((j) => ['queued', 'bundling', 'rendering'].includes(j.status) ); if (!hasRunning) return; const timer = setInterval(() => { void loadProjectDetails(activeProject.id); }, 3000); return () => clearInterval(timer); }, [activeProject?.id, renderJobs]); async function loadProjectDetails(projectId: string) { try { const [projData, rndData] = await Promise.all([ api.getProject(projectId), api.getRenderJobs(projectId), ]); setVersions(projData.versions || []); setRenderJobs(rndData.jobs || []); } catch {} } function playAudioUrl(url: string) { if (!url) return; if (audioPreviewRef.current) { if (playingAudioUrl === url) { audioPreviewRef.current.pause(); setPlayingAudioUrl(''); return; } audioPreviewRef.current.src = url; audioPreviewRef.current.play().catch(() => {}); setPlayingAudioUrl(url); } } const detectedUrls = (prompt.match(/https?:\/\/[^\s"'<>]+/gi) || []).slice(0, 4); async function handleCreateProject(e: React.FormEvent) { e.preventDefault(); if (!prompt.trim()) return; setCreating(true); try { const res = await api.createProject({ title: title.trim() || undefined, prompt: prompt.trim(), aspectRatio, creationMode, framePresetId, voiceId, voiceSpeed, bgmTrackId, brandKitId: brandKitId || undefined, recipeId: recipeId || undefined, manualAssetLock, overrideDirectorProfileId: overrideDirectorProfileId || undefined, overrideCoderProfileId: overrideCoderProfileId || undefined, }); setPrompt(''); setTitle(''); setShowCreateModal(false); onRefreshAll(); onSelectProject(res.project.id); } catch (err: any) { alert(`Lỗi tạo dự án: ${err.message}`); } finally { setCreating(false); } } function updateLocalScene(idx: number, patch: Partial) { setLocalScenes((prev) => prev.map((sc, i) => (i === idx ? { ...sc, ...patch } : sc)) ); setScenesDirty(true); } function addSceneBelow(idx: number) { const refScene = localScenes[idx]; const newScene: ScenePacket = { id: `sc-${Date.now().toString(36)}`, index: idx + 1, slug: `scene-${idx + 2}`, title: 'Tiêu đề phân cảnh mới', role: 'Key_Feature', narrationText: 'Nhập lời bình thuyết minh cho phân cảnh này...', visualDirection: 'Bố cục chuyển động hiện đại, rõ nét', imagePrompt: 'Modern clean product showcase studio lighting', catalogQuery: '', blueprintId: refScene?.blueprintId || 'kinetic-type-beats', motionRuleIds: refScene?.motionRuleIds || ['spring-pop', 'stagger-words'], registryBlockName: refScene?.registryBlockName || 'glass-callout-card', transitionOut: 'fade-blur', sfxCue: 'whoosh-soft', startSec: 0, durationSec: 4.5, audioUrl: '', audioDurationSec: 4.0, words: [], assignedAssetIds: [], referenceImageUrl: refScene?.referenceImageUrl || '', videoTrimStartSec: 0, filePath: '', status: 'planned', }; const next = [...localScenes]; next.splice(idx + 1, 0, newScene); setLocalScenes(next); setSelectedSceneIdx(idx + 1); setScenesDirty(true); } function duplicateScene(idx: number) { const source = localScenes[idx]; if (!source) return; const copy: ScenePacket = { ...source, id: `sc-${Date.now().toString(36)}`, title: `${source.title} (Bản sao)`, }; const next = [...localScenes]; next.splice(idx + 1, 0, copy); setLocalScenes(next); setSelectedSceneIdx(idx + 1); setScenesDirty(true); } function moveScene(idx: number, dir: -1 | 1) { const target = idx + dir; if (target < 0 || target >= localScenes.length) return; const next = [...localScenes]; const [item] = next.splice(idx, 1); next.splice(target, 0, item); setLocalScenes(next); setSelectedSceneIdx(target); setScenesDirty(true); } function deleteScene(idx: number) { if (localScenes.length <= 1) { alert('Dự án cần ít nhất 1 phân cảnh.'); return; } const next = localScenes.filter((_, i) => i !== idx); setLocalScenes(next); setSelectedSceneIdx(Math.max(0, idx - 1)); setScenesDirty(true); } async function handleSaveAndCompileScenes( overrideScenes?: ScenePacket[], overridePresetId?: string, overrideVoiceId?: string ) { if (!activeProject) return; setSavingScenes(true); try { await api.updateStoryboard(activeProject.id, { scenes: overrideScenes || localScenes, framePresetId: overridePresetId || activeProject.framePresetId, voiceId: overrideVoiceId || activeProject.voiceId, rebuildComposition: true, }); setScenesDirty(false); onRefreshAll(); setIframeKey((k) => k + 1); } catch (err: any) { alert(`Lỗi lưu phân cảnh: ${err.message}`); } finally { setSavingScenes(false); } } async function handleResynthesizeSceneVoice(idx: number) { if (!activeProject) return; const sc = localScenes[idx]; if (!sc) return; setBusySceneAction(`tts-${idx}`); try { await api.resynthesizeSceneVoice( activeProject.id, idx, sc.narrationText, activeProject.voiceId, activeProject.voiceSpeed ); onRefreshAll(); setIframeKey((k) => k + 1); } catch (err: any) { alert(`Lỗi tạo giọng đọc: ${err.message}`); } finally { setBusySceneAction(null); } } async function handleApproveStoryboard() { if (!activeProject) return; setSavingScenes(true); try { await api.updateStoryboard(activeProject.id, { scenes: localScenes, rebuildComposition: false, }); await api.approveStoryboardAndBuild(activeProject.id); onRefreshAll(); setIframeKey((k) => k + 1); } catch (err: any) { alert(`Lỗi dựng video: ${err.message}`); } finally { setSavingScenes(false); } } async function handlePromptEdit(e: React.FormEvent) { e.preventDefault(); if (!activeProject || !editPrompt.trim()) return; setEditingBusy(true); setLastEditSummary(''); try { const res = await api.promptEditProject( activeProject.id, editPrompt.trim(), editTargetIdx === 'all' ? undefined : editTargetIdx ); setEditPrompt(''); setLastEditSummary(res.summary); setVersions(res.versions || []); onRefreshAll(); setIframeKey((k) => k + 1); } catch (err: any) { alert(`Lỗi chỉnh sửa: ${err.message}`); } finally { setEditingBusy(false); } } async function handleAspectRatioChange(ratio: AspectRatio) { if (!activeProject || activeProject.aspectRatio === ratio) return; setEditingBusy(true); try { const res = await api.remixAspectRatio(activeProject.id, ratio); setVersions(res.versions || []); onRefreshAll(); setIframeKey((k) => k + 1); } catch (err: any) { alert(`Lỗi đổi tỷ lệ khung hình: ${err.message}`); } finally { setEditingBusy(false); } } async function handleStartRender() { if (!activeProject) return; setStartingRender(true); try { if (scenesDirty) { await handleSaveAndCompileScenes(); } await api.startRender(activeProject.id, renderingProvider); await loadProjectDetails(activeProject.id); onRefreshAll(); } catch (err: any) { alert(`Lỗi khởi chạy Render: ${err.message}`); } finally { setStartingRender(false); } } function openMediaPickerForScene(idx: number) { const sc = localScenes[idx]; setMediaModalSceneIdx(idx); setModalImagePrompt(sc?.imagePrompt || sc?.visualDirection || sc?.title || ''); setModalWebQuery(sc?.catalogQuery || sc?.title || ''); setModalMediaMessage(''); setMediaModalTab('library'); } async function handleAssignAssetToScene(asset: AssetItem) { if (mediaModalSceneIdx === null || !activeProject) return; const updated = localScenes.map((sc, i) => i === mediaModalSceneIdx ? { ...sc, assignedAssetIds: [asset.id], referenceImageUrl: asset.publicUrl, } : sc ); setLocalScenes(updated); setMediaModalSceneIdx(null); await handleSaveAndCompileScenes(updated); } async function handleModalGenerateAiImage() { if (mediaModalSceneIdx === null || !activeProject) return; setModalMediaBusy(true); setModalMediaMessage('Đang tạo hình ảnh AI tham khảo cho phân cảnh...'); try { await api.regenerateSceneImage( activeProject.id, mediaModalSceneIdx, modalImagePrompt.trim() ); onRefreshAll(); setIframeKey((k) => k + 1); setMediaModalSceneIdx(null); } catch (err: any) { setModalMediaMessage(`Lỗi tạo ảnh: ${err.message}`); } finally { setModalMediaBusy(false); } } async function handleModalScrapeUrl() { if (!modalScrapeUrl.trim() || !activeProject) return; setModalMediaBusy(true); setModalMediaMessage('Đang cào ảnh/logo từ URL & phân tích Vision AI...'); try { const res = await api.scrapeUrlAssets({ url: modalScrapeUrl.trim(), projectId: activeProject.id, }); setModalMediaMessage( `Đã thu thập & phân tích ${res.scrapedAssets?.length || 0} tài nguyên! Bấm vào ảnh bên dưới để gán vào cảnh.` ); onRefreshAll(); setMediaModalTab('library'); } catch (err: any) { setModalMediaMessage(`Lỗi cào URL: ${err.message}`); } finally { setModalMediaBusy(false); } } async function handleModalSearchWeb() { if (!modalWebQuery.trim() || !activeProject) return; setModalMediaBusy(true); setModalMediaMessage('Đang tìm ảnh thực tế trên Web...'); try { const res = await api.searchWebAssets({ query: modalWebQuery.trim(), projectId: activeProject.id, limit: 4, }); setModalMediaMessage( `Đã tìm thấy ${res.foundAssets?.length || 0} ảnh thực tế! Bấm vào ảnh bên dưới để gán vào cảnh.` ); onRefreshAll(); setMediaModalTab('library'); } catch (err: any) { setModalMediaMessage(`Lỗi tìm ảnh: ${err.message}`); } finally { setModalMediaBusy(false); } } async function handleOpenCodeInspector() { if (!activeProject) return; try { const resp = await fetch(`/api/projects/${activeProject.id}/preview`); const text = await resp.text(); setRawHtmlCode(text); setShowCodeModal(true); } catch {} } const voicesList = catalog?.voices || []; const selectedVoiceObj = voicesList.find( (v: any) => v.id === (activeProject?.voiceId || voiceId) || v.voiceId === (activeProject?.voiceId || voiceId) ); const isBuilding = activeProject && ['scraping_assets', 'planning_storyboard', 'generating_media', 'coding_scenes', 'validating'].includes( activeProject.status ); return (