Download apps/web/src/components/StudioWorkspaceView.tsx from phucsd/olokaflow: direct link, hf CLI and curl.
- Browser
- Download file 85.6 kB
-
https://huggingface.co/spaces/phucsd/olokaflow/resolve/main/apps/web/src/components/StudioWorkspaceView.tsx
- Command line
-
hf download hf://spaces/phucsd/olokaflow/apps/web/src/components/StudioWorkspaceView.tsx
-
curl -L -o StudioWorkspaceView.tsx https://huggingface.co/spaces/phucsd/olokaflow/resolve/main/apps/web/src/components/StudioWorkspaceView.tsx
85.6 kB
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<Props> = ({
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<AspectRatio>('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<number>(0);
const [localScenes, setLocalScenes] = useState<ScenePacket[]>([]);
const [scenesDirty, setScenesDirty] = useState(false);
const [savingScenes, setSavingScenes] = useState(false);
const [busySceneAction, setBusySceneAction] = useState<string | null>(null);
// AI Copilot Edit State
const [editPrompt, setEditPrompt] = useState('');
const [editTargetIdx, setEditTargetIdx] = useState<number | 'all'>('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<RenderJob[]>([]);
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<number | null>(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<HTMLAudioElement | null>(null);
const [playingAudioUrl, setPlayingAudioUrl] = useState<string>('');
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<ScenePacket>) {
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 (
<div className="space-y-4">
<audio
ref={audioPreviewRef}
onEnded={() => setPlayingAudioUrl('')}
className="hidden"
/>
{/* =====================================================================
1. FLIKI STUDIO TOP HEADER TOOLBAR (DESIGN.MD + SHADCN PRIMITIVES)
===================================================================== */}
<div className="fliki-card px-5 py-3 flex flex-wrap items-center justify-between gap-3 bg-white">
<div className="flex items-center gap-3 flex-wrap">
<div className="flex items-center gap-2">
<span className="w-2 h-2 rounded-full bg-[#E11D48]" />
<select
value={activeProject?.id || ''}
onChange={(e) => {
if (e.target.value) {
setShowCreateModal(false);
onSelectProject(e.target.value);
}
}}
className="bg-zinc-50 border border-zinc-200 hover:border-zinc-300 rounded-xl px-3.5 py-1.5 text-xs font-bold text-zinc-900 focus:outline-none focus:border-[#E11D48] cursor-pointer"
>
{projects.length === 0 && <option value="">Chưa có dự án nào</option>}
{projects.map((p) => (
<option key={p.id} value={p.id}>
{p.title} ({p.aspectRatio} • {Math.round(p.totalDurationSec || 0)}s)
</option>
))}
</select>
</div>
{activeProject && (
<Badge
variant={
activeProject.status === 'ready' || activeProject.status === 'rendered'
? 'emerald'
: activeProject.status === 'awaiting_storyboard_review'
? 'amber'
: 'crimson'
}
>
<CheckCircle2 className="w-3 h-3" />
{activeProject.status === 'ready'
? 'Sẵn sàng 60fps'
: activeProject.status === 'rendered'
? 'Đã xuất MP4'
: activeProject.status === 'awaiting_storyboard_review'
? 'Chờ duyệt Storyboard'
: activeProject.status}
</Badge>
)}
{/* Aspect Ratio Switcher */}
{activeProject && (
<div className="flex items-center bg-zinc-100 p-1 rounded-xl border border-zinc-200">
{(
[
{ ratio: '9:16' as AspectRatio, label: '9:16', Icon: Smartphone },
{ ratio: '16:9' as AspectRatio, label: '16:9', Icon: Monitor },
{ ratio: '1:1' as AspectRatio, label: '1:1', Icon: SquareIcon },
] as const
).map(({ ratio, label, Icon }) => (
<button
key={ratio}
onClick={() => handleAspectRatioChange(ratio)}
disabled={editingBusy}
className={`px-2.5 py-1 rounded-lg text-xs font-mono tabular-nums font-bold flex items-center gap-1.5 transition-all cursor-pointer ${
activeProject.aspectRatio === ratio
? 'bg-white text-[#E11D48] shadow-2xs'
: 'text-zinc-600 hover:text-zinc-900'
}`}
>
<Icon className="w-3.5 h-3.5" />
<span>{label}</span>
</button>
))}
</div>
)}
{/* Frame Preset Style Selector */}
{activeProject && (
<div className="flex items-center gap-1.5 bg-zinc-50 border border-zinc-200 rounded-xl px-2.5 py-1">
<Sliders className="w-3.5 h-3.5 text-zinc-500" />
<select
value={activeProject.framePresetId}
onChange={(e) =>
handleSaveAndCompileScenes(localScenes, e.target.value, undefined)
}
className="bg-transparent text-xs font-semibold text-zinc-800 focus:outline-none cursor-pointer"
title="Đổi bảng màu & Typography (HyperFrames Frame Preset)"
>
{(catalog?.framePresets || []).map((fp: any) => (
<option key={fp.id} value={fp.id}>
Preset: {fp.name}
</option>
))}
</select>
</div>
)}
{/* Global Voice Selector + Sample Preview */}
{activeProject && (
<div className="flex items-center gap-1.5 bg-zinc-50 border border-zinc-200 rounded-xl px-2.5 py-1">
<Mic className="w-3.5 h-3.5 text-[#E11D48]" />
<select
value={activeProject.voiceId}
onChange={(e) =>
handleSaveAndCompileScenes(localScenes, undefined, e.target.value)
}
className="bg-transparent text-xs font-semibold text-zinc-800 focus:outline-none max-w-[170px] cursor-pointer"
>
{voicesList.map((v: any) => (
<option key={v.id} value={v.voiceId || v.id}>
{v.name}
</option>
))}
</select>
{selectedVoiceObj?.previewUrl && (
<button
type="button"
onClick={() => playAudioUrl(selectedVoiceObj.previewUrl)}
className="px-2 py-0.5 rounded-md bg-rose-50 hover:bg-rose-100 text-[#E11D48] text-[11px] font-bold flex items-center gap-1 cursor-pointer"
title="Nghe thử mẫu giọng này"
>
{playingAudioUrl === selectedVoiceObj.previewUrl ? (
<>
<Square className="w-2.5 h-2.5 fill-current" />
<span>Dừng</span>
</>
) : (
<>
<Volume2 className="w-3 h-3" />
<span>Mẫu</span>
</>
)}
</button>
)}
</div>
)}
</div>
{/* Right Actions: Undo/Redo, New Video, Export MP4 */}
<div className="flex items-center gap-2">
{versions.length > 0 && activeProject && (
<div className="flex items-center gap-1.5 bg-zinc-50 border border-zinc-200 rounded-xl px-2.5 py-1.5">
<History className="w-3.5 h-3.5 text-zinc-500" />
<select
defaultValue=""
onChange={async (e) => {
if (!e.target.value) return;
await api.restoreVersion(activeProject.id, e.target.value);
e.target.value = '';
onRefreshAll();
setIframeKey((k) => k + 1);
}}
className="bg-transparent text-xs font-semibold text-zinc-700 focus:outline-none cursor-pointer"
>
<option value="">Lịch sử ({versions.length})</option>
{versions.map((v) => (
<option key={v.id} value={v.id}>
v{v.versionNum}: {v.label}
</option>
))}
</select>
</div>
)}
<Button
type="button"
variant="secondary"
onClick={() => setShowCreateModal(!showCreateModal)}
>
<Plus className="w-3.5 h-3.5 text-[#E11D48]" />
<span>{showCreateModal ? 'Đóng khung tạo' : 'Tạo Video Mới'}</span>
</Button>
{activeProject && (
<div className="flex items-center gap-1.5">
<div className="flex items-center gap-1 bg-zinc-50 border border-zinc-200 rounded-xl px-2.5 py-1.5">
{renderingProvider === 'modal' ? (
<Cloud className="w-3.5 h-3.5 text-[#E11D48]" />
) : (
<Laptop className="w-3.5 h-3.5 text-zinc-600" />
)}
<select
value={renderingProvider}
onChange={(e) => setRenderingProvider(e.target.value as 'modal' | 'local')}
className="bg-transparent text-xs font-semibold text-zinc-700 focus:outline-none cursor-pointer"
>
<option value="modal">Modal Cloud (cpu24w22)</option>
<option value="local">Local HyperFrames CLI</option>
</select>
</div>
<Button
type="button"
variant="primary"
onClick={handleStartRender}
disabled={startingRender}
>
<Download className="w-3.5 h-3.5" />
<span>{startingRender ? 'Đang gửi Render...' : 'Xuất MP4'}</span>
</Button>
</div>
)}
</div>
</div>
{/* =====================================================================
2. NEW VIDEO PROMPT-TO-VIDEO DRAWER (FLIKI IDEA-TO-VIDEO WIZARD)
===================================================================== */}
{showCreateModal && (
<form
onSubmit={handleCreateProject}
className="fliki-card p-6 bg-white border-zinc-200 space-y-5"
>
<div className="flex items-center justify-between border-b border-zinc-100 pb-4">
<div>
<Badge variant="crimson" className="mb-1.5">
<Sparkles className="w-3 h-3" />
Fliki Idea-to-Video • HyperFrames 4-Tier Catalog Engine
</Badge>
<h2 className="text-lg font-bold tracking-tight text-zinc-900">
Tạo Video Chuyên Nghiệp Từ Prompt Hoặc URL Sản Phẩm
</h2>
<p className="text-xs text-zinc-500 mt-0.5">
Nhập ý tưởng hoặc dán link trang web — Hệ thống tự động cào ảnh/logo chuẩn thương hiệu, viết kịch bản, đọc giọng OlokaTTS và dựng đồ họa chuyển động 60fps.
</p>
</div>
{activeProject && (
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => setShowCreateModal(false)}
>
<X className="w-4 h-4" />
<span>Đóng</span>
</Button>
)}
</div>
{/* Quick Prompt Templates */}
<div className="flex items-center gap-2 flex-wrap">
<span className="text-xs font-semibold text-zinc-500">Mẫu gợi ý nhanh:</span>
{[
{
label: 'Ra mắt nền tảng SaaS AI',
text: 'Tạo video quảng cáo 5 cảnh ra mắt nền tảng OlokaFlow AI Video Studio: tự động hóa dựng video 60fps bằng HyperFrames, tích hợp giọng đọc AI tiếng Việt tự nhiên và render đám mây siêu tốc.',
preset: 'editorial-clean-light',
},
{
label: 'Mỹ phẩm & Skincare Cao cấp',
text: 'Tạo video giới thiệu tinh chất Serum Vitamin C & Hyaluronic Acid dưỡng sáng da tự nhiên, cấp ẩm chuyên sâu 24h, cam kết chính hãng và ưu đãi đặt hàng hôm nay.',
preset: 'luxury-minimal-cream',
},
{
label: 'Báo cáo Tăng trưởng & Số liệu',
text: 'Tạo video thuyết trình báo cáo tăng trưởng doanh thu thương mại điện tử Q4 tăng 320%, tỷ lệ chuyển đổi đạt 8.4% và lộ trình mở rộng thị trường Đông Nam Á.',
preset: 'fintech-emerald-trust',
},
].map((tpl, i) => (
<button
key={i}
type="button"
onClick={() => {
setPrompt(tpl.text);
setFramePresetId(tpl.preset);
}}
className="px-3 py-1.5 rounded-full text-xs font-semibold bg-zinc-50 hover:bg-rose-50 text-zinc-700 hover:text-[#E11D48] border border-zinc-200 hover:border-rose-200 transition-colors cursor-pointer flex items-center gap-1.5"
>
<Sparkles className="w-3 h-3 text-[#E11D48]" />
<span>{tpl.label}</span>
</button>
))}
</div>
<div className="grid grid-cols-1 lg:grid-cols-12 gap-5">
<div className="lg:col-span-7 space-y-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className="block text-xs font-semibold text-zinc-700 mb-1">
Tên dự án (Tùy chọn)
</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="VD: TVC Ra mắt Sản phẩm Q4..."
className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-xs text-zinc-900 focus:outline-none focus:border-[#E11D48] focus:bg-white"
/>
</div>
<div>
<label className="block text-xs font-semibold text-zinc-700 mb-1">
Chế độ khởi tạo
</label>
<div className="grid grid-cols-2 bg-zinc-100 p-1 rounded-xl border border-zinc-200">
<button
type="button"
onClick={() => setCreationMode('auto')}
className={`py-1.5 rounded-lg text-xs font-semibold cursor-pointer transition-all flex items-center justify-center gap-1.5 ${
creationMode === 'auto'
? 'bg-white text-[#E11D48] shadow-2xs'
: 'text-zinc-600'
}`}
>
<Zap className="w-3.5 h-3.5" />
<span>Tự động 100%</span>
</button>
<button
type="button"
onClick={() => setCreationMode('storyboard_review')}
className={`py-1.5 rounded-lg text-xs font-semibold cursor-pointer transition-all flex items-center justify-center gap-1.5 ${
creationMode === 'storyboard_review'
? 'bg-white text-zinc-900 shadow-2xs'
: 'text-zinc-600'
}`}
>
<LayoutTemplate className="w-3.5 h-3.5" />
<span>Duyệt Storyboard</span>
</button>
</div>
</div>
</div>
<div>
<label className="block text-xs font-semibold text-zinc-700 mb-1">
Prompt kịch bản / Nội dung / Link URL sản phẩm *
</label>
<textarea
rows={4}
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder="Mô tả chi tiết video bạn muốn tạo, hoặc dán trực tiếp URL sản phẩm/bài viết (VD: https://...) để AI tự động cào hình ảnh, logo và phân tích đưa vào video..."
className="w-full bg-zinc-50 border border-zinc-200 rounded-xl p-3.5 text-sm text-zinc-900 focus:outline-none focus:border-[#E11D48] focus:bg-white"
required
/>
{detectedUrls.length > 0 && (
<div className="mt-2 flex items-center gap-2 px-3 py-2 rounded-xl bg-rose-50/70 border border-rose-200 text-xs text-rose-800 font-medium">
<Link2 className="w-3.5 h-3.5 text-[#E11D48] shrink-0" />
<span>Đã phát hiện {detectedUrls.length} URL:</span>
<span className="font-mono truncate">{detectedUrls.join(', ')}</span>
<span className="ml-auto font-bold text-[#E11D48]">
Tự động cào ảnh & phân tích Vision AI
</span>
</div>
)}
</div>
</div>
<div className="lg:col-span-5 grid grid-cols-1 sm:grid-cols-2 gap-3 bg-zinc-50/80 p-4 rounded-2xl border border-zinc-200/80">
<div>
<label className="block text-xs font-semibold text-zinc-700 mb-1">
Tỷ lệ khung hình
</label>
<select
value={aspectRatio}
onChange={(e) => setAspectRatio(e.target.value as AspectRatio)}
className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
>
<option value="9:16">9:16 Dọc (TikTok / Reels / Shorts)</option>
<option value="16:9">16:9 Ngang (YouTube / Web Hero)</option>
<option value="1:1">1:1 Vuông (Facebook / Instagram Feed)</option>
</select>
</div>
<div>
<label className="block text-xs font-semibold text-zinc-700 mb-1">
Phong cách thiết kế (Frame Preset)
</label>
<select
value={framePresetId}
onChange={(e) => setFramePresetId(e.target.value)}
className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
>
{(catalog?.framePresets || []).map((fp: any) => (
<option key={fp.id} value={fp.id}>
{fp.name} ({fp.category})
</option>
))}
</select>
</div>
<div className="sm:col-span-2">
<label className="block text-xs font-semibold text-zinc-700 mb-1">
Giọng đọc AI (25 Giọng OlokaTTS Việt Nam & OpenAI)
</label>
<div className="flex items-center gap-2">
<select
value={voiceId}
onChange={(e) => setVoiceId(e.target.value)}
className="flex-1 bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
>
{voicesList.map((v: any) => (
<option key={v.id} value={v.voiceId || v.id}>
{v.name} — {v.description}
</option>
))}
</select>
{(() => {
const vObj = voicesList.find(
(v: any) => v.id === voiceId || v.voiceId === voiceId
);
return vObj?.previewUrl ? (
<Button
type="button"
variant="outlineCrimson"
size="sm"
onClick={() => playAudioUrl(vObj.previewUrl)}
>
{playingAudioUrl === vObj.previewUrl ? (
<>
<Square className="w-3 h-3 fill-current" />
<span>Dừng</span>
</>
) : (
<>
<Volume2 className="w-3.5 h-3.5" />
<span>Nghe thử</span>
</>
)}
</Button>
) : null;
})()}
</div>
</div>
<div>
<label className="block text-xs font-semibold text-zinc-700 mb-1">
Bộ nhận diện (Brand Kit)
</label>
<select
value={brandKitId}
onChange={(e) => setBrandKitId(e.target.value)}
className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
>
<option value="">Mặc định theo Preset</option>
{brands.map((b) => (
<option key={b.id} value={b.id}>
{b.name} ({b.brandName})
</option>
))}
</select>
</div>
<div>
<label className="block text-xs font-semibold text-zinc-700 mb-1">
Công thức dựng sẵn (Frozen Recipe)
</label>
<select
value={recipeId}
onChange={(e) => setRecipeId(e.target.value)}
className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
>
<option value="">AI Director tự động chọn Blueprint</option>
{recipes.map((r) => (
<option key={r.id} value={r.id}>
{r.name}
</option>
))}
</select>
</div>
<div className="sm:col-span-2 flex items-center justify-between pt-2">
<label className="flex items-center gap-2 text-xs font-medium text-zinc-600 cursor-pointer">
<input
type="checkbox"
checked={manualAssetLock}
onChange={(e) => setManualAssetLock(e.target.checked)}
className="rounded border-zinc-300 text-[#E11D48] focus:ring-[#E11D48]"
/>
<Lock className="w-3.5 h-3.5 text-zinc-400" />
<span>Khóa tài nguyên thủ công (Chỉ dùng ảnh đã upload)</span>
</label>
<Button type="submit" variant="primary" size="lg" disabled={creating}>
<Film className="w-4 h-4" />
<span>
{creating
? 'Đang khởi tạo Pipeline...'
: creationMode === 'storyboard_review'
? 'Lập Storyboard & Tạo Media'
: 'Tạo Video HyperFrames Ngay'}
</span>
</Button>
</div>
</div>
</div>
</form>
)}
{/* =====================================================================
3. LIVE PIPELINE PROGRESS BANNER (WHEN BUILDING)
===================================================================== */}
{(isBuilding || (liveProgress && liveProgress.progress < 100)) && (
<div className="fliki-card p-4 bg-white border-rose-200 flex items-center justify-between gap-4">
<div className="flex items-center gap-3 flex-1">
<div className="w-9 h-9 rounded-xl bg-[#E11D48] text-white flex items-center justify-center">
<RefreshCw className="w-4 h-4 animate-spin" />
</div>
<div className="flex-1">
<div className="flex items-center justify-between text-xs font-bold text-zinc-900 mb-1">
<span>{liveProgress?.message || 'Đang xử lý pipeline HyperFrames...'}</span>
<span className="font-mono tabular-nums text-[#E11D48]">
{liveProgress?.progress || 45}%
</span>
</div>
<div className="w-full h-2 bg-zinc-100 rounded-full overflow-hidden">
<div
className="h-full bg-[#E11D48] transition-all duration-500"
style={{ width: `${liveProgress?.progress || 45}%` }}
/>
</div>
</div>
</div>
{activeProject && (
<Button
type="button"
variant="danger"
size="sm"
onClick={() => api.abortProject(activeProject.id)}
>
<Square className="w-3 h-3 fill-current" />
<span>Dừng</span>
</Button>
)}
</div>
)}
{/* =====================================================================
4. FLIKI SPLIT-SCREEN SCENE-BY-SCENE WORKSPACE (LEFT SCENES / RIGHT PLAYER)
===================================================================== */}
{activeProject && (
<div className="grid grid-cols-1 xl:grid-cols-12 gap-5 items-start">
{/* -----------------------------------------------------------------
LEFT COLUMN (7/12): FLIKI SCENE-BY-SCENE BLOCK EDITOR
----------------------------------------------------------------- */}
<div className="xl:col-span-7 space-y-3.5">
{activeProject.status === 'awaiting_storyboard_review' && (
<div className="fliki-card p-4 bg-amber-50/90 border-amber-300 flex flex-wrap items-center justify-between gap-3">
<div>
<h3 className="text-sm font-bold text-amber-950 flex items-center gap-2">
<LayoutTemplate className="w-4 h-4 text-amber-700" />
Chế độ Duyệt Storyboard Trước Khi Sinh Code HyperFrames
</h3>
<p className="text-xs text-amber-800 mt-0.5">
Kiểm tra lời bình, nghe thử giọng đọc, đổi ảnh tham khảo hoặc Blueprint từng cảnh rồi bấm nút bên phải để dựng video 60fps.
</p>
</div>
<Button
type="button"
variant="primary"
onClick={handleApproveStoryboard}
disabled={savingScenes}
>
<Film className="w-3.5 h-3.5" />
<span>
{savingScenes
? 'Đang dựng HyperFrames...'
: 'Duyệt & Dựng Video HyperFrames 60fps'}
</span>
</Button>
</div>
)}
{/* Scene Stack Header */}
<div className="flex items-center justify-between px-1">
<div className="flex items-center gap-2">
<h3 className="text-sm font-bold text-zinc-900 flex items-center gap-2">
<span>Danh sách Phân cảnh Kịch bản</span>
<span className="px-2 py-0.5 rounded-md bg-zinc-100 text-zinc-700 font-mono tabular-nums text-xs">
{localScenes.length} cảnh •{' '}
{localScenes
.reduce((acc, s) => acc + Number(s.durationSec || 0), 0)
.toFixed(1)}
s
</span>
</h3>
{scenesDirty && (
<Badge variant="amber">Có thay đổi chưa lưu</Badge>
)}
</div>
<div className="flex items-center gap-2">
{scenesDirty && (
<Button
type="button"
variant="primary"
size="sm"
onClick={() => handleSaveAndCompileScenes()}
disabled={savingScenes}
>
<RefreshCw
className={`w-3.5 h-3.5 ${savingScenes ? 'animate-spin' : ''}`}
/>
<span>
{savingScenes ? 'Đang biên dịch...' : 'Lưu & Cập nhật Player 60fps'}
</span>
</Button>
)}
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => addSceneBelow(localScenes.length - 1)}
>
<Plus className="w-3.5 h-3.5" />
<span>Thêm cảnh</span>
</Button>
</div>
</div>
{/* FLIKI SCENE CARDS LIST */}
<div className="space-y-3">
{localScenes.map((scene, idx) => {
const isSelected = selectedSceneIdx === idx;
const wordCount = (scene.narrationText || '')
.trim()
.split(/\s+/)
.filter(Boolean).length;
const paddedIdx = String(idx + 1).padStart(2, '0');
return (
<div
key={scene.id || idx}
onClick={() => setSelectedSceneIdx(idx)}
className={`${
isSelected ? 'fliki-card-active' : 'fliki-card'
} p-4 bg-white transition-all`}
>
{/* SCENE CARD HEADER BAR */}
<div className="flex flex-wrap items-center justify-between gap-2 pb-3 mb-3 border-b border-zinc-100">
<div className="flex items-center gap-2 flex-wrap">
<span
className={`px-2.5 py-1 rounded-lg text-xs font-mono tabular-nums font-bold ${
isSelected
? 'bg-[#E11D48] text-white'
: 'bg-zinc-100 text-zinc-700'
}`}
>
#{paddedIdx}
</span>
{/* Role Badge Selector */}
<select
value={scene.role}
onChange={(e) =>
updateLocalScene(idx, { role: e.target.value as SceneRole })
}
className="bg-zinc-50 border border-zinc-200 rounded-lg px-2.5 py-1 text-xs font-semibold text-zinc-700 focus:outline-none focus:border-[#E11D48] cursor-pointer"
>
{SCENE_ROLES.map((r) => (
<option key={r} value={r}>
{r}
</option>
))}
</select>
{/* Fliki Voiceover Pill */}
<div className="flex items-center gap-1.5 bg-rose-50/70 border border-rose-200/80 rounded-full px-2.5 py-0.5 text-xs">
<Mic className="w-3 h-3 text-[#E11D48]" />
<span className="font-semibold text-rose-900">
{activeProject.voiceId}
</span>
{scene.audioUrl && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
playAudioUrl(scene.audioUrl);
}}
className="px-2 py-0.5 rounded-full bg-white hover:bg-rose-100 text-[#E11D48] font-semibold text-[11px] border border-rose-200 flex items-center gap-1 cursor-pointer"
>
{playingAudioUrl === scene.audioUrl ? (
<>
<Square className="w-2.5 h-2.5 fill-current" />
<span>Dừng</span>
</>
) : (
<>
<Play className="w-2.5 h-2.5 fill-current" />
<span>Nghe</span>
</>
)}
</button>
)}
<button
type="button"
onClick={(e) => {
e.stopPropagation();
void handleResynthesizeSceneVoice(idx);
}}
disabled={busySceneAction === `tts-${idx}`}
className="px-2 py-0.5 rounded-full bg-[#E11D48] hover:bg-[#BE123C] text-white font-semibold text-[11px] flex items-center gap-1 cursor-pointer"
title="Tổng hợp lại giọng đọc TTS cho cảnh này"
>
<RefreshCw
className={`w-2.5 h-2.5 ${
busySceneAction === `tts-${idx}` ? 'animate-spin' : ''
}`}
/>
<span>
{busySceneAction === `tts-${idx}` ? 'Đang đọc...' : 'Đọc lại TTS'}
</span>
</button>
</div>
{/* Scene Duration Pill */}
<div className="flex items-center gap-1 bg-zinc-50 border border-zinc-200 rounded-lg px-2 py-0.5 text-xs text-zinc-600">
<Clock className="w-3 h-3 text-zinc-400" />
<input
type="number"
step="0.2"
min="2.0"
max="30.0"
value={scene.durationSec}
onChange={(e) =>
updateLocalScene(idx, {
durationSec: Number(e.target.value) || 4.5,
})
}
className="w-12 bg-transparent font-mono tabular-nums font-bold text-zinc-900 focus:outline-none text-center"
/>
<span className="font-mono">s</span>
</div>
</div>
{/* Scene Block Controls (Up / Down / Duplicate / Add Below / Delete) */}
<div className="flex items-center gap-1">
<button
type="button"
onClick={(e) => {
e.stopPropagation();
moveScene(idx, -1);
}}
disabled={idx === 0}
className="p-1.5 rounded-lg hover:bg-zinc-100 text-zinc-500 disabled:opacity-30 cursor-pointer"
title="Di chuyển cảnh lên"
>
<ArrowUp className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
moveScene(idx, 1);
}}
disabled={idx === localScenes.length - 1}
className="p-1.5 rounded-lg hover:bg-zinc-100 text-zinc-500 disabled:opacity-30 cursor-pointer"
title="Di chuyển cảnh xuống"
>
<ArrowDown className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
duplicateScene(idx);
}}
className="px-2 py-1 rounded-lg hover:bg-zinc-100 text-zinc-600 text-xs font-semibold flex items-center gap-1 cursor-pointer"
title="Nhân bản cảnh này"
>
<Copy className="w-3 h-3" />
<span>Nhân bản</span>
</button>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
addSceneBelow(idx);
}}
className="px-2 py-1 rounded-lg hover:bg-zinc-100 text-zinc-700 text-xs font-semibold flex items-center gap-1 cursor-pointer"
title="Chèn cảnh mới bên dưới"
>
<Plus className="w-3 h-3" />
<span>Cảnh dưới</span>
</button>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
deleteScene(idx);
}}
className="p-1.5 rounded-lg hover:bg-rose-50 text-zinc-400 hover:text-[#E11D48] cursor-pointer"
title="Xóa phân cảnh"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
</div>
{/* SCENE CARD MAIN BODY: LEFT SCRIPT & HEADLINE / RIGHT MEDIA THUMBNAIL */}
<div className="grid grid-cols-1 sm:grid-cols-12 gap-4 items-start">
<div className="sm:col-span-9 space-y-2.5">
{/* On-screen Headline Input */}
<div>
<label className="block text-[11px] font-bold uppercase tracking-wider text-zinc-400 mb-1">
Tiêu đề hiển thị trên màn hình (Headline Layer)
</label>
<input
type="text"
value={scene.title}
onChange={(e) =>
updateLocalScene(idx, { title: e.target.value })
}
placeholder="Nhập tiêu đề chính hiển thị trên cảnh..."
className="w-full bg-zinc-50/70 hover:bg-zinc-50 focus:bg-white border border-zinc-200 focus:border-[#E11D48] rounded-xl px-3.5 py-2 text-sm font-bold text-zinc-900 focus:outline-none transition-colors"
/>
</div>
{/* Narration Script Textarea */}
<div>
<div className="flex items-center justify-between mb-1">
<label className="text-[11px] font-bold uppercase tracking-wider text-zinc-400">
Lời bình thuyết minh (Voiceover Script & Phụ đề Karaoke)
</label>
<span className="text-[11px] text-zinc-400 font-mono tabular-nums">
{wordCount} từ • ~{Math.max(2.5, wordCount / 2.9).toFixed(1)}s đọc
</span>
</div>
<textarea
rows={2}
value={scene.narrationText}
onChange={(e) =>
updateLocalScene(idx, { narrationText: e.target.value })
}
placeholder="Nhập lời thoại tiếng Việt cho phân cảnh này..."
className="w-full bg-zinc-50/70 hover:bg-zinc-50 focus:bg-white border border-zinc-200 focus:border-[#E11D48] rounded-xl p-3 text-sm text-zinc-800 leading-relaxed focus:outline-none transition-colors"
/>
</div>
{/* HyperFrames Blueprint & Motion Layer Pills */}
<div className="flex flex-wrap items-center gap-2 pt-1">
<div className="flex items-center gap-1.5 bg-zinc-100 border border-zinc-200 rounded-lg px-2.5 py-1 text-xs">
<LayoutTemplate className="w-3.5 h-3.5 text-[#E11D48]" />
<span className="text-zinc-600 font-semibold">Blueprint:</span>
<select
value={scene.blueprintId}
onChange={(e) =>
updateLocalScene(idx, { blueprintId: e.target.value })
}
className="bg-transparent font-semibold text-zinc-900 focus:outline-none cursor-pointer"
>
{(catalog?.sceneBlueprints || []).map((bp: any) => (
<option key={bp.id} value={bp.id}>
{bp.name} ({bp.id})
</option>
))}
</select>
</div>
<div className="flex items-center gap-1 bg-zinc-100 border border-zinc-200 rounded-lg px-2.5 py-1 text-xs text-zinc-700">
<Sparkles className="w-3 h-3 text-[#E11D48]" />
<span className="font-semibold">Motion:</span>
<span className="font-mono text-[11px]">
{(scene.motionRuleIds || []).join(', ') || 'spring-pop'}
</span>
</div>
<div className="flex items-center gap-1 bg-zinc-100 border border-zinc-200 rounded-lg px-2.5 py-1 text-xs text-zinc-700">
<Scissors className="w-3 h-3 text-zinc-500" />
<span className="font-semibold">Trim:</span>
<input
type="number"
step="0.5"
min="0"
value={scene.videoTrimStartSec || 0}
onChange={(e) =>
updateLocalScene(idx, {
videoTrimStartSec: Number(e.target.value) || 0,
})
}
className="w-10 bg-transparent font-mono tabular-nums font-bold text-center focus:outline-none"
title="Mốc cắt giây bắt đầu của video B-Roll (data-media-start)"
/>
<span className="font-mono">s</span>
</div>
</div>
</div>
{/* Right 3 Cols: Fliki Clickable Media Layer Box */}
<div className="sm:col-span-3 flex flex-col items-center">
<div
onClick={(e) => {
e.stopPropagation();
openMediaPickerForScene(idx);
}}
className="group relative w-full aspect-square max-w-[140px] rounded-2xl border border-zinc-200 hover:border-[#E11D48] overflow-hidden bg-zinc-100 cursor-pointer shadow-2xs transition-all"
title="Bấm để đổi hình ảnh / video B-roll hoặc tạo ảnh AI mới"
>
{scene.referenceImageUrl ? (
<img
src={scene.referenceImageUrl}
alt={scene.title}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
/>
) : (
<div className="w-full h-full flex flex-col items-center justify-center p-2 text-center text-zinc-400">
<ImageIcon className="w-6 h-6 mb-1" />
<span className="text-[11px] font-semibold">Chọn Media</span>
</div>
)}
<div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-zinc-950/85 via-zinc-950/50 to-transparent p-2 text-center">
<span className="text-[11px] font-semibold text-white flex items-center justify-center gap-1">
<RefreshCw className="w-3 h-3" />
<span>Đổi Media</span>
</span>
</div>
</div>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
openMediaPickerForScene(idx);
}}
className="mt-1.5 text-[11px] font-semibold text-[#E11D48] hover:text-[#BE123C] cursor-pointer flex items-center gap-1"
>
<Plus className="w-3 h-3" />
<span>Kho Media / Tạo AI</span>
</button>
</div>
</div>
</div>
);
})}
</div>
</div>
{/* -----------------------------------------------------------------
RIGHT COLUMN (5/12): STICKY LIVE 60FPS PLAYER + TIMELINE + AI COPILOT
----------------------------------------------------------------- */}
<div className="xl:col-span-5 xl:sticky xl:top-4 space-y-4">
{/* LIVE 60FPS HYPERFRAMES STAGE CARD */}
<div className="fliki-card p-4 bg-white space-y-3">
<div className="flex items-center justify-between border-b border-zinc-100 pb-2.5">
<div className="flex items-center gap-2">
<span className="w-2 h-2 rounded-full bg-emerald-500" />
<h3 className="text-xs font-bold uppercase tracking-wider text-zinc-800">
HyperFrames 60fps Live Stage ({activeProject.aspectRatio})
</h3>
</div>
<div className="flex items-center gap-1.5">
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => setIframeKey((k) => k + 1)}
>
<RefreshCw className="w-3 h-3" />
<span>Phát lại</span>
</Button>
<Button
type="button"
variant="secondary"
size="sm"
onClick={handleOpenCodeInspector}
>
<Code2 className="w-3.5 h-3.5 text-[#E11D48]" />
<span>Mã HTML</span>
</Button>
</div>
</div>
{/* Iframe Preview Stage */}
<div className="w-full bg-zinc-100/90 rounded-2xl p-3 flex items-center justify-center border border-zinc-200/80 min-h-[360px]">
<div
className="relative overflow-hidden rounded-xl shadow-md bg-zinc-950 border border-zinc-300"
style={{
width:
activeProject.aspectRatio === '9:16'
? '260px'
: activeProject.aspectRatio === '1:1'
? '320px'
: '100%',
aspectRatio:
activeProject.aspectRatio === '9:16'
? '9 / 16'
: activeProject.aspectRatio === '1:1'
? '1 / 1'
: '16 / 9',
}}
>
<iframe
key={`${activeProject.id}-${iframeKey}`}
src={`/api/projects/${activeProject.id}/preview?t=${iframeKey}`}
title="HyperFrames 60fps Live Preview"
className="w-full h-full border-0"
sandbox="allow-scripts allow-same-origin"
/>
</div>
</div>
{/* Scene Scrubber Pills */}
<div className="space-y-1.5">
<div className="flex items-center justify-between text-[11px] font-semibold text-zinc-500">
<span>Thanh thời gian Phân cảnh (Timeline Scrubber)</span>
<span className="font-mono tabular-nums">
Tổng: {activeProject.totalDurationSec || 0}s
</span>
</div>
<div className="flex items-center gap-1.5 overflow-x-auto pb-1">
{localScenes.map((sc, i) => (
<button
key={sc.id || i}
type="button"
onClick={() => setSelectedSceneIdx(i)}
className={`px-2.5 py-1.5 rounded-xl text-xs font-mono tabular-nums font-semibold shrink-0 border transition-all cursor-pointer ${
selectedSceneIdx === i
? 'bg-[#E11D48] text-white border-[#E11D48] shadow-2xs'
: 'bg-zinc-50 hover:bg-zinc-100 text-zinc-700 border-zinc-200'
}`}
>
#{String(i + 1).padStart(2, '0')} {sc.role} ({sc.durationSec}s)
</button>
))}
</div>
</div>
</div>
{/* FLIKI AI PROMPT EDIT COPILOT CARD */}
<div className="fliki-card p-4 bg-white space-y-3">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<Wand2 className="w-4 h-4 text-[#E11D48]" />
<h3 className="text-xs font-bold uppercase tracking-wider text-zinc-900">
AI Prompt Edit Copilot
</h3>
</div>
<select
value={editTargetIdx}
onChange={(e) =>
setEditTargetIdx(
e.target.value === 'all' ? 'all' : Number(e.target.value)
)
}
className="bg-zinc-50 border border-zinc-200 rounded-lg px-2.5 py-1 text-xs font-semibold text-zinc-700 cursor-pointer"
>
<option value="all">Phạm vi: Tự động (JEV Router)</option>
{localScenes.map((sc, i) => (
<option key={sc.id || i} value={i}>
Chỉ sửa Cảnh #{String(i + 1).padStart(2, '0')} ({sc.role})
</option>
))}
</select>
</div>
<form onSubmit={handlePromptEdit} className="flex gap-2">
<input
type="text"
value={editPrompt}
onChange={(e) => setEditPrompt(e.target.value)}
placeholder="VD: Đổi lời thoại cảnh 1 ngắn gọn hơn, tạo lại ảnh cảnh 2 sáng đẹp..."
className="flex-1 bg-zinc-50 border border-zinc-200 focus:border-[#E11D48] focus:bg-white rounded-xl px-3.5 py-2 text-xs text-zinc-900 focus:outline-none"
/>
<Button
type="submit"
variant="primary"
disabled={editingBusy || !editPrompt.trim()}
>
<Sparkles className="w-3.5 h-3.5" />
<span>{editingBusy ? 'Đang sửa...' : 'Áp dụng AI'}</span>
</Button>
</form>
<div className="flex flex-wrap gap-1.5">
{[
`Tạo lại ảnh cho Cảnh ${selectedSceneIdx + 1} theo phong cách studio cao cấp`,
`Viết lại lời thoại Cảnh ${selectedSceneIdx + 1} cuốn hút và ngắn gọn hơn`,
`Đổi hiệu ứng Cảnh ${selectedSceneIdx + 1} sang thống kê số liệu dataviz-countup`,
].map((chip, i) => (
<button
key={i}
type="button"
onClick={() => setEditPrompt(chip)}
className="px-2.5 py-1 rounded-full bg-zinc-50 hover:bg-rose-50 text-zinc-600 hover:text-[#E11D48] border border-zinc-200 text-[11px] font-medium cursor-pointer"
>
+ {chip}
</button>
))}
</div>
{lastEditSummary && (
<div className="p-2.5 rounded-xl bg-emerald-50 border border-emerald-200 text-xs text-emerald-800 font-medium flex items-center gap-1.5">
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-600 shrink-0" />
<span>{lastEditSummary}</span>
</div>
)}
</div>
{/* RENDERED MP4 & SOCIAL PUBLISH KIT CARD */}
{(activeProject.renderOutputUrl || renderJobs.length > 0) && (
<div className="fliki-card p-4 bg-white space-y-3 border-emerald-200">
<div className="flex items-center justify-between">
<h3 className="text-xs font-bold uppercase tracking-wider text-zinc-900 flex items-center gap-1.5">
<Film className="w-3.5 h-3.5 text-emerald-600" />
<span>Xuất bản Video MP4 & Bộ Social Kit</span>
</h3>
{activeProject.renderOutputUrl && (
<div className="flex items-center gap-2">
<a
href={activeProject.renderOutputUrl}
download
className="px-3 py-1 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-semibold flex items-center gap-1"
>
<Download className="w-3 h-3" />
<span>Tải MP4</span>
</a>
<a
href={`/api/projects/${activeProject.id}/srt`}
download
className="px-3 py-1 rounded-lg bg-zinc-100 hover:bg-zinc-200 text-zinc-700 text-xs font-semibold flex items-center gap-1"
>
<Download className="w-3 h-3" />
<span>Phụ đề .SRT</span>
</a>
</div>
)}
</div>
{renderJobs[0] &&
['queued', 'bundling', 'rendering'].includes(renderJobs[0].status) && (
<div className="p-3 rounded-xl bg-zinc-50 border border-zinc-200 space-y-1.5">
<div className="flex justify-between text-xs font-bold text-zinc-900">
<span>
Đang Render MP4 qua{' '}
{renderJobs[0].provider === 'modal'
? 'Modal Serverless Cloud'
: 'Local CLI'}
...
</span>
<span className="font-mono tabular-nums text-[#E11D48]">
{renderJobs[0].progress}%
</span>
</div>
<div className="w-full h-2 bg-zinc-200 rounded-full overflow-hidden">
<div
className="h-full bg-[#E11D48] transition-all"
style={{ width: `${renderJobs[0].progress}%` }}
/>
</div>
</div>
)}
{activeProject.renderOutputUrl && (
<video
src={activeProject.renderOutputUrl}
controls
className="w-full max-h-[260px] rounded-xl bg-zinc-950"
/>
)}
{activeProject.socialKit && (
<div className="p-3 rounded-xl bg-zinc-50 border border-zinc-200 space-y-1.5 text-xs">
<div className="font-bold text-zinc-700">
Tiêu đề gợi ý đăng TikTok / YouTube / Reels:
</div>
<div className="text-zinc-900 font-medium">
{activeProject.socialKit.suggestedTitles?.[0]}
</div>
<div className="text-[#E11D48] font-mono text-[11px]">
{(activeProject.socialKit.hashtags || []).join(' ')}
</div>
</div>
)}
</div>
)}
</div>
</div>
)}
{/* =====================================================================
5. FLIKI 4-TAB SCENE MEDIA PICKER MODAL
===================================================================== */}
{mediaModalSceneIdx !== null && activeProject && (
<div className="fixed inset-0 z-50 bg-zinc-950/50 backdrop-blur-xs flex items-center justify-center p-4">
<div className="bg-white border border-zinc-200 rounded-2xl max-w-4xl w-full max-h-[88vh] flex flex-col shadow-2xl overflow-hidden">
{/* Modal Header */}
<div className="px-6 py-4 border-b border-zinc-100 flex items-center justify-between">
<div>
<h3 className="text-base font-bold text-zinc-900 flex items-center gap-2">
<ImageIcon className="w-4 h-4 text-[#E11D48]" />
<span>
Chọn hoặc Tạo Media cho Phân cảnh #{mediaModalSceneIdx + 1}: "
{localScenes[mediaModalSceneIdx]?.title}"
</span>
</h3>
<p className="text-xs text-zinc-500 mt-0.5">
Chọn từ Kho Tài nguyên đã phân tích Vision AI, tạo ảnh mới bằng FLUX.1/OpenAI, cào trực tiếp từ URL hoặc tìm ảnh thực tế.
</p>
</div>
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => setMediaModalSceneIdx(null)}
>
<X className="w-3.5 h-3.5" />
<span>Đóng</span>
</Button>
</div>
{/* 4-Tab Bar */}
<div className="px-6 pt-3 bg-zinc-50 border-b border-zinc-200 flex gap-2 overflow-x-auto">
{[
{
id: 'library',
label: `Kho Tài Nguyên Đã Có (${assets.length})`,
Icon: FolderOpen,
},
{
id: 'ai_gen',
label: 'Tạo Ảnh Tham Khảo AI (FLUX.1 / OpenAI)',
Icon: Sparkles,
},
{
id: 'url_scrape',
label: 'Cào Ảnh / Logo Từ URL Trang Web',
Icon: Globe,
},
{
id: 'web_search',
label: 'Tìm Ảnh Thực Tế Trên Web',
Icon: Search,
},
].map((t) => {
const Icon = t.Icon;
return (
<button
key={t.id}
type="button"
onClick={() => setMediaModalTab(t.id as any)}
className={`px-4 py-2.5 rounded-t-xl text-xs font-semibold border-b-2 transition-all cursor-pointer flex items-center gap-1.5 ${
mediaModalTab === t.id
? 'bg-white text-[#E11D48] border-[#E11D48]'
: 'text-zinc-600 border-transparent hover:text-zinc-900'
}`}
>
<Icon className="w-3.5 h-3.5" />
<span>{t.label}</span>
</button>
);
})}
</div>
{/* Modal Content */}
<div className="p-6 overflow-y-auto flex-1 space-y-4">
{modalMediaMessage && (
<div className="p-3 rounded-xl bg-zinc-100 border border-zinc-200 text-xs font-semibold text-zinc-800">
{modalMediaMessage}
</div>
)}
{/* TAB 1: ASSET LIBRARY */}
{mediaModalTab === 'library' && (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3.5">
{assets.map((ast) => (
<div
key={ast.id}
onClick={() => handleAssignAssetToScene(ast)}
className="group border border-zinc-200 hover:border-[#E11D48] rounded-xl overflow-hidden bg-white cursor-pointer shadow-2xs hover:shadow-md transition-all flex flex-col"
>
<div className="aspect-square bg-zinc-100 relative overflow-hidden">
<img
src={ast.publicUrl}
alt={ast.name}
className="w-full h-full object-cover group-hover:scale-105 transition-transform"
/>
<span className="absolute top-2 left-2 px-2 py-0.5 rounded-md bg-zinc-900/75 text-white text-[10px] font-mono font-semibold">
{ast.source}
</span>
</div>
<div className="p-2.5">
<div className="text-xs font-bold text-zinc-800 truncate">
{ast.name}
</div>
<div className="text-[11px] text-zinc-500 line-clamp-1 mt-0.5">
{ast.analysis?.shortCaption ||
ast.analysis?.subject ||
'Bấm để gán vào cảnh'}
</div>
</div>
</div>
))}
</div>
)}
{/* TAB 2: AI IMAGE GENERATOR */}
{mediaModalTab === 'ai_gen' && (
<div className="space-y-3 max-w-2xl">
<label className="block text-xs font-semibold text-zinc-700">
Prompt mô tả hình ảnh cần tạo cho Phân cảnh #{mediaModalSceneIdx + 1}:
</label>
<textarea
rows={3}
value={modalImagePrompt}
onChange={(e) => setModalImagePrompt(e.target.value)}
className="w-full bg-zinc-50 border border-zinc-200 rounded-xl p-3.5 text-sm text-zinc-900 focus:outline-none focus:border-[#E11D48]"
placeholder="Mô tả chi tiết hình ảnh tham khảo cần tạo..."
/>
<Button
type="button"
variant="primary"
onClick={handleModalGenerateAiImage}
disabled={modalMediaBusy}
>
<Sparkles className="w-3.5 h-3.5" />
<span>
{modalMediaBusy
? 'Đang tạo ảnh AI...'
: 'Tạo Ảnh AI Mới & Gán Vào Phân Cảnh Này'}
</span>
</Button>
</div>
)}
{/* TAB 3: URL SCRAPER */}
{mediaModalTab === 'url_scrape' && (
<div className="space-y-3 max-w-2xl">
<label className="block text-xs font-semibold text-zinc-700">
Nhập URL trang sản phẩm / bài viết cần cào ảnh & logo:
</label>
<div className="flex gap-2">
<input
type="url"
value={modalScrapeUrl}
onChange={(e) => setModalScrapeUrl(e.target.value)}
placeholder="https://example.com/product"
className="flex-1 bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-sm text-zinc-900"
/>
<Button
type="button"
variant="primary"
onClick={handleModalScrapeUrl}
disabled={modalMediaBusy}
>
<Globe className="w-3.5 h-3.5" />
<span>
{modalMediaBusy ? 'Đang cào & phân tích...' : 'Cào Ảnh & Phân Tích AI'}
</span>
</Button>
</div>
</div>
)}
{/* TAB 4: WEB SEARCH */}
{mediaModalTab === 'web_search' && (
<div className="space-y-3 max-w-2xl">
<label className="block text-xs font-semibold text-zinc-700">
Từ khóa tìm kiếm hình ảnh thực tế (Wikimedia / Openverse):
</label>
<div className="flex gap-2">
<input
type="text"
value={modalWebQuery}
onChange={(e) => setModalWebQuery(e.target.value)}
placeholder="VD: coffee shop, skincare serum, electric car..."
className="flex-1 bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-sm text-zinc-900"
/>
<Button
type="button"
variant="primary"
onClick={handleModalSearchWeb}
disabled={modalMediaBusy}
>
<Search className="w-3.5 h-3.5" />
<span>{modalMediaBusy ? 'Đang tìm...' : 'Tìm Ảnh Web'}</span>
</Button>
</div>
</div>
)}
</div>
</div>
</div>
)}
{/* =====================================================================
6. HYPERFRAMES HTML5 + GSAP CODE INSPECTOR MODAL
===================================================================== */}
{showCodeModal && (
<div className="fixed inset-0 z-50 bg-zinc-950/50 backdrop-blur-xs flex items-center justify-center p-4">
<div className="bg-white border border-zinc-200 rounded-2xl max-w-5xl w-full max-h-[85vh] flex flex-col shadow-2xl overflow-hidden">
<div className="px-6 py-4 border-b border-zinc-100 flex items-center justify-between">
<div>
<h3 className="text-base font-bold text-zinc-900 flex items-center gap-2">
<Code2 className="w-4 h-4 text-[#E11D48]" />
<span>
Mã Nguồn HyperFrames Composition (index.html • Deterministic GSAP)
</span>
</h3>
<p className="text-xs text-zinc-500 mt-0.5">
Đã qua kiểm định JEV & Self-Healing Validator (WCAG AA Contrast, Safe-Zone, __hf Timeline).
</p>
</div>
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => setShowCodeModal(false)}
>
<X className="w-3.5 h-3.5" />
<span>Đóng</span>
</Button>
</div>
<pre className="p-5 bg-zinc-950 text-emerald-300 text-xs font-mono overflow-auto flex-1 leading-relaxed">
{rawHtmlCode}
</pre>
</div>
</div>
)}
</div>
);
};
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<Props> = ({
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<AspectRatio>('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('');