import { useState, useRef, useCallback } from 'react'; import { Upload, Image, Loader2, Send, Check, Download, ArrowRight, ArrowLeft, Sparkles, Video, Type, X, Plus, MessageSquare, FileText, Youtube, AlertCircle, Settings } from 'lucide-react'; import { getApiUrl } from '../config'; import { apiFetch } from '../lib/api'; import StepIndicator from './ui/StepIndicator'; import SegmentedControl from './ui/SegmentedControl'; const STEPS = ['Input', 'Titles', 'Generate', 'Description', 'Publish']; function DragDropZone({ label, accept, onFile, file, onClear, icon }) { const Icon = icon; const [isDragging, setIsDragging] = useState(false); const inputRef = useRef(null); const handleDrop = useCallback((e) => { e.preventDefault(); setIsDragging(false); const f = e.dataTransfer.files[0]; if (f) onFile(f); }, [onFile]); const handleDragOver = useCallback((e) => { e.preventDefault(); setIsDragging(true); }, []); if (file) { return (
{file.type?.startsWith('image/') ? ( ) : (
)}

{file.name}

{(file.size / 1024 / 1024).toFixed(1)} MB

); } return (
inputRef.current?.click()} onDrop={handleDrop} onDragOver={handleDragOver} onDragLeave={() => setIsDragging(false)} className={`border-2 border-dashed rounded-card p-6 text-center cursor-pointer transition-colors duration-200 ${isDragging ? 'border-brass bg-paper3' : 'border-rule2 hover:border-brass' }`} >

{label}

Drop or click to upload

e.target.files[0] && onFile(e.target.files[0])} />
); } export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUserId, managed = false }) { // Managed (hosted plan): Gemini runs server-side via the bearer token, no BYOK key. // Only send X-Gemini-Key for self-host BYOK. apiFetch attaches the bearer token. const keyHeader = geminiApiKey ? { 'X-Gemini-Key': geminiApiKey } : {}; const needsKey = !geminiApiKey && !managed; // Step management const [step, setStep] = useState(0); const [mode, setMode] = useState(null); // 'video' or 'manual' // Step 1 state const [videoFile, setVideoFile] = useState(null); const [isAnalyzing, setIsAnalyzing] = useState(false); // Step 2 state const [sessionId, setSessionId] = useState(null); const [titles, setTitles] = useState([]); const [selectedTitle, setSelectedTitle] = useState(''); const [manualTitle, setManualTitle] = useState(''); const [chatInput, setChatInput] = useState(''); const [chatHistory, setChatHistory] = useState([]); const [isRefining, setIsRefining] = useState(false); const [recommended, setRecommended] = useState([]); // [{index, reason}] // Step 3 state const [faceImage, setFaceImage] = useState(null); const [bgImage, setBgImage] = useState(null); const [extraPrompt, setExtraPrompt] = useState(''); const [thumbnailCount, setThumbnailCount] = useState(3); const [isGenerating, setIsGenerating] = useState(false); const [generatedThumbnails, setGeneratedThumbnails] = useState([]); // Description state const [description, setDescription] = useState(''); const [isDescribing, setIsDescribing] = useState(false); // Step 4 (Publish) state const [selectedThumbnail, setSelectedThumbnail] = useState(null); const [isPublishing, setIsPublishing] = useState(false); const [publishResult, setPublishResult] = useState(null); // Background preprocessing state const [preprocessSessionId, setPreprocessSessionId] = useState(null); const [isPreprocessing, setIsPreprocessing] = useState(false); const chatEndRef = useRef(null); const scrollToBottom = () => { chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }; // --- Background Pre-upload (starts Whisper immediately) --- const handlePreUpload = async (file) => { setPreprocessSessionId(null); setIsPreprocessing(true); try { const formData = new FormData(); formData.append('file', file); const res = await apiFetch('/api/thumbnail/upload', { method: 'POST', body: formData }); if (res.ok) { const data = await res.json(); setPreprocessSessionId(data.session_id); console.log(`🎙️ Background Whisper started: ${data.session_id}`); } } catch (e) { console.error('Pre-upload failed:', e); } finally { setIsPreprocessing(false); } }; // --- Step 1: Analyze Video --- const handleAnalyze = async () => { if (needsKey) return alert('Please set your Gemini API key in Settings first.'); setIsAnalyzing(true); try { const formData = new FormData(); if (preprocessSessionId) { // Use pre-uploaded session (Whisper already running/done in background) formData.append('session_id', preprocessSessionId); } else if (videoFile) { formData.append('file', videoFile); } else { return alert('Please upload a video file.'); } const res = await apiFetch('/api/thumbnail/analyze', { method: 'POST', headers: keyHeader, body: formData }); if (!res.ok) { const err = await res.text(); throw new Error(err); } const data = await res.json(); setSessionId(data.session_id); setTitles(data.titles || []); setRecommended(data.recommended || []); setChatHistory([{ role: 'assistant', content: `Here are 10 viral title suggestions based on your video. Titles marked TOP PICK are my top picks. Click one to select it, or tell me how to refine them.` }]); setStep(1); } catch (e) { alert(`Analysis failed: ${e.message}`); } finally { setIsAnalyzing(false); } }; const handleManualMode = () => { setMode('manual'); setStep(1); }; // --- Step 2: Title Selection / Refinement --- const handleSelectTitle = (title) => { setSelectedTitle(title); }; const handleConfirmTitle = () => { if (mode === 'manual' && manualTitle) { setSelectedTitle(manualTitle); // Create session for manual mode const newSessionId = sessionId || crypto.randomUUID(); setSessionId(newSessionId); apiFetch('/api/thumbnail/titles', { method: 'POST', headers: { 'Content-Type': 'application/json', ...keyHeader }, body: JSON.stringify({ title: manualTitle, session_id: newSessionId }) }).catch(() => { }); } if (selectedTitle || (mode === 'manual' && manualTitle)) { setStep(2); } }; const handleRefine = async () => { if (!chatInput.trim() || !sessionId) return; setIsRefining(true); const userMsg = chatInput.trim(); setChatInput(''); setChatHistory(prev => [...prev, { role: 'user', content: userMsg }]); try { const res = await apiFetch('/api/thumbnail/titles', { method: 'POST', headers: { 'Content-Type': 'application/json', ...keyHeader }, body: JSON.stringify({ session_id: sessionId, message: userMsg }) }); if (!res.ok) throw new Error(await res.text()); const data = await res.json(); setTitles(data.titles || []); setChatHistory(prev => [...prev, { role: 'assistant', content: `Here are refined titles based on your feedback. Click one to select it.` }]); setTimeout(scrollToBottom, 100); } catch (e) { setChatHistory(prev => [...prev, { role: 'assistant', content: `Failed to refine: ${e.message}` }]); } finally { setIsRefining(false); } }; // --- Step 3: Generate Thumbnails --- const handleGenerate = async () => { if (needsKey) return alert('Please set your Gemini API key in Settings first.'); const finalTitle = selectedTitle || manualTitle; if (!finalTitle) return alert('Please select or enter a title first.'); setIsGenerating(true); setGeneratedThumbnails([]); try { const formData = new FormData(); formData.append('session_id', sessionId || 'manual'); formData.append('title', finalTitle); formData.append('extra_prompt', extraPrompt); formData.append('count', thumbnailCount); if (faceImage) formData.append('face', faceImage); if (bgImage) formData.append('background', bgImage); const res = await apiFetch('/api/thumbnail/generate', { method: 'POST', headers: keyHeader, body: formData }); if (!res.ok) { const errData = await res.json().catch(() => null); throw new Error(errData?.detail || `Server error ${res.status}`); } const data = await res.json(); if (!data.thumbnails || data.thumbnails.length === 0) { throw new Error('No thumbnails were generated. Your Gemini API key may not have access to image generation.'); } setGeneratedThumbnails(data.thumbnails); } catch (e) { alert(`Generation failed: ${e.message}`); } finally { setIsGenerating(false); } }; const handleDownload = async (url) => { try { const response = await fetch(getApiUrl(url)); const blob = await response.blob(); const blobUrl = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = blobUrl; a.download = url.split('/').pop() || 'thumbnail.png'; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(blobUrl); } catch { // Fallback: open in new tab if fetch fails window.open(getApiUrl(url), '_blank'); } }; // --- Description Generation --- const handleGenerateDescription = async () => { if (needsKey) return alert('Please set your Gemini API key in Settings first.'); const finalTitle = selectedTitle || manualTitle; if (!finalTitle) return alert('Please select a title first.'); if (!sessionId) return alert('No session available.'); setIsDescribing(true); try { const res = await apiFetch('/api/thumbnail/describe', { method: 'POST', headers: { 'Content-Type': 'application/json', ...keyHeader }, body: JSON.stringify({ session_id: sessionId, title: finalTitle }) }); if (!res.ok) { const err = await res.text(); throw new Error(err); } const data = await res.json(); setDescription(data.description || ''); } catch (e) { alert(`Description generation failed: ${e.message}`); } finally { setIsDescribing(false); } }; // --- Publish to YouTube --- const handlePublish = async () => { if (!managed && (!uploadPostKey || !uploadUserId)) return alert('Please configure your Upload-Post API key and user in Settings first.'); const finalTitle = selectedTitle || manualTitle; if (!finalTitle) return alert('No title selected.'); if (!selectedThumbnail) return alert('Please select a thumbnail first.'); if (!description) return alert('Please generate or write a description first.'); setIsPublishing(true); setPublishResult(null); try { const formData = new FormData(); formData.append('session_id', sessionId); formData.append('title', finalTitle); formData.append('description', description); formData.append('thumbnail_url', selectedThumbnail); formData.append('api_key', uploadPostKey); formData.append('user_id', uploadUserId); // Submit the publish job — returns immediately with a publish_id const res = await apiFetch('/api/thumbnail/publish', { method: 'POST', body: formData }); if (!res.ok) { const err = await res.text(); throw new Error(err); } const { publish_id } = await res.json(); // Poll for status every 2 seconds (upload can take minutes for large videos) await new Promise((resolve, reject) => { const interval = setInterval(async () => { try { const statusRes = await fetch(getApiUrl(`/api/thumbnail/publish/status/${publish_id}`)); if (!statusRes.ok) { clearInterval(interval); reject(new Error('Status check failed')); return; } const statusData = await statusRes.json(); if (statusData.status === 'done') { clearInterval(interval); setPublishResult({ success: true, data: statusData.result }); resolve(); } else if (statusData.status === 'failed') { clearInterval(interval); reject(new Error(statusData.error || 'Upload failed')); } // 'uploading' → keep polling } catch (e) { clearInterval(interval); reject(e); } }, 2000); }); } catch (e) { setPublishResult({ success: false, error: e.message }); } finally { setIsPublishing(false); } }; const handleReset = () => { setStep(0); setMode(null); setVideoFile(null); setSessionId(null); setTitles([]); setSelectedTitle(''); setManualTitle(''); setChatInput(''); setChatHistory([]); setFaceImage(null); setBgImage(null); setExtraPrompt(''); setGeneratedThumbnails([]); setDescription(''); setIsDescribing(false); setSelectedThumbnail(null); setIsPublishing(false); setPublishResult(null); setPreprocessSessionId(null); setIsPreprocessing(false); setRecommended([]); }; return (
{/* Header */}

05 · YOUTUBE STUDIO

YouTube Studio

{step > 0 && ( )}

Generate viral titles, AI thumbnails, descriptions and publish directly to YouTube

{/* Gemini API Key Warning (self-host BYOK only; managed uses server key) */} {needsKey && (

Gemini API Key Required

YouTube Studio requires a Google Gemini API key to function. Please configure it in the Settings tab before using this feature. Gemini's free tier includes 1,500 requests per day.

)} {/* ===== STEP 0: Input Mode Selection ===== */} {step === 0 && (
{/* Mode A: Video Analysis */}

A · ANALYZE VIDEO

AI suggests viral titles from your content

{ setVideoFile(f); setMode('video'); handlePreUpload(f); }} file={videoFile} onClear={() => { setVideoFile(null); setPreprocessSessionId(null); }} icon={Video} /> {isPreprocessing && (
Pre-processing video (Whisper transcription starting)...
)} {preprocessSessionId && !isPreprocessing && (
Video uploaded — transcription running in background
)}
{/* Mode B: Manual Title */}

B · WRITE YOUR OWN

Skip analysis, enter your title directly

setManualTitle(e.target.value)} placeholder="Enter your YouTube title..." className="input-field text-sm mb-4" maxLength={70} />

{manualTitle.length} / 70

)} {/* ===== STEP 1: Title Selection ===== */} {step === 1 && (
{/* Left: Chat / Controls */}
{mode === 'manual' ? (

YOUR TITLE

setManualTitle(e.target.value)} className="input-field text-sm" maxLength={70} />

{manualTitle.length} / 70

) : (
TITLE REFINEMENT CHAT
{/* Chat messages */}
{chatHistory.map((msg, i) => (
{msg.content}
))}
{/* Chat input */}
setChatInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && !e.shiftKey && handleRefine()} placeholder="Make them more clickbait..." className="input-field text-xs flex-1" disabled={isRefining} />
)} {mode !== 'manual' && selectedTitle && ( )}
{/* Right: Title Cards */}
{selectedTitle && (
Selected: {selectedTitle}
)} {titles.length > 0 && (
{titles.map((title, i) => { const rec = recommended.find(r => r.index === i); const recRank = recommended.findIndex(r => r.index === i); return ( ); })}
)} {isRefining && (
Refining titles...
)}
)} {/* ===== STEP 2: Thumbnail Generation ===== */} {step === 2 && (
{/* Left: Controls */}

TITLE

{selectedTitle || manualTitle}

FACE IMAGE · OPTIONAL

setFaceImage(null)} icon={Upload} />

BACKGROUND · OPTIONAL

setBgImage(null)} icon={Image} />

INSTRUCTIONS · OPTIONAL