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 } from 'lucide-react';
import KeyInput from './components/KeyInput';
import MediaInput from './components/MediaInput';
import ResultCard from './components/ResultCard';
import ProcessingAnimation from './components/ProcessingAnimation';
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 && }
))}
)}
);
};
// 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 '';
});
const [uploadUserId, setUploadUserId] = useState(() => localStorage.getItem('uploadUserId') || '');
const [userProfiles, setUserProfiles] = useState([]); // List of {username, connected: []}
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
// 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);
};
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 (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');
setLogs(prev => [...prev, "Error: " + data.error]);
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) => {
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);
};
// --- 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'}`}
>
Dashboard
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 */}
{/* 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.
)}
{/* 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
)}
)}
);
}
export default App;