import React, { useState, useEffect } from 'react';
import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity, LayoutDashboard, Settings, PlusCircle, History, Menu, X, Terminal, Shield, LayoutGrid, Image, Globe, RotateCcw } from 'lucide-react';
import KeyInput from './components/KeyInput';
import MediaInput from './components/MediaInput';
import ResultCard from './components/ResultCard';
import ProcessingAnimation from './components/ProcessingAnimation';
// import Gallery from './components/Gallery';
import ThumbnailStudio from './components/ThumbnailStudio';
import SaaShortsTab from './components/SaaShortsTab';
import UGCGallery from './components/UGCGallery';
import { getApiUrl } from './config';
// Enhanced "Encryption" using XOR + Base64 with a Salt
// This is better than plain Base64 but still client-side.
const SECRET_KEY = import.meta.env.VITE_ENCRYPTION_KEY || "OpenShorts-Static-Salt-Change-Me";
const ENCRYPTION_PREFIX = "ENC:";
const encrypt = (text) => {
if (!text) return '';
try {
const xor = text.split('').map((c, i) =>
String.fromCharCode(c.charCodeAt(0) ^ SECRET_KEY.charCodeAt(i % SECRET_KEY.length))
).join('');
return ENCRYPTION_PREFIX + btoa(xor);
} catch (e) {
console.error("Encryption failed", e);
return text;
}
};
const decrypt = (text) => {
if (!text) return '';
if (text.startsWith(ENCRYPTION_PREFIX)) {
try {
const raw = text.slice(ENCRYPTION_PREFIX.length);
// Check if it's plain base64 or our custom XOR (simple try)
const xor = atob(raw);
const result = xor.split('').map((c, i) =>
String.fromCharCode(c.charCodeAt(0) ^ SECRET_KEY.charCodeAt(i % SECRET_KEY.length))
).join('');
return result;
} catch (e) {
// Fallback if decryption fails (might be old plain text)
return '';
}
}
// Backward compatibility: If no prefix, assume old plain text (or return empty if you want to force re-login)
// For migration: Return text as is, so it populates the field, and next save will encrypt it.
return text;
};
// Simple TikTok icon sine Lucide might not have it or it varies
const TikTokIcon = ({ size = 16, className = "" }) => (
);
const UserProfileSelector = ({ profiles, selectedUserId, onSelect }) => {
const [isOpen, setIsOpen] = useState(false);
if (!profiles || profiles.length === 0) return null;
const selectedProfile = profiles.find(p => p.username === selectedUserId) || profiles[0];
return (
setIsOpen(!isOpen)}
className="flex items-center justify-between bg-surface border border-white/10 rounded-lg px-3 py-2 text-sm text-zinc-300 hover:bg-white/5 transition-colors min-w-[180px]"
>
{selectedProfile?.username?.substring(0, 1).toUpperCase() || "U"}
{selectedProfile?.username || "Select User"}
{isOpen && (
{profiles.map((profile) => (
{
onSelect(profile.username);
setIsOpen(false);
}}
className="w-full flex items-center justify-between px-4 py-3 hover:bg-white/5 transition-colors text-left group border-b border-white/5 last:border-0"
>
{profile.username.substring(0, 2).toUpperCase()}
{profile.username}
{/* Status indicators */}
{selectedUserId === profile.username && }
))}
)}
);
};
const SESSION_KEY = 'openshorts_session';
const SESSION_MAX_AGE = 3600000; // 1 hour (matches server job retention)
// Mock polling function
const pollJob = async (jobId) => {
const res = await fetch(getApiUrl(`/api/status/${jobId}`));
if (!res.ok) throw new Error('Status check failed');
return res.json();
};
function App() {
const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || '');
// Social API State - Load encrypted or plain
const [uploadPostKey, setUploadPostKey] = useState(() => {
const stored = localStorage.getItem('uploadPostKey_v3');
if (stored) return decrypt(stored);
return '';
});
// ElevenLabs API State - Load encrypted
const [elevenLabsKey, setElevenLabsKey] = useState(() => {
const stored = localStorage.getItem('elevenLabsKey_v1');
if (stored) return decrypt(stored);
return '';
});
// fal.ai API State - Load encrypted
const [falKey, setFalKey] = useState(() => {
const stored = localStorage.getItem('falKey_v1');
if (stored) return decrypt(stored);
return '';
});
const [uploadUserId, setUploadUserId] = useState(() => localStorage.getItem('uploadUserId') || '');
const [userProfiles, setUserProfiles] = useState([]); // List of {username, connected: []}
const [showKeyModal, setShowKeyModal] = useState(false);
const [jobId, setJobId] = useState(null);
const [status, setStatus] = useState('idle'); // idle, processing, complete, error
const [results, setResults] = useState(null);
const [logs, setLogs] = useState([]);
const [logsVisible, setLogsVisible] = useState(true);
const [processingMedia, setProcessingMedia] = useState(null);
const [activeTab, setActiveTab] = useState('dashboard'); // dashboard, settings
const [sessionRecovered, setSessionRecovered] = useState(false);
// Sync state for original video playback
const [syncedTime, setSyncedTime] = useState(0);
const [isSyncedPlaying, setIsSyncedPlaying] = useState(false);
const [syncTrigger, setSyncTrigger] = useState(0);
const handleClipPlay = (startTime) => {
setSyncedTime(startTime);
setIsSyncedPlaying(true);
setSyncTrigger(prev => prev + 1);
};
const handleClipPause = () => {
setIsSyncedPlaying(false);
};
// Session Recovery: Restore on mount
useEffect(() => {
try {
const saved = localStorage.getItem(SESSION_KEY);
if (!saved) return;
const session = JSON.parse(saved);
if (Date.now() - session.timestamp > SESSION_MAX_AGE) {
localStorage.removeItem(SESSION_KEY);
return;
}
if (session.jobId && session.status && session.status !== 'idle') {
setJobId(session.jobId);
setResults(session.results || null);
if (session.processingMedia) setProcessingMedia(session.processingMedia);
if (session.activeTab) setActiveTab(session.activeTab);
// If was processing, resume polling; if complete/error, just show results
setStatus(session.status === 'processing' ? 'processing' : session.status);
setSessionRecovered(true);
setTimeout(() => setSessionRecovered(false), 5000);
}
} catch (e) {
localStorage.removeItem(SESSION_KEY);
}
}, []);
// Session Recovery: Save state changes
useEffect(() => {
if (status === 'idle') {
localStorage.removeItem(SESSION_KEY);
return;
}
try {
const sessionData = {
jobId,
status,
results,
processingMedia: processingMedia?.type === 'url' ? processingMedia : null,
activeTab,
timestamp: Date.now()
};
localStorage.setItem(SESSION_KEY, JSON.stringify(sessionData));
} catch (e) {
// localStorage full or serialization error - ignore
}
}, [jobId, status, results, activeTab]);
useEffect(() => {
// Encrypt Gemini Key too for consistency if desired, but user asked specifically about Social integration not saving well.
// For now keeping gemini plain for compatibility unless requested.
if (apiKey) localStorage.setItem('gemini_key', apiKey);
}, [apiKey]);
useEffect(() => {
if (uploadPostKey) {
localStorage.setItem('uploadPostKey_v3', encrypt(uploadPostKey));
}
if (uploadUserId) {
localStorage.setItem('uploadUserId', uploadUserId);
}
}, [uploadPostKey, uploadUserId]);
useEffect(() => {
if (elevenLabsKey) {
localStorage.setItem('elevenLabsKey_v1', encrypt(elevenLabsKey));
}
}, [elevenLabsKey]);
useEffect(() => {
if (falKey) {
localStorage.setItem('falKey_v1', encrypt(falKey));
}
}, [falKey]);
useEffect(() => {
if (uploadPostKey && userProfiles.length === 0) {
fetchUserProfiles();
}
}, [uploadPostKey]);
useEffect(() => {
let interval;
if ((status === 'processing' || status === 'completed') && jobId) {
interval = setInterval(async () => {
try {
const data = await pollJob(jobId);
console.log("Job status:", data);
// Update results if available (real-time)
if (data.result) {
setResults(data.result);
}
if (data.status === 'completed') {
setStatus('complete');
clearInterval(interval);
} else if (data.status === 'failed') {
setStatus('error');
const errorMsg = data.error || (data.logs && data.logs.length > 0 ? data.logs[data.logs.length - 1] : "Process failed");
setLogs(prev => [...prev, "Error: " + errorMsg]);
clearInterval(interval);
} else {
// Update logs if available
if (data.logs) setLogs(data.logs);
}
} catch (e) {
console.error("Polling error", e);
}
}, 2000);
}
return () => clearInterval(interval);
}, [status, jobId]);
const fetchUserProfiles = async () => {
if (!uploadPostKey) return;
try {
const res = await fetch(getApiUrl('/api/social/user'), {
headers: { 'X-Upload-Post-Key': uploadPostKey }
});
if (!res.ok) throw new Error("Failed to fetch");
const data = await res.json();
if (data.profiles && data.profiles.length > 0) {
setUserProfiles(data.profiles);
// Auto select first if none selected
if (!uploadUserId) {
setUploadUserId(data.profiles[0].username);
}
} else {
alert("No profiles found for this API Key.");
}
} catch (e) {
alert("Error fetching User Profiles. Please check key.");
console.error(e);
}
};
const handleProcess = async (data) => {
if (!apiKey) {
setShowKeyModal(true);
return;
}
setStatus('processing');
setLogs(["Starting process..."]);
setResults(null);
setProcessingMedia(data);
try {
let body;
const headers = { 'X-Gemini-Key': apiKey };
if (data.type === 'url') {
headers['Content-Type'] = 'application/json';
body = JSON.stringify({ url: data.payload });
} else {
const formData = new FormData();
formData.append('file', data.payload);
body = formData;
}
const res = await fetch(getApiUrl('/api/process'), {
method: 'POST',
headers: data.type === 'url' ? headers : { 'X-Gemini-Key': apiKey },
body
});
if (!res.ok) throw new Error(await res.text());
const resData = await res.json();
setJobId(resData.job_id);
} catch (e) {
setStatus('error');
setLogs(l => [...l, `Error starting job: ${e.message}`]);
}
};
const handleReset = () => {
setStatus('idle');
setJobId(null);
setResults(null);
setLogs([]);
setProcessingMedia(null);
localStorage.removeItem(SESSION_KEY);
};
// --- UI Components ---
const Sidebar = () => (
setActiveTab('dashboard')}
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'dashboard' ? 'bg-primary/10 text-primary' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
>
Clip Generator
setActiveTab('saasshorts')}
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'saasshorts' ? 'bg-violet-500/10 text-violet-400' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
>
AI Shorts
setActiveTab('ugc-gallery')}
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'ugc-gallery' ? 'bg-violet-500/10 text-violet-400' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
>
UGC Gallery
setActiveTab('thumbnails')}
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'thumbnails' ? 'bg-primary/10 text-primary' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
>
YouTube Studio
{/* setActiveTab('gallery')}
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'gallery' ? 'bg-primary/10 text-primary' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
>
Gallery
*/}
setActiveTab('settings')}
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'settings' ? 'bg-primary/10 text-primary' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
>
Settings
);
return (
{/* Background Gradients */}
{/* Top Header */}
{/* Session Recovery Banner */}
{sessionRecovered && (
Session recovered
Your previous work has been restored.
setSessionRecovered(false)} className="text-zinc-500 hover:text-white transition-colors">
)}
{/* Main Workspace */}
{/* View: Settings */}
{activeTab === 'settings' && (
Settings
Privacy: keys only live in your browser (sent to backend just to process)
Social Integration
Optional
Automatically publish your clips to TikTok, Instagram Reels, and YouTube Shorts via Upload-Post .
Includes a free tier (no credit card required).
If you prefer, you can skip this and manually download/upload your videos.
Video Translation
Optional
Translate your clips to different languages using ElevenLabs AI dubbing.
Automatically translates speech while preserving the original voice characteristics.
AI Shorts (UGC Videos)
New
Generate UGC-style videos with AI actors for any product or business using fal.ai .
Just describe your product or paste a URL. Requires fal.ai + ElevenLabs API keys.
)}
{/* View: SaaS Shorts */}
{activeTab === 'saasshorts' && (
)}
{/* View: UGC Gallery */}
{activeTab === 'ugc-gallery' && (
)}
{/* View: Thumbnails */}
{activeTab === 'thumbnails' && (
)}
{/* View: Gallery */}
{/* {activeTab === 'gallery' && (
)} */}
{/* View: Dashboard (Idle) */}
{activeTab === 'dashboard' && status === 'idle' && (
Create Viral Shorts
Drop your long-form video URL or file below to instantly generate viral clips with AI.
YouTube
Instagram
TikTok
)}
{/* View: Processing / Results (Split View) */}
{activeTab === 'dashboard' && (status === 'processing' || status === 'complete' || status === 'error') && (
{/* Left Panel: Preview & Status */}
Live Analysis
{status.toUpperCase()}
{/* Video Preview */}
{processingMedia && (
)}
{/* Logs Terminal */}
System Logs
setLogsVisible(!logsVisible)} className="text-zinc-500 hover:text-white transition-colors">
{logsVisible ? : }
{logsVisible && (
{logs.map((log, i) => (
{new Date().toLocaleTimeString()}
{log}
))}
{status === 'processing' && (
_
)}
)}
{/* Right Panel: Results Grid */}
Generated Shorts
{results?.clips?.length > 0 && (
{results.clips.length} Clips
)}
{results?.cost_analysis && (
${results.cost_analysis.total_cost.toFixed(5)}
)}
{results && results.clips && results.clips.length > 0 ? (
{results.clips.map((clip, i) => (
handleClipPlay(time)}
onPause={handleClipPause}
/>
))}
) : (
status === 'processing' ? (
) : status === 'error' ? (
) : null
)}
)}
{/* Missing API Key Modal */}
{showKeyModal && (
setShowKeyModal(false)}>
e.stopPropagation()}>
Gemini API Key Required
You need a Google Gemini API key to use the Clip Generator. It's free and takes 30 seconds to get.
How to get your free key:
Go to aistudio.google.com/app/apikey
Sign in with your Google account
Click "Create API Key"
Copy the key and paste it below
{
if (e.key === 'Enter' && e.target.value.trim()) {
setApiKey(e.target.value.trim());
setShowKeyModal(false);
}
}}
/>
{/* Upload-Post info */}
Optional: Auto-publish to social media
With an Upload-Post API key you can publish your clips directly to TikTok, Instagram Reels, and YouTube Shorts — or schedule them for later. Free tier available, no credit card needed.
Register at app.upload-post.com
Connect your TikTok, Instagram, or YouTube accounts
Go to API Keys and generate one
Paste it in Settings — done!
setShowKeyModal(false)}
className="flex-1 text-sm text-zinc-400 py-2 rounded-lg border border-white/10 hover:bg-white/5 transition-colors"
>
Cancel
{ setShowKeyModal(false); setActiveTab('settings'); }}
className="flex-1 text-sm text-white py-2 rounded-lg bg-blue-600 hover:bg-blue-500 transition-colors font-medium"
>
Go to Settings
)}
);
}
export default App;