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 */}
{step > 0 && (
Start over
)}
Generate viral UGC videos for any product or business
{/* Progress Steps */}
{/* ── Step 0: URL Input ────────────────────────────────── */}
{step === 0 && (
{/* Video Mode Selector */}
Video Mode
setVideoMode('lowcost')}
className={`card card-hover p-4 text-left ${
videoMode === 'lowcost' ? 'border-brass' : ''
}`}
>
Low Cost
recommended
~$0.80 / VIDEO
Hailuo 2.3 img2video + VEED Lipsync. Good movement + lip-sync.
setVideoMode('premium')}
className={`card card-hover p-4 text-left ${
videoMode === 'premium' ? 'border-brass' : ''
}`}
>
Premium
best quality
~$2.00 / VIDEO
Kling Avatar v2 Standard. Full integrated movement.
Website URL (optional)
If provided, we'll scrape and research your site automatically
{url.trim() ? 'Extra context' : 'Describe your product/business'} {url.trim() ? '(optional)' : '(required if no URL)'}
Language
Actor
Video Style
({ value: s.id, label: s.label, hint: s.desc }))}
value={style}
onChange={setStyle}
columns={5}
/>
Number of Scripts
({ value: n, label: String(n) }))}
value={numScripts}
onChange={setNumScripts}
size="sm"
/>
{analyzeError && (
)}
{analyzing ? (
<>
{url.trim() ? 'Scraping + researching web + generating scripts... (45-90s)' : 'Generating scripts... (20-40s)'}
>
) : (
<>
{url.trim() ? 'research & generate scripts' : 'generate scripts'}
>
)}
{/* Info cards */}
Deep Research
AI analyzes your product via URL scraping + web research, or generates directly from your description.
Pain Point Scripts
Generates hook-problem-solution scripts targeting your audience's real pain points.
AI Actor Videos
Realistic AI-generated actors with lip-sync, b-roll, and viral subtitles. From ~$0.50/video.
)}
{/* ── Step 1: Analysis Results ─────────────────────────── */}
{step === 1 && analysis && (
{/* Analysis Summary */}
{analysis.product_name || 'Analysis'}
{fromCache && (
cached
{ setStep(0); setFromCache(false); }} className="hover:text-ink transition-colors" title="Re-analyze">
)}
{analysis.industry}
{analysis.one_liner}
Pain Points
{(analysis.pain_points || []).map((pp, i) => (
{[0, 1, 2].map((d) => (
))}
{pp.pain}
{pp.source && pp.source !== 'website' && (
{pp.source}
)}
))}
Emotional Hooks
{(analysis.emotional_hooks || []).map((h, i) => (
{h}
))}
{/* Web Research Results */}
{webResearch && (
Web Research
{webResearch.grounding_sources && (
{webResearch.grounding_sources.length} sources
)}
{/* Real user reviews */}
{webResearch.real_reviews && webResearch.real_reviews.length > 0 && (
Real User Reviews
{webResearch.real_reviews.slice(0, 5).map((review, i) => (
"{review.quote}"
{review.source}
{review.sentiment}
))}
)}
{/* Competitors */}
{webResearch.competitors && webResearch.competitors.length > 0 && (
Competitors
{webResearch.competitors.map((c, i) => (
{c.name}
))}
)}
{/* Sources */}
{webResearch.grounding_sources && webResearch.grounding_sources.length > 0 && (
)}
)}
{/* Scripts */}
Generated Scripts
{scripts.length} scripts
{scripts.map((script, i) => (
handleSelectScript(i)}
className={`card card-hover p-5 cursor-pointer ${
selectedScript === i ? 'border-brass' : ''
}`}
>
{String(i + 1).padStart(2, '0')}
{script.title}
{script.duration_seconds}s · {script.style} · {script.target_platform}
{selectedScript === i && (
selected
)}
{/* Segments preview */}
{(script.segments || []).map((seg, j) => (
))}
hook · problem · solution
{(script.segments || []).map((seg, j) => (
{seg.type}
{seg.narration}
))}
{/* Hook text & hashtags */}
hook
"{script.hook_text}"
{(script.hashtags || []).slice(0, 4).map((tag, j) => (
{tag}
))}
))}
setStep(0)} className="btn-ghost px-4 py-2 text-sm">
Back
setStep(2)} className="btn-primary px-6 py-2 text-sm">
Configure video
)}
{/* ── Step 2: Configure ────────────────────────────────── */}
{step === 2 && scripts[selectedScript] && (
Configure Video
script: {scripts[selectedScript].title}
{/* Voice Selection */}
Voice {language === 'es' ? '(Spanish)' : '(English)'}
{(() => {
// Filter voices by language/accent
const filtered = voices.length > 0
? voices.filter((v) => {
const gender = (v.labels?.gender || '').toLowerCase();
// Only show voices that match the selected gender
return gender === actorGender;
})
.sort((a, b) => {
const aAccent = (a.labels?.accent || '').toLowerCase();
const bAccent = (b.labels?.accent || '').toLowerCase();
if (language === 'es') {
// Spanish/latin accents first, then everything else
const aScore = (aAccent.includes('spanish') || aAccent.includes('latin')) ? 0 : 1;
const bScore = (bAccent.includes('spanish') || bAccent.includes('latin')) ? 0 : 1;
return aScore - bScore;
}
// English: american/british first
const aScore = (aAccent.includes('american') || aAccent.includes('british')) ? 0 : 1;
const bScore = (bAccent.includes('american') || bAccent.includes('british')) ? 0 : 1;
return aScore - bScore;
})
: [];
if (filtered.length > 0) {
return (
{filtered.map((v) => (
setSelectedVoice(v.voice_id)}
className={`w-full flex items-center gap-3 p-2.5 rounded-input border text-left transition-colors duration-200 ${
selectedVoice === v.voice_id
? 'border-brass bg-paper3'
: 'border-rule bg-paper hover:bg-paper3'
}`}
>
{v.name}
{v.labels?.accent || ''} {v.labels?.gender || ''} {v.category ? `· ${v.category}` : ''}
{v.preview_url && (
{ e.stopPropagation(); new Audio(v.preview_url).play(); }}
className="shrink-0 w-7 h-7 rounded-full bg-paper3 text-muted hover:text-brass flex items-center justify-center transition-colors"
title="Preview voice"
>
)}
{selectedVoice === v.voice_id && }
))}
);
}
// Fallback defaults by gender + language
const defaults = {
'en-female': [
{ id: '21m00Tcm4TlvDq8ikWAM', name: 'Rachel (calm)' },
{ id: 'EXAVITQu4vr4xnSDxMaL', name: 'Bella (soft)' },
],
'en-male': [
{ id: '29vD33N1CtxCmqQRPOHJ', name: 'Drew (confident)' },
{ id: 'TxGEqnHWrfWFTfGW9XjX', name: 'Josh (deep)' },
{ id: 'yoZ06aMxZJJ28mfd3POQ', name: 'Sam (raspy)' },
],
'es-female': [
{ id: 'EXAVITQu4vr4xnSDxMaL', name: 'Bella (suave)' },
{ id: '21m00Tcm4TlvDq8ikWAM', name: 'Rachel (calmada)' },
],
'es-male': [
{ id: 'ErXwobaYiN019PkySvjV', name: 'Antoni (cálido)' },
{ id: '29vD33N1CtxCmqQRPOHJ', name: 'Drew (confiado)' },
],
};
const key = `${language}-${actorGender}`;
const opts = defaults[key] || defaults['en-female'];
return (
setSelectedVoice(e.target.value)} className="input-field">
{opts.map((o) => {o.name} )}
);
})()}
{actorGender === 'female' ? 'female' : 'male'} voices · multilingual model speaks your selected language · click speaker to preview
{/* Actor Selection: Gallery + Generate New */}
AI Actor — Choose Your Actor
{/* Existing Gallery from S3 */}
{actorGallery.length > 0 && (
Previously generated actors (click to select)
{actorGallery.map((img, i) => (
setSelectedActor(img.url)}
className={`relative rounded-input overflow-hidden border-2 transition-colors duration-200 aspect-[3/4] ${
selectedActor === img.url ? 'border-brass' : 'border-rule hover:border-rule2'
}`}
>
{selectedActor === img.url && (
)}
))}
)}
{loadingGallery && (
Loading actor gallery...
)}
{/* Upload Custom Actor */}
Upload your own photo
{
const file = e.target.files?.[0];
if (!file) return;
// Show instant preview
const localPreview = URL.createObjectURL(file);
setUploadedActorPreview({ localPreview, serverUrl: null });
setSelectedActor(null);
const formData = new FormData();
formData.append('file', file);
try {
const res = await apiFetch('/api/saasshorts/actor-upload', {
method: 'POST',
body: formData,
});
if (res.ok) {
const data = await res.json();
if (data.url) {
setUploadedActorPreview({ localPreview, serverUrl: data.url });
setSelectedActor(data.url);
}
}
} catch (err) { console.error('Upload failed:', err); }
e.target.value = '';
}}
/>
{uploadedActorPreview && (
{
if (uploadedActorPreview.serverUrl) {
setSelectedActor(uploadedActorPreview.serverUrl);
}
}}
className={`relative w-16 h-20 rounded-input overflow-hidden border-2 transition-colors duration-200 flex-shrink-0 ${
selectedActor === uploadedActorPreview.serverUrl
? 'border-brass'
: 'border-rule hover:border-rule2'
}`}
>
{selectedActor === uploadedActorPreview.serverUrl && (
)}
{!uploadedActorPreview.serverUrl && (
)}
)}
{/* Generate New Actors */}
{actorGallery.length > 0 ? 'Or generate new actors' : 'Or describe your actor'}
{/* Narration Edit */}
{/* Cost Estimate */}
Estimated Cost
~${videoMode === 'lowcost' ? '0.65' : '2.50'}
{(videoMode === 'lowcost'
? [
['Flux image', '$0.05'],
['ElevenLabs voice', '$0.10'],
['Hailuo 2.3 img2video', '$0.19'],
['VEED Lipsync', '$0.20'],
['Flux b-roll', '$0.10'],
]
: [
['Flux image', '$0.05'],
['ElevenLabs voice', '$0.10'],
['Kling avatar', '$1.69'],
['Kling b-roll', '$0.70'],
]
).map(([item, cost]) => (
{item}
{cost}
))}
{/* Missing keys warning */}
{(!falKey || !elevenLabsKey) && (
{!falKey && 'fal.ai API key missing. '}{!elevenLabsKey && 'ElevenLabs API key missing. '}
Set them in Settings.
)}
setShareToGallery(e.target.checked)}
className="mt-0.5 accent-brass"
/>
Share this video in the public gallery
Your video, product name and script will be visible at openshorts.app/gallery
setStep(1)} className="btn-ghost px-4 py-2 text-sm">
Back
{generating ? (
<> Generating...>
) : !selectedActor ? (
<> Select an actor first>
) : (
<> Generate video (~${videoMode === 'lowcost' ? '0.65' : '2.00'})>
)}
)}
{/* ── Step 3: Generation Progress ──────────────────────── */}
{step === 3 && (
Video Generation
{genStatus.toUpperCase()}
{/* Progress steps */}
{[
'Generating actor image + voiceover',
'Creating talking head video (2-5 min)',
'Generating b-roll clips',
'Compositing final video',
].map((label, i) => {
const logStr = genLogs.join(' ').toLowerCase();
const stepDone =
i === 0 ? logStr.includes('[2/6]') || logStr.includes('[3/6]') :
i === 1 ? logStr.includes('[3/6]') && (logStr.includes('[4/6]') || logStr.includes('talking head ready')) :
i === 2 ? logStr.includes('[5/6]') || logStr.includes('[6/6]') :
genStatus === 'completed';
const stepActive =
i === 0 ? logStr.includes('[1/6]') && !stepDone :
i === 1 ? (logStr.includes('[3/6]') && !logStr.includes('[4/6]')) :
i === 2 ? (logStr.includes('[4/6]') && !logStr.includes('[5/6]') && !logStr.includes('[6/6]')) :
logStr.includes('[6/6]') && genStatus !== 'completed';
return (
{String(i + 1).padStart(2, '0')}
{stepDone ? (
) : stepActive ? (
) : (
)}
{label}
);
})}
{/* Logs Terminal */}
Generation Logs
setLogsExpanded(!logsExpanded)} className="text-muted hover:text-ink transition-colors">
{logsExpanded && (
{genLogs.map((log, i) => (
{log}
))}
{genStatus === 'processing' && (
_
)}
)}
{/* Retry button when failed */}
{genStatus === 'failed' && (
Generation failed. You can retry or go back to change settings.
{ setStep(2); setGenStatus('idle'); setGenerating(false); }}
className="btn-quiet px-4 py-2 text-sm"
>
Change voice/settings
Retry
)}
)}
{/* ── Step 4: Results ──────────────────────────────────── */}
{step === 4 && genResult && (
Your Short is Ready
{/* Video Player */}
{/* Details */}
{genResult.script?.title}
{genResult.duration?.toFixed(1)}s · 9:16 vertical
{/* Cost breakdown */}
{genResult.cost_estimate && (
Cost Breakdown
{Object.entries(genResult.cost_estimate).filter(([k]) => k !== 'total').map(([k, v]) => (
{k.replace(/_/g, ' ')}
${v}
))}
Total
${genResult.cost_estimate.total}
)}
{/* Caption */}
{genResult.script?.caption && (
Caption
handleCopy(genResult.script.caption, 'caption')}
className="text-xs lowercase text-muted hover:text-brass flex items-center gap-1 transition-colors"
>
{copied === 'caption' ? : }
{copied === 'caption' ? 'Copied' : 'Copy'}
{genResult.script.caption}
)}
{/* Hashtags */}
{genResult.script?.hashtags && (
Hashtags
handleCopy(genResult.script.hashtags.join(' '), 'hashtags')}
className="text-xs lowercase text-muted hover:text-brass flex items-center gap-1 transition-colors"
>
{copied === 'hashtags' ? : }
{copied === 'hashtags' ? 'Copied' : 'Copy'}
{genResult.script.hashtags.map((tag, i) => (
{tag}
))}
)}
{/* Actions */}
{/* Publish to Social Media */}
Publish to Social Media
{!uploadPostKey ? (
Set your Upload-Post API key in Settings to enable publishing.
) : (
<>
{/* Platform toggles */}
publishPlatforms[k])}
onChange={(arr) => setPublishPlatforms({
tiktok: arr.includes('tiktok'),
instagram: arr.includes('instagram'),
youtube: arr.includes('youtube'),
})}
/>
{/* Same notice as ResultCard: TikTok lands as a draft,
and finding nothing live reads as a failed post. */}
{publishPlatforms.tiktok && (
tiktok arrives as a draft and you'll get a
notification in the app — finishing it there lets you add trending sounds
and hashtags, which reaches more people than posting from an api.
)}
{/* Schedule toggle */}
setIsScheduling(e.target.checked)}
className="w-3.5 h-3.5 rounded accent-brass"
/>
Schedule
{isScheduling && (
setScheduleDate(e.target.value)}
className="input-field text-xs py-1 px-2 w-auto"
/>
)}
{/* Publish button */}
{
const selected = Object.keys(publishPlatforms).filter(k => publishPlatforms[k]);
if (selected.length === 0) { setPublishResult({ ok: false, msg: 'Select at least one platform' }); return; }
if (isScheduling && !scheduleDate) { setPublishResult({ ok: false, msg: 'Select a date' }); return; }
setPublishing(true);
setPublishResult(null);
try {
const payload = {
job_id: jobId,
api_key: uploadPostKey,
user_id: uploadUserId,
platforms: selected,
title: genResult.script?.title,
description: genResult.script?.caption || genResult.script?.full_narration,
};
if (isScheduling && scheduleDate) {
payload.scheduled_date = new Date(scheduleDate).toISOString();
payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
}
const res = await apiFetch('/api/saasshorts/post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
if (!res.ok) {
const err = await res.json().catch(() => ({ detail: 'Failed' }));
throw new Error(err.detail || 'Failed');
}
setPublishResult({ ok: true, msg: isScheduling ? 'Scheduled!' : 'Published!' });
} catch (e) {
setPublishResult({ ok: false, msg: e.message });
} finally {
setPublishing(false);
}
}}
disabled={publishing}
className="btn-primary w-full py-2 text-sm"
>
{publishing ? (
<> {isScheduling ? 'Scheduling...' : 'Publishing...'}>
) : (
<> {isScheduling ? 'Schedule post' : 'Publish now'}>
)}
{publishResult && (
{publishResult.msg}
)}
>
)}
)}
);
}