clipwright/dashboard/src/App.jsx

1533 lines
70 KiB
JavaScript

import React, { useState, useEffect, useRef, useMemo } from 'react';
import { Youtube, Instagram, Share2, ChevronDown, Check, Activity, LayoutDashboard, Settings, Plus, X, Terminal, Shield, Image, RotateCcw, AlertTriangle, KeyRound, ExternalLink, Mail, Loader2, Download, Menu, Lock } from 'lucide-react';
import KeyInput from './components/KeyInput';
import MediaInput from './components/MediaInput';
import ResultCard from './components/ResultCard';
import ProcessingAnimation from './components/ProcessingAnimation';
import ThumbnailStudio from './components/ThumbnailStudio';
import ClipEditor from './components/ClipEditor';
import ReframeEditor from './components/ReframeEditor';
import StarBanner from './components/StarBanner';
import ClipTutorial from './components/ClipTutorial';
import Modal from './components/ui/Modal';
import { useAuth } from './contexts/AuthContext';
import { apiFetch } from './lib/api';
import { track } from './lib/analytics';
// 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 || "Clipwright-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 = "" }) => (
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" className={className}>
<path d="M19.589 6.686a4.793 4.793 0 0 1-3.77-4.245V2h-3.445v13.672a2.896 2.896 0 0 1-5.201 1.743l-.002-.001.002.001a2.895 2.895 0 0 1 3.183-4.51v-3.5a6.329 6.329 0 0 0-5.394 10.692 6.33 6.33 0 0 0 10.857-4.424V8.687a8.182 8.182 0 0 0 4.773 1.526V6.79a4.831 4.831 0 0 1-1.003-.104z" />
</svg>
);
// Postiz integration identifiers -> platform icon. Anything else falls back to
// a generic share glyph so a connected channel we do not special-case still
// shows up.
const ChannelIcon = ({ identifier, size = 14 }) => {
const id = String(identifier || '').toLowerCase();
if (id.includes('tiktok')) return <TikTokIcon size={size} />;
if (id.includes('instagram')) return <Instagram size={size} />;
if (id.includes('youtube')) return <Youtube size={size} />;
return <Share2 size={size} />;
};
// Connected Postiz channels, sourced from GET /api/postiz/integrations. The
// dropdown replaced the old per-profile social picker: Postiz owns the
// channel connections, so this is read-only and points back at the Postiz UI.
const UserProfileSelector = ({ channels, postizUrl }) => {
const [isOpen, setIsOpen] = useState(false);
if (!channels || channels.length === 0) return null;
return (
<div className="relative z-50">
<button
onClick={() => setIsOpen(!isOpen)}
aria-label="connected channels"
className="flex items-center justify-between gap-1 bg-paper2 border border-rule2 rounded-input px-2 sm:px-3 py-2 text-sm text-ink2 hover:bg-paper3 transition-colors sm:min-w-[180px]"
>
<span className="flex items-center gap-1.5">
<div className="w-5 h-5 rounded-full bg-paper3 border border-rule flex items-center justify-center font-mono text-micro text-brass shrink-0">
{channels.length}
</div>
<span className="hidden sm:flex items-center gap-1.5 text-ink">
{channels.slice(0, 3).map((ch) => (
<ChannelIcon key={ch.id} identifier={ch.identifier} size={13} />
))}
</span>
</span>
<ChevronDown size={14} className={`text-muted transition-transform ${isOpen ? 'rotate-180' : ''}`} />
</button>
{isOpen && (
<div className="absolute top-full mt-2 right-0 w-64 card overflow-hidden">
<div className="max-h-60 overflow-y-auto custom-scrollbar">
{channels.map((ch) => (
<div
key={ch.id}
className="w-full flex items-center justify-between px-4 py-3 text-left border-b border-rule last:border-0"
>
<div className="flex items-center gap-3 min-w-0">
<div className="w-8 h-8 rounded-full bg-paper3 flex items-center justify-center text-ink border border-rule shrink-0">
<ChannelIcon identifier={ch.identifier} size={15} />
</div>
<div className="min-w-0">
<div className="text-sm font-medium text-ink2 truncate">
{ch.name || ch.identifier}
</div>
<div className="readout mt-0.5">{ch.identifier}</div>
</div>
</div>
{ch.disabled
? <span className="badge-warn shrink-0">off</span>
: <Check size={14} className="text-brass shrink-0" />}
</div>
))}
</div>
{postizUrl && (
<a
href={postizUrl}
target="_blank"
rel="noopener noreferrer"
className="w-full flex items-center gap-2 px-4 py-3 text-sm text-brass hover:bg-paper3 transition-colors text-left border-t border-rule"
>
<ExternalLink size={14} /> manage channels in Postiz
</a>
)}
</div>
)}
</div>
);
};
const formatRetention = (seconds) => {
if (seconds >= 86400) return `${Math.round(seconds / 86400)} day${seconds >= 172800 ? 's' : ''}`;
if (seconds >= 3600) return `${Math.round(seconds / 3600)} hour${seconds >= 7200 ? 's' : ''}`;
return `${Math.max(1, Math.round(seconds / 60))} min`;
};
// Headers the backend uses to resolve the self-host Postiz instance. A request
// without an explicit base URL must not fall back to any built-in host: return
// no headers so publish/test paths are inert until the user supplies their own.
const postizHeaders = (key, url) => {
const headers = {};
const base = String(url || '').trim();
if (!base) return headers;
headers['X-Postiz-Url'] = base.replace(/\/$/, '');
if (key) headers['X-Postiz-Key'] = key;
return headers;
};
// Older builds defaulted to a maintainer-hosted Postiz instance and persisted
// it to localStorage on mount, so an upgrade could silently keep sending a
// user's API key to someone else's server. Recognize that retired default and
// treat it as unset. The host is assembled from parts so no live reference to
// it remains in the source.
const RETIRED_POSTIZ_HOST = ['postiz', 'pbento', 'pt'].join('.');
const normalizeStoredPostizUrl = (url) => {
const base = String(url || '').trim().replace(/\/$/, '');
if (!base) return '';
return base === `https://${RETIRED_POSTIZ_HOST}` ? '' : base;
};
const SESSION_KEY = 'clipwright_session';
// The server's own explanation for a rejected/failed job, readable: FastAPI
// answers {"detail": "..."} or {"detail": {"message": ...}}. Showing the raw
// JSON (or a generic "failed") hid actionable reasons such as "this video is
// only 30s long", and new users in the tutorial saw only "That run failed".
const readableError = (raw) => {
const text = String(raw || '').trim();
try {
const body = JSON.parse(text);
const d = body?.detail ?? body;
if (typeof d === 'string' && d) return d.slice(0, 300);
if (d && typeof d.message === 'string') return d.message.slice(0, 300);
} catch (_) { /* not JSON */ }
return text.replace(/^Error:\s*/, '').slice(0, 300) || 'Something went wrong.';
};
// Matches the self-host JOB_RETENTION_SECONDS default. A restore whose job was
// already purged server-side fails gracefully and clears the saved session.
const SESSION_MAX_AGE = 86400000; // 24 hours
// Mock polling function
const pollJob = async (jobId) => {
const res = await apiFetch(`/api/status/${jobId}`);
if (!res.ok) throw new Error('Status check failed');
return res.json();
};
function App() {
// Self-host config: job retention (retention notice) and whether a local LLM
// backend removes the Gemini-key requirement. Auth/billing is gone.
const { jobRetentionSeconds, localLlm } = useAuth();
const [tutorialPhase, setTutorialPhase] = useState(null); // null | intro | coach | celebrate
// Why the last job could not start or failed, in plain words (or '').
const [jobError, setJobError] = useState('');
const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || '');
// Postiz (self-hosted social publishing) config. The API key is encrypted at
// rest like the other BYOK keys; the base URL is not a secret. There is no
// built-in default: the user must enter the URL of their own instance.
const [postizUrl, setPostizUrl] = useState(() => normalizeStoredPostizUrl(localStorage.getItem('postiz_url')));
const [postizKey, setPostizKey] = useState(() => {
const stored = localStorage.getItem('postiz_key_v1');
if (stored) return decrypt(stored);
return '';
});
// Connected channels from GET /api/postiz/integrations.
const [postizChannels, setPostizChannels] = useState([]);
// Post-generation social nudge: shown at the results peak until the user
// either connects a network or dismisses it. Only 2.7% of cloud users who
// reach the social flow ever connect an account — this is the moment (clips
// just appeared) with the best odds of moving that number.
const [socialNudgeDismissed, setSocialNudgeDismissed] = useState(() => {
try { return localStorage.getItem('cw_social_nudge_dismissed') === '1'; } catch (_) { return false; }
});
const [showKeyModal, setShowKeyModal] = useState(false);
const [jobId, setJobId] = useState(null);
const [status, setStatus] = useState('idle'); // idle, processing, complete, error
const [results, setResults] = useState(null);
// Best clips first. The backend hands them back in transcript order, which
// buries the strongest one wherever it happens to fall in the video — and
// the first card is the one people actually watch and publish.
//
// The ORIGINAL array position travels with each clip and is what gets passed
// down as `index`: it is the clip's identity everywhere else (clip_index on
// /api/subtitle, /api/edit and publishing, the clip-N.mp4 download name, the
// saved per-clip project state). Sorting the array itself would silently
// repoint all of that at the wrong clip.
const rankedClips = useMemo(() => {
const clips = results?.clips;
if (!Array.isArray(clips)) return [];
return clips
.map((clip, index) => ({ clip, index }))
.sort((a, b) => {
const sa = Number.isFinite(a.clip?.predicted_score) ? a.clip.predicted_score : -1;
const sb = Number.isFinite(b.clip?.predicted_score) ? b.clip.predicted_score : -1;
// Ties (and clips with no score at all) keep transcript order.
return sb - sa || a.index - b.index;
});
}, [results]);
// Bulk subtitles: apply one style to every clip of the job (triggered from
// within a clip's subtitle modal via "apply to all").
const [bulkSub, setBulkSub] = useState({ running: false, current: 0, total: 0, errors: 0 });
const [downloadingAll, setDownloadingAll] = useState(false);
// Pre-flight quality gate: { info: {max_height, min_height, cookies_invalid}, data }
const [qualityGate, setQualityGate] = useState(null);
const [logs, setLogs] = useState([]);
// When each server log line arrived (epoch s, parallel to logs), from /api/status.
const [logTimes, setLogTimes] = useState([]);
// Collapsed on phones: the log tail is the least useful thing on a 360px
// screen and it was pushing the actual clips a full scroll down.
const [logsVisible, setLogsVisible] = useState(() => {
try { return window.innerWidth >= 768; } catch { return true; }
});
const [processingMedia, setProcessingMedia] = useState(null);
const [activeTab, setActiveTab] = useState('dashboard'); // dashboard, settings
// Mobile only: the full nav lives in a drawer behind the header's menu button.
const [navOpen, setNavOpen] = useState(false);
const [sessionRecovered, setSessionRecovered] = useState(false);
// Clip editor overlay: index of the clip being edited, or null.
const [editingClip, setEditingClip] = useState(null);
const [reframingClip, setReframingClip] = useState(null);
// 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);
};
// A recut replaced the clip's server file with a fresh render (burned layers
// reset), so update the results and let the ResultCard remount from the new file.
const handleClipRerendered = (index, data) => {
setResults((prev) => {
if (!prev?.clips?.[index]) return prev;
const clips = prev.clips.slice();
clips[index] = {
...clips[index],
video_url: data.new_video_url,
start: data.start,
end: data.end,
recipe: data.recipe,
};
return { ...prev, clips };
});
};
// Apply one subtitle style to every clip of the job, sequentially.
const handleBulkSubtitles = async (options) => {
const clips = results?.clips || [];
const total = clips.length;
if (!total) return;
setBulkSub({ running: true, current: 0, total, errors: 0 });
let errors = 0;
for (let i = 0; i < total; i++) {
setBulkSub({ running: true, current: i + 1, total, errors });
try {
const res = await apiFetch('/api/subtitle', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
job_id: jobId,
clip_index: i,
position: options.position,
font_size: options.fontSize,
font_name: options.fontName,
font_color: options.fontColor,
border_color: options.borderColor,
border_width: options.borderWidth,
bg_color: options.bgColor,
bg_opacity: options.bgOpacity,
style: options.style || 'pill',
highlight_color: options.highlightColor || '#FFD700',
effect: options.effect || 'none',
base_opacity: options.baseOpacity ?? 1.0,
uppercase: options.uppercase || false,
reveal: options.reveal || false,
shadow: options.shadow || 0,
max_chars: options.maxChars ?? null,
max_duration: options.maxDuration ?? null,
// Chain from the clip's current server file (its video_url basename).
input_filename: (clips[i].video_url || '').split('/').pop(),
}),
});
if (!res.ok) errors++;
} catch {
errors++;
}
}
setBulkSub({ running: false, current: total, total, errors });
// Refresh results so each ResultCard picks up its new subtitled video_url.
try {
const data = await pollJob(jobId);
if (data.result) setResults(data.result);
} catch { /* keep current results */ }
};
const handleDownloadAll = async () => {
if (!jobId) return;
setDownloadingAll(true);
try {
const res = await apiFetch(`/api/jobs/${jobId}/download-all`);
if (!res.ok) throw new Error(await res.text());
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `clipwright_clips_${(jobId || '').slice(0, 8)}.zip`;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
} catch (e) {
alert(`Download failed: ${e.message}`);
} finally {
setDownloadingAll(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);
// Restore the source preview. Older sessions (or uploads) saved no
// media, so fall back to the backend-served source for this job.
if (session.processingMedia) setProcessingMedia(session.processingMedia);
else setProcessingMedia({ type: 'server', payload: `/api/source/${session.jobId}` });
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 {
// URL (YouTube) media serializes as-is. Uploaded 'file' media is a blob
// that can't be persisted, so point the recovered preview at the source
// served by the backend instead of dropping it.
let persistMedia = null;
if (processingMedia?.type === 'url') persistMedia = processingMedia;
else if (processingMedia && jobId) persistMedia = { type: 'server', payload: `/api/source/${jobId}` };
const sessionData = {
jobId,
status,
results,
processingMedia: persistMedia,
activeTab,
timestamp: Date.now()
};
localStorage.setItem(SESSION_KEY, JSON.stringify(sessionData));
} catch (e) {
// localStorage full or serialization error - ignore
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [jobId, status, results, activeTab]);
useEffect(() => {
// Gemini key stays plain for backward compatibility with older sessions.
if (apiKey) localStorage.setItem('gemini_key', apiKey);
}, [apiKey]);
useEffect(() => {
if (postizKey) {
localStorage.setItem('postiz_key_v1', encrypt(postizKey));
}
}, [postizKey]);
useEffect(() => {
try {
if (postizUrl) localStorage.setItem('postiz_url', postizUrl);
else localStorage.removeItem('postiz_url');
} catch (_) { /* ignore */ }
}, [postizUrl]);
useEffect(() => {
if (postizKey && postizUrl && postizChannels.length === 0) {
fetchPostizChannels({ silent: true });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [postizKey, postizUrl]);
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");
setJobError(readableError(errorMsg));
setLogs(prev => [...prev, "Error: " + errorMsg]);
clearInterval(interval);
} else {
// Update logs if available
if (data.logs) {
setLogs(data.logs);
setLogTimes(data.log_times || []);
}
}
} catch (e) {
console.error("Polling error", e);
}
}, 2000);
}
return () => clearInterval(interval);
}, [status, jobId]);
// silent: background auto-fetch — never alert(), just log.
const fetchPostizChannels = async ({ silent = false } = {}) => {
if (!postizUrl || !postizKey) {
if (!silent) alert('Enter your Postiz base URL and API key first.');
return;
}
try {
const res = await apiFetch('/api/postiz/integrations', {
headers: postizHeaders(postizKey, postizUrl),
});
if (!res.ok) throw new Error('Failed to fetch');
const data = await res.json();
const channels = Array.isArray(data) ? data : (data.integrations || []);
setPostizChannels(channels);
if (channels.length === 0 && !silent) {
alert('No channels are connected in Postiz yet.');
}
} catch (e) {
if (!silent) alert('Could not reach Postiz. Check the base URL and API key.');
console.error(e);
}
};
// `keysMissing` only covers what clipping itself needs — the Gemini key.
// Publishing is a separate, optional Postiz concern (gated in the publish
// flows instead), so a missing Postiz key never blocks the clip generator.
// A server running the moment picker on a local LLM (LLM_BASE_URL) does not
// need a Gemini key for the core pipeline.
const geminiOk = !!apiKey || !!localLlm;
const keysMissing = !geminiOk;
// Fresh sign-up: Clip Generator tutorial (AuthContext set cw_show_clip_tutorial
// after the auth redirect). QA: #app?tutorial=1. Resume coach if they refreshed
// mid-job. Runs once on mount.
useEffect(() => {
let showTutorial = false;
let resumeCoach = false;
try {
const q = new URLSearchParams((window.location.hash.split('?')[1] || ''));
const qa = q.get('tutorial');
if (qa === '1') showTutorial = true;
if (qa === 'coach') resumeCoach = true;
if (qa === 'celebrate') { setTutorialPhase('celebrate'); return; }
if (localStorage.getItem('cw_show_clip_tutorial') === '1') showTutorial = true;
if (localStorage.getItem('cw_clip_tutorial') === 'coach') resumeCoach = true;
} catch (_) { /* ignore */ }
if (showTutorial) {
setTutorialPhase('intro');
setActiveTab('dashboard');
} else if (resumeCoach) {
setTutorialPhase('coach');
setActiveTab('dashboard');
}
}, []);
const tutorialLock = tutorialPhase === 'intro' || tutorialPhase === 'coach' || tutorialPhase === 'celebrate';
useEffect(() => {
if (tutorialLock && activeTab !== 'dashboard') setActiveTab('dashboard');
}, [tutorialLock, activeTab]);
// Deep links into a tab (#app?tab=settings|thumbnails|dashboard).
// Read once per hash change, then the query is dropped so a reload does not
// keep forcing the tab.
useEffect(() => {
const DEEP_LINK_TABS = ['settings', 'thumbnails', 'dashboard'];
const apply = () => {
const hash = window.location.hash || '';
if (!hash.startsWith('#app?')) return;
const params = new URLSearchParams(hash.slice(5));
const tab = params.get('tab');
if (!tab || !DEEP_LINK_TABS.includes(tab)) return; // e.g. #app?tutorial=1
setActiveTab(tab);
try { window.history.replaceState(null, '', '#app'); } catch (_) { /* ignore */ }
};
apply();
window.addEventListener('hashchange', apply);
return () => window.removeEventListener('hashchange', apply);
}, []);
useEffect(() => {
if (tutorialPhase === 'coach' && status === 'complete' && (results?.clips?.length > 0)) {
setTutorialPhase('celebrate');
track('ClipTutorialCompleted', { props: { clips: results.clips.length } });
}
}, [tutorialPhase, status, results]);
const finishTutorial = () => {
try { localStorage.setItem('cw_clip_tutorial', 'done'); } catch (_) { /* ignore */ }
try { localStorage.removeItem('cw_show_clip_tutorial'); } catch (_) { /* ignore */ }
setTutorialPhase(null);
};
const startTutorial = () => {
try { localStorage.setItem('cw_clip_tutorial', 'coach'); } catch (_) { /* ignore */ }
try { localStorage.removeItem('cw_show_clip_tutorial'); } catch (_) { /* ignore */ }
track('ClipTutorialStarted');
setTutorialPhase('coach');
setActiveTab('dashboard');
};
const skipTutorial = () => {
track('ClipTutorialSkipped', { props: { phase: tutorialPhase } });
finishTutorial();
};
// Distinct platform identifiers (tiktok/instagram/youtube/…) among the
// connected Postiz channels. Identifiers are lowercased to match the backend
// and ChannelIcon, and disabled channels are excluded so an integration that
// is turned off cannot enable a platform option. Empty means "nothing
// connected yet". The header selector still lists disabled channels with an
// "off" badge, but they do not count as connected.
const connectedSocials = useMemo(
() => [...new Set(
postizChannels
.filter((c) => !c.disabled)
.map((c) => String(c.identifier || '').toLowerCase())
.filter(Boolean),
)],
[postizChannels],
);
// Prompt to set up publishing once clips land, unless Postiz is already
// configured or the user dismissed the nudge.
const showSocialNudge = (!postizKey || !postizUrl) && !socialNudgeDismissed && connectedSocials.length === 0 && !tutorialLock;
// Both fields are required before Postiz can be tested or published to. The
// URL has no default, so an empty value must never count as configured.
const postizConfigured = !!postizUrl.trim() && !!postizKey;
// One Seen event per job, only when the banner actually rendered.
const socialNudgeSeenRef = useRef(null);
useEffect(() => {
if (status === 'complete' && (results?.clips?.length > 0) && showSocialNudge && socialNudgeSeenRef.current !== jobId) {
socialNudgeSeenRef.current = jobId;
track('SocialNudgeSeen', { props: { clips: results.clips.length } });
}
}, [status, results, showSocialNudge, jobId]);
// Channels are connected inside the user's own Postiz instance, so "connect"
// opens it. Until a base URL is set there is nothing to open, so send the
// user to Settings to enter theirs.
const handleConnectSocials = () => {
if (postizUrl) window.open(postizUrl, '_blank', 'noopener');
else setActiveTab('settings');
};
const handleProcess = async (data, forceLowQuality = false) => {
// The only gate is the BYOK Gemini key (unless a local LLM handles it).
if (keysMissing) {
setShowKeyModal(true);
return;
}
setStatus('processing');
setJobError('');
setLogs(["Starting process..."]);
setLogTimes([Date.now() / 1000]);
setResults(null);
// Studio handovers have no local media object; the preview switches to the
// backend-served source once the job id is known.
setProcessingMedia(data.type === 'thumbnail_session' ? null : data);
setQualityGate(null);
try {
let body;
// BYOK: send the Gemini header.
const headers = apiKey ? { 'X-Gemini-Key': apiKey } : {};
// Advanced generation controls: only sent when the user set them, so the
// default request stays byte-identical to the pre-feature one.
const advanced = {
target_clips: data.targetClips || null,
clip_min_seconds: data.clipMinSeconds || null,
clip_max_seconds: data.clipMaxSeconds || null,
// Sent explicitly both ways: absent means off for raw API callers,
// but the dashboard always states the user's choice.
auto_hook: data.autoHook ? '1' : '0',
auto_hook_style: data.autoHook ? (data.autoHookStyle || 'pill') : null,
// 'auto' is the server default, so only a deliberate choice travels.
layouts: data.layout && data.layout !== 'auto' ? data.layout : null,
// Channel profile slug (channels/<slug>.json). Absent = no profile, so
// the default request stays byte-identical to the pre-feature one.
channel: data.channel || null,
};
if (data.type === 'url') {
headers['Content-Type'] = 'application/json';
body = JSON.stringify({
url: data.payload,
acknowledged: !!data.acknowledged,
output_format: data.outputFormat || 'auto',
force_low_quality: forceLowQuality,
...Object.fromEntries(Object.entries(advanced).filter(([, v]) => v != null)),
});
} else if (data.type === 'thumbnail_session') {
// Handover from Thumbnail Studio (issue #68): the video and transcript
// already live server-side, keyed by the Studio session.
headers['Content-Type'] = 'application/json';
body = JSON.stringify({
thumbnail_session_id: data.payload,
acknowledged: !!data.acknowledged,
output_format: data.outputFormat || 'auto',
...Object.fromEntries(Object.entries(advanced).filter(([, v]) => v != null)),
});
} else {
const formData = new FormData();
formData.append('file', data.payload);
formData.append('acknowledged', data.acknowledged ? 'true' : 'false');
formData.append('output_format', data.outputFormat || 'auto');
for (const [k, v] of Object.entries(advanced)) {
if (v != null) formData.append(k, v);
}
body = formData;
}
const res = await apiFetch('/api/process', { method: 'POST', headers, body });
if (!res.ok) throw new Error(await res.text());
const resData = await res.json();
// Quality gate: the source is below the min resolution — ask before burning
// 20 min on it. On confirm we resend with force_low_quality.
if (resData.needs_confirmation) {
setStatus('idle');
setQualityGate({ info: resData.quality_check, data });
return;
}
setJobId(resData.job_id);
if (data.type === 'thumbnail_session') {
setProcessingMedia({ type: 'server', payload: `/api/source/${resData.job_id}` });
}
} catch (e) {
const reason = readableError(e.message);
setJobError(reason);
setStatus('error');
setLogs(l => [...l, `Error starting job: ${reason}`]);
}
};
const handleReset = () => {
setStatus('idle');
setJobId(null);
setResults(null);
setLogs([]);
setLogTimes([]);
setProcessingMedia(null);
setJobError('');
localStorage.removeItem(SESSION_KEY);
};
// --- UI Components ---
// One nav definition drives all three surfaces: the desktop rail, the mobile
// drawer, and the bottom tab bar. `short` is the tab-bar label — the full one
// wraps to two lines in a narrow tab bar on a 360px phone.
const navItems = [
{ id: 'dashboard', ord: '01', icon: LayoutDashboard, label: 'Clip Generator', short: 'clips', primary: true },
{ id: 'thumbnails', ord: '02', icon: Image, label: 'YouTube Studio', short: 'studio', primary: true },
{ id: 'settings', ord: '03', icon: Settings, label: 'Settings', short: 'settings' },
];
const activeNav = navItems.find((n) => n.id === activeTab);
// Escape closes the mobile drawer. The shell itself is overflow-hidden, so
// there is no body scroll to lock behind it.
useEffect(() => {
if (!navOpen) return;
const onKey = (e) => { if (e.key === 'Escape') setNavOpen(false); };
document.addEventListener('keydown', onKey);
return () => document.removeEventListener('keydown', onKey);
}, [navOpen]);
const goToTab = (id) => {
if (tutorialLock && id !== 'dashboard') return;
setActiveTab(id);
setNavOpen(false);
};
const tabLocked = (id) => tutorialLock && id !== 'dashboard';
// Shared footer links (repo, contact) — same list in the desktop rail and the
// mobile drawer, so they can never drift apart.
const NavFooterLinks = ({ collapsed = false }) => (
<>
<a
href="https://git.pbento.pt/pedro-bento/clipwright"
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-2 px-3 py-2 text-xs lowercase text-muted hover:text-ink2 transition-colors"
>
<svg height="14" viewBox="0 0 16 16" version="1.1" width="14" aria-hidden="true" fill="currentColor" className="shrink-0"><path fillRule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg>
<span className={collapsed ? 'hidden lg:block truncate' : 'truncate'}>open source</span>
</a>
<a
href="https://git.pbento.pt/pedro-bento/clipwright"
className="flex items-center gap-2 px-3 py-2 text-xs lowercase text-muted hover:text-ink2 transition-colors"
>
<Mail size={14} className="shrink-0" />
<span className={collapsed ? 'hidden lg:block truncate' : 'truncate'}>https://git.pbento.pt/pedro-bento/clipwright</span>
</a>
</>
);
// Desktop rail: icon-only from md, labelled from lg. Below md it is gone
// entirely — an unlabelled 80px rail ate a fifth of a phone screen.
const Sidebar = () => (
<div className="hidden md:flex w-20 lg:w-64 bg-paper2 border-r border-rule flex-col h-full shrink-0 transition-all duration-300">
<div className="p-6 flex items-center gap-3">
<div className="w-8 h-8 bg-paper3 rounded-input flex items-center justify-center shrink-0 overflow-hidden border border-rule">
<img src="/logo-clipwright.png" alt="Logo" className="w-full h-full object-cover" />
</div>
<span className="font-display lowercase text-lg text-ink hidden lg:block">clipwright</span>
</div>
<nav className="flex-1 px-4 py-4 space-y-1">
{navItems.map((item) => {
const NavIcon = item.icon;
const isActive = activeTab === item.id;
return (
<button
key={item.id}
data-tutorial={item.id === 'dashboard' ? 'nav-clips' : undefined}
onClick={() => goToTab(item.id)}
title={tabLocked(item.id) ? 'Finish your first clips to unlock' : item.label}
disabled={tabLocked(item.id)}
className={`relative w-full flex items-center gap-3 px-3 py-2.5 rounded-input transition-colors ${isActive ? 'bg-paper3 text-ink' : 'text-muted hover:text-ink2 hover:bg-paper3/50'} ${tabLocked(item.id) ? 'opacity-40 cursor-not-allowed hover:bg-transparent hover:text-muted' : ''}`}
>
{isActive && (
<span className="absolute left-0 top-1.5 bottom-1.5 w-0.5 bg-brass rounded-full" aria-hidden="true" />
)}
<NavIcon size={18} className={`shrink-0 ${isActive ? 'text-brass' : ''}`} />
<span className="text-sm lowercase hidden lg:block flex-1 text-left truncate">{item.label}</span>
{tabLocked(item.id)
? <Lock size={12} className="shrink-0 hidden lg:block" />
: item.byok ? <span className="readout hidden lg:block">BYOK</span>
: item.isNew ? <span className="badge-brass hidden lg:block">new</span> : null}
<span className="readout hidden lg:block">{item.ord}</span>
</button>
);
})}
</nav>
<div className="p-4 border-t border-rule space-y-1">
<NavFooterLinks collapsed />
</div>
</div>
);
// Mobile drawer: the complete nav, reachable from the header's menu button.
const MobileNavDrawer = () => (
<div
className="md:hidden fixed inset-0 z-[90] flex"
role="dialog"
aria-modal="true"
aria-label="Navigation"
>
<div
className="absolute inset-0 bg-black/60 animate-fade"
onClick={() => setNavOpen(false)}
aria-hidden="true"
/>
<div className="relative w-[17rem] max-w-[82vw] h-full bg-paper2 border-r border-rule flex flex-col animate-slide-in-left">
<div className="flex items-center justify-between px-5 h-14 border-b border-rule shrink-0">
<div className="flex items-center gap-2.5">
<div className="w-7 h-7 bg-paper3 rounded-input overflow-hidden border border-rule shrink-0">
<img src="/logo-clipwright.png" alt="" className="w-full h-full object-cover" />
</div>
<span className="font-display lowercase text-lg text-ink">clipwright</span>
</div>
<button
onClick={() => setNavOpen(false)}
aria-label="close navigation"
className="p-2 -mr-2 text-muted hover:text-ink transition-colors"
>
<X size={18} />
</button>
</div>
<nav className="flex-1 overflow-y-auto custom-scrollbar px-3 py-3 space-y-1">
{navItems.map((item) => {
const NavIcon = item.icon;
const isActive = activeTab === item.id;
return (
<button
key={item.id}
onClick={() => goToTab(item.id)}
disabled={tabLocked(item.id)}
aria-current={isActive ? 'page' : undefined}
title={tabLocked(item.id) ? 'Finish your first clips to unlock' : undefined}
className={`relative w-full flex items-center gap-3 px-3 py-3 rounded-input transition-colors ${isActive ? 'bg-paper3 text-ink' : 'text-muted active:bg-paper3/60'} ${tabLocked(item.id) ? 'opacity-40 cursor-not-allowed' : ''}`}
>
{isActive && (
<span className="absolute left-0 top-2 bottom-2 w-0.5 bg-brass rounded-full" aria-hidden="true" />
)}
<NavIcon size={18} className={`shrink-0 ${isActive ? 'text-brass' : ''}`} />
<span className="text-[0.95rem] lowercase flex-1 text-left truncate">{item.label}</span>
{tabLocked(item.id)
? <Lock size={12} className="shrink-0" />
: item.byok ? <span className="readout shrink-0">BYOK</span>
: item.isNew ? <span className="badge-brass shrink-0">new</span> : null}
</button>
);
})}
</nav>
<div className="px-3 py-3 border-t border-rule space-y-0.5 safe-bottom shrink-0">
<NavFooterLinks />
</div>
</div>
</div>
);
// Bottom tab bar: the four everyday destinations plus "more" for the rest.
// It is a flex sibling of the scrolling pane rather than `fixed`, so nothing
// ever hides behind it and no pane needs compensating padding.
const MobileTabBar = () => {
const tabs = navItems.filter((n) => n.primary);
const moreActive = !tabs.some((t) => t.id === activeTab);
return (
<nav className="md:hidden shrink-0 border-t border-rule bg-paper2/95 backdrop-blur-sm safe-bottom">
<div className="flex items-stretch">
{tabs.map((item) => {
const NavIcon = item.icon;
const isActive = activeTab === item.id;
return (
<button
key={item.id}
data-tutorial={item.id === 'dashboard' ? 'nav-clips' : undefined}
onClick={() => goToTab(item.id)}
disabled={tabLocked(item.id)}
aria-current={isActive ? 'page' : undefined}
title={tabLocked(item.id) ? 'Finish your first clips to unlock' : undefined}
className={`flex-1 min-w-0 flex flex-col items-center justify-center gap-1 py-2 min-h-[56px] transition-colors ${isActive ? 'text-ink' : 'text-muted active:text-ink2'} ${tabLocked(item.id) ? 'opacity-40 cursor-not-allowed' : ''}`}
>
<NavIcon size={19} className={isActive ? 'text-brass' : ''} />
<span className="text-[10.5px] lowercase leading-none truncate max-w-full px-0.5">{item.short}</span>
</button>
);
})}
<button
onClick={() => setNavOpen(true)}
aria-label="more sections"
aria-expanded={navOpen}
className={`flex-1 min-w-0 flex flex-col items-center justify-center gap-1 py-2 min-h-[56px] transition-colors ${moreActive ? 'text-ink' : 'text-muted active:text-ink2'}`}
>
<Menu size={19} className={moreActive ? 'text-brass' : ''} />
<span className="text-[10.5px] lowercase leading-none">more</span>
</button>
</div>
</nav>
);
};
return (
/* h-dvh where supported: on mobile Safari/Chrome `100vh` is the tallest the
viewport ever gets, so a h-screen shell hides its own bottom bar behind
the browser chrome until the user scrolls. */
<div className="flex h-screen supports-[height:100dvh]:h-[100dvh] bg-paper overflow-hidden">
<Sidebar />
{navOpen && <MobileNavDrawer />}
<main className="flex-1 min-w-0 flex flex-col h-full overflow-hidden relative">
{/* Top Header */}
<header className="h-14 border-b border-rule bg-paper flex items-center justify-between gap-2 px-3 sm:px-6 shrink-0 z-10">
<div className="flex items-center gap-2 sm:gap-4 min-w-0">
{/* Mobile: the drawer handle, and the section name the icon rail
used to carry. Without it a phone has no "where am I". */}
<button
onClick={() => setNavOpen(true)}
aria-label="open navigation"
className="md:hidden -ml-1 p-2 rounded-input text-muted active:bg-paper3 transition-colors shrink-0"
>
<Menu size={20} />
</button>
<span data-tutorial="nav-clips" className="md:hidden font-display lowercase text-base text-ink truncate">
{activeNav?.label || 'clipwright'}
</span>
{status !== 'idle' && (
<button
onClick={handleReset}
className="btn-quiet px-3 py-1.5 text-xs shrink-0"
aria-label="New Project"
>
<Plus size={14} />
<span className="hidden sm:inline">New Project</span>
</button>
)}
</div>
<div className="flex items-center gap-2 sm:gap-4 shrink-0">
{postizChannels.length > 0 && (
<UserProfileSelector channels={postizChannels} postizUrl={postizUrl} />
)}
{/* Hidden below sm: the standing banner underneath already says the
same thing, and two warnings in a 360px header is just noise. */}
{keysMissing && (
<button
onClick={() => goToTab('settings')}
className="badge-warn hover:brightness-125 transition-all hidden sm:inline-flex"
title="Configure your Gemini API key"
>
<AlertTriangle size={12} />
<span className="hidden md:inline">Gemini API Key Missing</span>
<span className="md:hidden">keys missing</span>
</button>
)}
</div>
</header>
{/* Persistent Missing Keys Banner — visible on every screen */}
{keysMissing && activeTab !== 'settings' && (
<div className="mx-3 sm:mx-6 mt-3 px-3.5 sm:px-4 py-3 bg-paper2 border border-rule rounded-card flex flex-wrap items-center justify-between gap-2.5 sm:gap-4 shrink-0 animate-fade">
<div className="flex items-start sm:items-center gap-2.5 sm:gap-3 text-sm text-ink2 min-w-0 flex-1">
<KeyRound size={16} className="shrink-0 text-warn mt-0.5 sm:mt-0" />
<div className="min-w-0">
<span className="font-medium text-ink">Required API keys missing.</span>{' '}
<span className="text-muted">
Set your Gemini API key to use Clipwright.
</span>
</div>
</div>
<button
onClick={() => goToTab('settings')}
className="btn-quiet px-3 py-1.5 text-xs shrink-0 w-full sm:w-auto"
>
Go to Settings
</button>
</div>
)}
{/* Session Recovery Banner */}
{sessionRecovered && (
<div className="mx-3 sm:mx-6 mt-2 px-3.5 sm:px-4 py-3 bg-paper2 border border-rule rounded-card flex items-start justify-between gap-3 animate-fade shrink-0">
<div className="flex items-start sm:items-center gap-2 text-sm text-ink2 flex-wrap min-w-0">
<RotateCcw size={16} className="text-brass shrink-0 mt-0.5 sm:mt-0" />
<span className="font-medium">Session recovered</span>
<span className="text-muted text-xs">Your previous work has been restored.</span>
</div>
<button
onClick={() => setSessionRecovered(false)}
aria-label="dismiss"
className="text-muted hover:text-ink transition-colors shrink-0 -m-1 p-1"
>
<X size={16} />
</button>
</div>
)}
{/* Main Workspace */}
<div className="flex-1 overflow-hidden relative">
{/* View: Settings */}
{activeTab === 'settings' && (
<div className="h-full overflow-y-auto p-4 sm:p-8 max-w-2xl mx-auto animate-fade">
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 mb-8">
<div>
<p className="eyebrow mb-1.5">03 · SETTINGS</p>
<h1 className="font-display lowercase text-2xl text-ink">Settings</h1>
</div>
<div className="flex items-center gap-2 text-xs text-muted mt-1">
<Shield size={12} className="text-ok shrink-0" /> Privacy: keys only live in your browser (sent to backend just to process)
</div>
</div>
<KeyInput onKeySet={setApiKey} savedKey={apiKey} />
<div className="card p-4 sm:p-6 mt-8">
<div className="flex flex-wrap items-center justify-between gap-2 mb-4">
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-input bg-paper3 flex items-center justify-center shrink-0">
<Share2 size={16} className="text-brass" />
</div>
<h2 className="text-base font-medium text-ink lowercase">Publishing (Postiz)</h2>
</div>
<span className="readout">FOR PUBLISHING</span>
</div>
<p className="text-xs text-muted mb-6 leading-relaxed">
Optional — clipping works without it. To publish your clips to TikTok, Instagram Reels, and
YouTube Shorts through your own self-hosted <strong>Postiz</strong> instance, connect your
channels inside Postiz, then paste its public API URL and key here.
</p>
<div className="space-y-4">
<div>
<label className="block text-sm text-muted mb-1.5">postiz base url</label>
<input
type="text"
value={postizUrl}
onChange={(e) => setPostizUrl(e.target.value)}
className="input-field"
placeholder="https://postiz.example.com"
/>
</div>
<div>
<label className="block text-sm text-muted mb-1.5">postiz api key</label>
<div className="flex flex-col sm:flex-row gap-2">
<input
type="password"
value={postizKey}
onChange={(e) => setPostizKey(e.target.value)}
className="input-field"
placeholder="public api key"
/>
<button
onClick={() => fetchPostizChannels()}
disabled={!postizConfigured}
className="btn-quiet py-2 px-4 text-sm shrink-0 disabled:opacity-45 disabled:cursor-not-allowed"
>
test connection
</button>
</div>
</div>
{!postizConfigured && (
<p className="text-xs text-warn leading-relaxed">
Enter your own Postiz base URL and API key to enable the connection test and publishing.
</p>
)}
{postizChannels.length > 0 && (
<div className="rounded-input border border-rule bg-paper p-3">
<p className="eyebrow mb-2">CONNECTED CHANNELS</p>
<div className="space-y-2">
{postizChannels.map((ch) => (
<div key={ch.id} className="flex items-center gap-2 text-sm text-ink2">
<ChannelIcon identifier={ch.identifier} size={14} />
<span className="truncate">{ch.name || ch.identifier}</span>
<span className="readout ml-auto">{ch.identifier}</span>
</div>
))}
</div>
</div>
)}
<div className="text-xs text-muted leading-relaxed">
{postizUrl ? (
<>Open <a href={postizUrl} target="_blank" rel="noopener noreferrer" className="text-brass underline">your Postiz instance</a>,
add your channels, then create a public API key under Settings → Public API.</>
) : (
<>Enter your own Postiz base URL above, add your channels in that instance, then create a public API key under Settings → Public API.</>
)}
<br />
<span className="text-muted">
Keys are only stored in your browser. They are sent to the backend only to process your request, never stored server-side.
</span>
</div>
</div>
</div>
</div>
)}
{activeTab === 'thumbnails' && (
<ThumbnailStudio
geminiApiKey={apiKey}
postizKey={postizKey}
postizUrl={postizUrl}
onCreateClips={(sessionId) => {
setActiveTab('dashboard');
// The Studio source is the user's own upload, published to their
// own channel; the handover carries that same attestation.
handleProcess({ type: 'thumbnail_session', payload: sessionId, acknowledged: true });
}}
/>
)}
{/* View: Dashboard (Idle) */}
{activeTab === 'dashboard' && status === 'idle' && (
<div className="h-full overflow-y-auto custom-scrollbar animate-fade">
<div className="min-h-full flex flex-col items-center justify-center px-4 py-5 sm:p-6">
{/* On a phone the hero used to fill the fold on its own and push
the uploader — the whole point of the screen — below it. The
eyebrow, the display size and the gaps all shrink first. */}
<div className="max-w-xl w-full text-center space-y-5 sm:space-y-8">
<div className="space-y-2.5 sm:space-y-4">
<p className="eyebrow hidden sm:block">01 · CLIP GENERATOR</p>
<h1 className="font-display lowercase text-3xl sm:text-4xl md:text-5xl text-ink">
Create Viral Shorts
</h1>
<p className="text-muted text-[15px] sm:text-lg leading-snug sm:leading-normal max-w-sm sm:max-w-none mx-auto">
Drop your long-form video below to instantly generate viral clips with AI.
</p>
</div>
<MediaInput onProcess={handleProcess} isProcessing={status === 'processing'} />
<div className="flex flex-wrap items-center justify-center gap-4 sm:gap-8 text-muted text-xs sm:text-sm">
<span className="flex items-center gap-2"><Youtube size={16} /> YouTube</span>
<span className="flex items-center gap-2"><Instagram size={16} /> Instagram</span>
<span className="flex items-center gap-2"><TikTokIcon size={16} /> TikTok</span>
</div>
</div>
</div>
</div>
)}
{/* View: Processing / Results (Split View) */}
{activeTab === 'dashboard' && (status === 'processing' || status === 'complete' || status === 'error') && (
<div className="h-full flex flex-col md:flex-row gap-3 md:gap-4 p-3 md:p-4 overflow-y-auto md:overflow-y-hidden custom-scrollbar animate-fade">
{/* Left Panel: Preview & Status */}
<div className={`${status === 'complete' ? 'w-full md:w-[30%] lg:w-[25%]' : 'w-full md:w-[55%] lg:w-[60%]'} md:h-full flex flex-col shrink-0 md:shrink card p-3.5 sm:p-6 md:overflow-y-auto custom-scrollbar transition-all duration-700 ease-in-out`}>
<div className="mb-4 sm:mb-6 flex items-center justify-between gap-2">
<h2 className="text-sm font-medium text-ink lowercase flex items-center gap-2">
<Activity className={`text-brass ${status === 'processing' ? 'animate-pulse' : ''}`} size={18} />
Live Analysis
</h2>
<span className={status === 'processing' ? 'badge-brass' :
status === 'complete' ? 'badge-ok' :
'badge-danger'
}>
{status.toUpperCase()}
</span>
</div>
{/* Video Preview */}
{processingMedia && (
<ProcessingAnimation
media={processingMedia}
isComplete={status === 'complete'}
syncedTime={syncedTime}
isSyncedPlaying={isSyncedPlaying}
syncTrigger={syncTrigger}
/>
)}
{/* Phones only. The scan box drops its invented telemetry at
this size and the log terminal below starts collapsed, so
without this the screen would say nothing about what the job
is actually doing. The log tail is the real answer. */}
{status === 'processing' && (
<div className="sm:hidden mb-3 flex items-start gap-2 text-xs text-ink2 min-w-0">
<Loader2 size={14} className="animate-spin text-brass shrink-0 mt-px" />
<span className="min-w-0 leading-snug break-words">
{logs.length ? logs[logs.length - 1] : 'starting up…'}
</span>
</div>
)}
{/* The render is dead time: the user is watching a progress bar
with nothing to do, so this is where the one star ask goes. */}
{status === 'processing' && (
<div className="my-3">
<StarBanner message="Got a minute while this renders?" />
</div>
)}
{/* Logs Terminal */}
<div className={`bg-paper rounded-card border border-rule overflow-hidden flex flex-col transition-all duration-500 ${status === 'complete' ? `min-h-0 opacity-50 hover:opacity-100 ${logsVisible ? 'h-32' : 'h-auto'}` : `flex-1 ${logsVisible ? 'min-h-[160px] sm:min-h-[200px]' : 'min-h-0 flex-none'}`}`}>
<button
type="button"
onClick={() => setLogsVisible(!logsVisible)}
aria-expanded={logsVisible}
className="w-full px-3.5 sm:px-4 py-2.5 border-b border-rule flex items-center justify-between gap-2 bg-paper2 shrink-0 text-left"
>
<span className="readout flex items-center gap-2">
<Terminal size={12} /> System Logs
</span>
<span className="flex items-center gap-2 text-muted">
{!logsVisible && logs.length > 0 && (
<span className="readout normal-case">{logs.length}</span>
)}
<ChevronDown size={16} className={logsVisible ? '' : 'rotate-180'} />
</span>
</button>
{logsVisible && (
<div className="flex-1 p-3.5 sm:p-4 overflow-y-auto font-mono text-[11px] sm:text-xs space-y-1.5 custom-scrollbar text-muted break-words">
{logs.map((log, i) => (
<div key={i} className={`flex gap-2 ${log.toLowerCase().includes('error') ? 'text-danger' : 'text-muted'}`}>
<span className="text-muted opacity-50 shrink-0 hidden sm:inline tabular-nums">
{logTimes[i] ? new Date(logTimes[i] * 1000).toLocaleTimeString() : ''}
</span>
<span className="min-w-0 break-words">{log}</span>
</div>
))}
{status === 'processing' && (
<div className="animate-pulse text-brass">_</div>
)}
</div>
)}
</div>
</div>
{/* Right Panel: Results Grid */}
<div className={`${status === 'complete' ? 'w-full md:w-[70%] lg:w-[75%]' : 'w-full md:w-[45%] lg:w-[40%]'} md:h-full flex flex-col shrink-0 md:shrink card p-3.5 sm:p-6 transition-all duration-700 ease-in-out`}>
{/* Title + counters on one row, the two actions on their own row
below. Wrapping them all together dropped a lone half-width
"schedule week" pill under the title on a phone. */}
<div className="mb-4 sm:mb-6 shrink-0 space-y-3">
<h2 className="font-display lowercase text-lg sm:text-xl text-ink flex flex-wrap items-center gap-2">
<span className="mr-auto">Generated Shorts</span>
{results?.clips?.length > 0 && (
<span className="readout bg-paper3 px-2.5 py-1 rounded-full">
{results.clips.length} Clips
</span>
)}
{results?.cost_analysis && (
<span className="readout bg-paper3 px-2.5 py-1 rounded-full" title={`Input: ${results.cost_analysis.input_tokens} | Output: ${results.cost_analysis.output_tokens}`}>
GEMINI · ${results.cost_analysis.total_cost.toFixed(5)}
</span>
)}
</h2>
{results?.clips?.length > 0 && status === 'complete' && (
<div className="flex flex-col sm:flex-row sm:justify-end items-stretch sm:items-center gap-2">
<button
onClick={handleDownloadAll}
disabled={downloadingAll}
className="btn-ghost px-3 py-2 text-xs"
title="Download all clips as a ZIP"
>
{downloadingAll
? <><Loader2 size={14} className="animate-spin" />zipping…</>
: <><Download size={14} />download all</>}
</button>
</div>
)}
</div>
{status === 'complete' && results?.clips?.length > 0 && (
<div className="mb-2 space-y-2">
{/* Distribution nudge at the same peak: clips on screen,
publishing them is one connect away. Hidden once Postiz
is configured or the user dismisses it. */}
{showSocialNudge && (
<div className="w-full flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 px-3 py-2.5 rounded-input bg-paper3 border border-rule text-sm">
<div className="flex items-start gap-3 flex-1 min-w-0">
<div className="min-w-0 leading-relaxed">
<span className="text-ink">Publish these clips straight from here.</span>{' '}
<span className="text-muted">Connect your YouTube, TikTok or Instagram once — after that every clip is one click from posted.</span>
</div>
{/* On a phone the dismiss X rides the copy, so the CTA
below can run the full width of the card. */}
<button
onClick={() => {
track('SocialNudgeDismissed');
setSocialNudgeDismissed(true);
try { localStorage.setItem('cw_social_nudge_dismissed', '1'); } catch (_) { /* ignore */ }
}}
aria-label="dismiss"
className="sm:hidden shrink-0 -m-1 p-1 text-muted hover:text-ink"
>
<X size={16} />
</button>
</div>
<button
onClick={() => { track('SocialNudgeConnect'); handleConnectSocials(); }}
className="btn-quiet shrink-0 text-xs py-1.5 px-3 lowercase w-full sm:w-auto"
>
connect socials →
</button>
<button
onClick={() => {
track('SocialNudgeDismissed');
setSocialNudgeDismissed(true);
try { localStorage.setItem('cw_social_nudge_dismissed', '1'); } catch (_) { /* ignore */ }
}}
aria-label="dismiss"
className="hidden sm:block shrink-0 p-1 text-muted hover:text-ink"
>
<X size={14} />
</button>
</div>
)}
{/* Clips really are gone once the retention sweep runs. */}
{jobRetentionSeconds > 0 && (
<div className="px-3 py-2.5 rounded-input bg-paper3 border border-paper3 text-sm">
<span className="text-ink">Clips are kept for {formatRetention(jobRetentionSeconds)}, then deleted.</span>{' '}
<span className="text-muted">Download what you want to keep, or raise JOB_RETENTION_SECONDS in your env.</span>
</div>
)}
</div>
)}
<div className="flex-1 overflow-y-auto custom-scrollbar p-1">
{results && results.clips && results.clips.length > 0 ? (
<div className={`grid gap-4 pb-10 ${status === 'complete' ? 'grid-cols-[repeat(auto-fill,minmax(min(100%,600px),1fr))]' : 'grid-cols-1'}`}>
{rankedClips.map(({ clip, index: i }) => (
<ResultCard
key={`${jobId}-${i}-${clip.video_url || ''}`}
clip={clip}
index={i}
jobId={jobId}
onEditClip={(index) => setEditingClip(index)}
onReframeClip={(index) => setReframingClip(index)}
postizKey={postizKey}
postizUrl={postizUrl}
geminiApiKey={apiKey}
onConnectSocials={handleConnectSocials}
onPlay={(time) => handleClipPlay(time)}
onPause={handleClipPause}
onBulkSubtitle={handleBulkSubtitles}
clipCount={results.clips.length}
bulkProgress={bulkSub}
/>
))}
</div>
) : (
status === 'processing' ? (
<div className="h-full min-h-[140px] flex flex-col items-center justify-center text-muted space-y-3 text-center px-4">
<Loader2 size={28} className="animate-spin text-brass" />
<p className="text-sm lowercase">Waiting for clips...</p>
<p className="text-xs text-muted/80 max-w-[26ch] leading-snug">
They appear here one by one as each finishes rendering.
</p>
</div>
) : status === 'error' ? (
<div className="h-full min-h-[120px] flex flex-col items-center justify-center text-danger space-y-2">
<p>Generation failed.</p>
</div>
) : null
)}
</div>
</div>
</div>
)}
</div>
{/* Phone navigation. A flex sibling of the scrolling pane, not a fixed
overlay, so content is never trapped behind it. */}
<MobileTabBar />
</main>
{/* Missing API Key Modal */}
<Modal
isOpen={showKeyModal}
onClose={() => setShowKeyModal(false)}
eyebrow="SETUP"
title="Gemini API Key Required"
footer={
<div className="flex gap-3">
<button
onClick={() => setShowKeyModal(false)}
className="btn-ghost flex-1 px-4 py-2 text-sm"
>
Cancel
</button>
<button
onClick={() => { setShowKeyModal(false); goToTab('settings'); }}
className="btn-primary flex-1 px-4 py-2 text-sm"
>
Go to Settings
</button>
</div>
}
>
<div className="space-y-4">
<p className="text-sm text-muted">
Clipwright needs a <strong className="text-ink2">Gemini</strong> API key to generate clips.
</p>
{/* Gemini block */}
<div className={`rounded-input p-4 space-y-2 border ${!apiKey ? 'border-rule2' : 'border-rule opacity-70'}`}>
<p className="text-xs font-medium text-ink flex items-center gap-2">
{apiKey ? <Check size={12} className="text-ok" /> : <AlertTriangle size={12} className="text-warn" />}
Gemini API Key {apiKey && <span className="text-ok">— set</span>}
</p>
{!apiKey && (
<>
<ol className="text-xs text-muted space-y-1 list-decimal list-inside">
<li>Go to <a href="https://aistudio.google.com/app/apikey" target="_blank" rel="noopener noreferrer" className="text-brass underline">aistudio.google.com/app/apikey</a></li>
<li>Sign in with your Google account</li>
<li>Click "Create API Key"</li>
<li>Copy the key and paste it below</li>
</ol>
<input
type="text"
placeholder="Paste your Gemini API key here..."
className="input-field"
onKeyDown={(e) => {
if (e.key === 'Enter' && e.target.value.trim()) {
setApiKey(e.target.value.trim());
}
}}
/>
</>
)}
</div>
</div>
</Modal>
{/* Pre-flight quality gate */}
{qualityGate && (
<Modal isOpen={true} onClose={() => setQualityGate(null)} size="md" eyebrow="HEADS UP" title="low source quality">
<div className="space-y-4">
<p className="text-sm text-ink2">
YouTube only offers <span className="text-brass font-semibold">{qualityGate.info.max_height}p</span> for this video
(below the {qualityGate.info.min_height}p we recommend). Processing anyway will produce lower-quality clips.
</p>
{qualityGate.info.cookies_invalid && (
<p className="text-xs text-muted">
Your YouTube cookies look expired — refreshing them (export again from an incognito window) often unlocks HD.
</p>
)}
<div className="flex gap-2 justify-end pt-2">
<button onClick={() => setQualityGate(null)} className="btn-ghost">cancel</button>
<button
onClick={() => { const d = qualityGate.data; setQualityGate(null); handleProcess(d, true); }}
className="btn-primary"
>
process anyway
</button>
</div>
</div>
</Modal>
)}
{editingClip !== null && results?.clips?.[editingClip] && (
<ClipEditor
jobId={jobId}
clipIndex={editingClip}
clipTitle={results.clips[editingClip].video_title_for_youtube_short || ''}
onClose={() => setEditingClip(null)}
onRerendered={handleClipRerendered}
/>
)}
{reframingClip !== null && results?.clips?.[reframingClip] && (
<ReframeEditor
jobId={jobId}
clipIndex={reframingClip}
clipTitle={results.clips[reframingClip].video_title_for_youtube_short || ''}
onClose={() => setReframingClip(null)}
onReframed={handleClipRerendered}
/>
)}
{tutorialPhase && (
<ClipTutorial
phase={tutorialPhase}
jobStatus={status}
errorText={jobError}
onStart={startTutorial}
onSkip={skipTutorial}
onDismissCelebrate={finishTutorial}
/>
)}
</div>
);
}
export default App;