import { useState, useEffect } from 'react'; import { Globe, Sparkles, Download, Copy, Check, ChevronRight, ChevronLeft, Loader2, AlertCircle, Volume2, User, Film, Terminal, ChevronDown, RefreshCw, Share2, Calendar, Upload } from 'lucide-react'; import { getApiUrl } from '../config'; import { apiFetch } from '../lib/api'; import StepIndicator from './ui/StepIndicator'; import SegmentedControl from './ui/SegmentedControl'; import StarBanner from './StarBanner'; const STYLE_OPTIONS = [ { id: 'ugc', label: 'UGC Natural', desc: 'Authentic, talking to camera' }, { id: 'educational', label: 'Educational', desc: 'Clear explanations' }, { id: 'shock', label: 'Shock/Discovery', desc: 'Surprising opener' }, { id: 'story', label: 'Storytelling', desc: 'Mini narrative arc' }, { id: 'comparison', label: 'Before/After', desc: 'Comparison style' }, ]; const STEPS = ['Setup', 'Analysis', 'Configure', 'Generate', 'Result']; const CACHE_KEY = 'saasshorts_cache'; const CACHE_MAX_AGE = 24 * 60 * 60 * 1000; // 24 hours function loadCache() { try { const raw = localStorage.getItem(CACHE_KEY); if (!raw) return null; const cache = JSON.parse(raw); if (Date.now() - cache.timestamp > CACHE_MAX_AGE) { localStorage.removeItem(CACHE_KEY); return null; } return cache; } catch { return null; } } function saveCache(url, analysis, webResearch, scripts) { try { localStorage.setItem(CACHE_KEY, JSON.stringify({ url, analysis, webResearch, scripts, timestamp: Date.now(), })); } catch { /* localStorage full */ } } export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uploadPostKey, uploadUserId, managed = false }) { // Managed (hosted plan): Gemini (script) + Upload-Post run server-side via the // bearer token — no BYOK Gemini key needed. fal.ai + ElevenLabs stay BYOK. const geminiHeader = geminiApiKey ? { 'X-Gemini-Key': geminiApiKey } : {}; const needsGeminiKey = !geminiApiKey && !managed; // Wizard state const [step, setStep] = useState(() => { const cache = loadCache(); return cache ? 1 : 0; }); // Step 0: URL input const [url, setUrl] = useState(() => loadCache()?.url || ''); const [videoMode, setVideoMode] = useState('lowcost'); // "lowcost" or "premium" const [description, setDescription] = useState(''); const [style, setStyle] = useState('ugc'); const [language, setLanguage] = useState('en'); const [actorGender, setActorGender] = useState('female'); const [numScripts, setNumScripts] = useState(3); const [analyzing, setAnalyzing] = useState(false); const [analyzeError, setAnalyzeError] = useState(''); const [fromCache, setFromCache] = useState(() => !!loadCache()); // Step 1: Analysis results const [analysis, setAnalysis] = useState(() => loadCache()?.analysis || null); const [webResearch, setWebResearch] = useState(() => loadCache()?.webResearch || null); const [scripts, setScripts] = useState(() => loadCache()?.scripts || []); const [selectedScript, setSelectedScript] = useState(0); // Step 2: Configure const [shareToGallery, setShareToGallery] = useState(false); const [voices, setVoices] = useState([]); const [selectedVoice, setSelectedVoice] = useState('21m00Tcm4TlvDq8ikWAM'); const [actorDescription, setActorDescription] = useState(''); const [editedNarration, setEditedNarration] = useState(''); const [actorOptions, setActorOptions] = useState([]); const [selectedActor, setSelectedActor] = useState(null); const [generatingActors, setGeneratingActors] = useState(false); const [actorGallery, setActorGallery] = useState([]); const [loadingGallery, setLoadingGallery] = useState(false); const [uploadedActorPreview, setUploadedActorPreview] = useState(null); // {localPreview, serverUrl} const [productPhoto, setProductPhoto] = useState(null); // {preview, serverUrl} const [productDescription, setProductDescription] = useState(''); // Step 3: Generate const [generating, setGenerating] = useState(false); const [jobId, setJobId] = useState(null); const [genLogs, setGenLogs] = useState([]); const [genStatus, setGenStatus] = useState('idle'); const [genResult, setGenResult] = useState(null); // Publish const [publishing, setPublishing] = useState(false); const [publishResult, setPublishResult] = useState(null); const [publishPlatforms, setPublishPlatforms] = useState({ tiktok: true, instagram: true, youtube: true }); const [isScheduling, setIsScheduling] = useState(false); const [scheduleDate, setScheduleDate] = useState(''); // UI const [copied, setCopied] = useState(''); const [logsExpanded, setLogsExpanded] = useState(true); // Pre-fill from cache on mount useEffect(() => { if (fromCache && scripts.length > 0 && !actorDescription) { setActorDescription(scripts[0].actor_description || ''); setEditedNarration(scripts[0].full_narration || ''); } }, []); // Fetch actor gallery on mount useEffect(() => { setLoadingGallery(true); fetch(getApiUrl('/api/saasshorts/actor-gallery')) .then(res => res.ok ? res.json() : { images: [] }) .then(data => setActorGallery(data.images || [])) .catch(() => {}) .finally(() => setLoadingGallery(false)); }, []); // Fetch voices on mount useEffect(() => { if (elevenLabsKey) { fetchVoices(); } }, [elevenLabsKey]); // Reset selected voice when actor gender changes useEffect(() => { const genderDefaults = { 'en-female': '21m00Tcm4TlvDq8ikWAM', // Rachel 'en-male': '29vD33N1CtxCmqQRPOHJ', // Drew 'es-female': 'EXAVITQu4vr4xnSDxMaL', // Bella 'es-male': 'ErXwobaYiN019PkySvjV', // Antoni }; // If we have fetched voices, pick the first matching one; otherwise use hardcoded default const matchingVoice = voices.find(v => (v.labels?.gender || '').toLowerCase() === actorGender); if (matchingVoice) { setSelectedVoice(matchingVoice.voice_id); } else { setSelectedVoice(genderDefaults[`${language}-${actorGender}`] || genderDefaults['en-female']); } }, [actorGender, language]); // Poll generation status useEffect(() => { let interval; if (jobId && genStatus === 'processing') { interval = setInterval(async () => { try { const res = await apiFetch(`/api/saasshorts/status/${jobId}`); if (res.status === 404) { // Job lost (server restart) — treat as failed so Retry appears setGenStatus('failed'); setGenerating(false); setGenLogs((prev) => [...prev, 'Job lost after server restart. Click Retry to resume from cached assets.']); clearInterval(interval); return; } if (!res.ok) return; const data = await res.json(); if (data.logs) setGenLogs(data.logs); if (data.status === 'completed') { setGenStatus('completed'); setGenResult(data.result); setGenerating(false); setStep(4); clearInterval(interval); } else if (data.status === 'failed') { setGenStatus('failed'); setGenerating(false); clearInterval(interval); } } catch (e) { console.error('Poll error:', e); } }, 2000); } return () => clearInterval(interval); }, [jobId, genStatus]); const fetchVoices = async () => { try { const res = await fetch(getApiUrl('/api/saasshorts/voices'), { headers: { 'X-ElevenLabs-Key': elevenLabsKey }, }); if (res.ok) { const data = await res.json(); setVoices(data.voices || []); } } catch (e) { console.error('Voices fetch error:', e); } }; const handleAnalyze = async () => { if (!url.trim() && !description.trim()) return; if (needsGeminiKey) { setAnalyzeError('Gemini API key required. Set it in Settings.'); return; } setAnalyzing(true); setAnalyzeError(''); try { const res = await apiFetch('/api/saasshorts/analyze', { method: 'POST', headers: { 'Content-Type': 'application/json', ...geminiHeader, }, body: JSON.stringify({ url: url.trim() || undefined, description: description.trim() || undefined, num_scripts: numScripts, style, language, actor_gender: actorGender, }), }); if (!res.ok) { let msg = 'Analysis failed'; try { const err = await res.json(); msg = err.detail || msg; } catch { msg = await res.text() || msg; } throw new Error(msg); } const data = await res.json(); setAnalysis(data.analysis); setWebResearch(data.web_research || null); setScripts(data.scripts); setSelectedScript(0); setFromCache(false); // Cache results saveCache(url.trim(), data.analysis, data.web_research, data.scripts); // Pre-fill actor description and narration from first script if (data.scripts.length > 0) { setActorDescription(data.scripts[0].actor_description || ''); setEditedNarration(data.scripts[0].full_narration || ''); } setStep(1); } catch (e) { setAnalyzeError(e.message); } finally { setAnalyzing(false); } }; const handleSelectScript = (idx) => { setSelectedScript(idx); if (scripts[idx]) { setActorDescription(scripts[idx].actor_description || ''); setEditedNarration(scripts[idx].full_narration || ''); } }; const handleGenerate = async () => { if (!falKey) { alert('fal.ai API key required. Set it in Settings.'); return; } if (!elevenLabsKey) { alert('ElevenLabs API key required. Set it in Settings.'); return; } setGenerating(true); setGenLogs(['Starting video generation...']); setGenStatus('processing'); setGenResult(null); setStep(3); try { // Update script with edited narration const scriptToSend = { ...scripts[selectedScript] }; scriptToSend._product_name = analysis?.product_name || analysis?.name || ''; scriptToSend._product_url = url; if (editedNarration !== scriptToSend.full_narration) { scriptToSend.full_narration = editedNarration; } const res = await apiFetch('/api/saasshorts/generate', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Fal-Key': falKey, 'X-ElevenLabs-Key': elevenLabsKey, }, body: JSON.stringify({ script: scriptToSend, voice_id: selectedVoice, actor_description: actorDescription || undefined, selected_actor_url: selectedActor || undefined, video_mode: videoMode, share_to_gallery: shareToGallery, }), }); if (!res.ok) { let msg = 'Generation failed'; try { const err = await res.json(); msg = err.detail || msg; } catch { msg = await res.text() || msg; } throw new Error(msg); } const data = await res.json(); setJobId(data.job_id); } catch (e) { setGenStatus('failed'); setGenLogs((prev) => [...prev, `Error: ${e.message}`]); setGenerating(false); } }; const handleRetry = async () => { if (!jobId) return; setGenerating(true); setGenLogs(['Retrying from cached assets...']); setGenStatus('processing'); setGenResult(null); try { const scriptToSend = { ...scripts[selectedScript] }; scriptToSend._product_name = analysis?.product_name || analysis?.name || ''; scriptToSend._product_url = url; if (editedNarration !== scriptToSend.full_narration) { scriptToSend.full_narration = editedNarration; } const res = await apiFetch('/api/saasshorts/generate', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Fal-Key': falKey, 'X-ElevenLabs-Key': elevenLabsKey, }, body: JSON.stringify({ script: scriptToSend, voice_id: selectedVoice, actor_description: actorDescription || undefined, retry_job_id: jobId, video_mode: videoMode, share_to_gallery: shareToGallery, }), }); if (!res.ok) { let msg = 'Retry failed'; try { const err = await res.json(); msg = err.detail || msg; } catch { msg = await res.text() || msg; } throw new Error(msg); } const data = await res.json(); setJobId(data.job_id); } catch (e) { setGenStatus('failed'); setGenLogs((prev) => [...prev, `Retry error: ${e.message}`]); setGenerating(false); } }; const handleCopy = (text, label) => { navigator.clipboard.writeText(text); setCopied(label); setTimeout(() => setCopied(''), 2000); }; const handleReset = () => { setStep(0); setUrl(''); setAnalyzeError(''); setAnalysis(null); setWebResearch(null); setScripts([]); setFromCache(false); localStorage.removeItem(CACHE_KEY); setSelectedScript(0); setJobId(null); setGenLogs([]); setGenStatus('idle'); setGenResult(null); setGenerating(false); setActorDescription(''); setEditedNarration(''); }; // ─── Render Steps ───────────────────────────────────────────────── return (
{/* Header */}

02 · AI SHORTS

AI Shorts

{step > 0 && ( )}

Generate viral UGC videos for any product or business

{/* Progress Steps */}
{/* ── Step 0: URL Input ────────────────────────────────── */} {step === 0 && (
{/* Video Mode Selector */}
setUrl(e.target.value)} placeholder="https://your-website.com" className="input-field pl-10" onKeyDown={(e) => e.key === 'Enter' && handleAnalyze()} />

If provided, we'll scrape and research your site automatically