import React, { useState, useEffect, useRef } from 'react'; import { Download, Share2, Instagram, Youtube, AlertCircle, Loader2, Copy, Check, Wand2, Type, Calendar, FileText, Link2, Scissors, Crosshair, TrendingUp } from 'lucide-react'; import { getApiUrl } from '../config'; import { apiFetch } from '../lib/api'; import SubtitleModal from './SubtitleModal'; import HookModal from './HookModal'; import BridgeModal from './BridgeModal'; import Modal from './ui/Modal'; import { renderInBrowser } from '../lib/renderInBrowser'; const QUIET_BTN = 'group flex flex-col items-center justify-center gap-1 py-2.5 sm:py-2 px-1 rounded-input border border-rule hover:bg-paper3 text-[11px] lowercase text-ink2 whitespace-nowrap transition-colors disabled:opacity-45 disabled:cursor-not-allowed'; // Postiz integration identifier -> glyph. Anything we do not special-case falls // back to a generic share glyph so every connected channel still shows up. const TikTokGlyph = ({ size = 16 }) => ( ); const PlatformIcon = ({ identifier, size = 16 }) => { const id = String(identifier || '').toLowerCase(); if (id.includes('tiktok')) return ; if (id.includes('instagram')) return ; if (id.includes('youtube')) return ; return ; }; // Today as YYYY-MM-DD in the user's own timezone, for the date input's `min`. // Built from local parts (not toISOString, which would shift the day across the // UTC boundary for users west of Greenwich). function todayInputValue() { const n = new Date(); return `${n.getFullYear()}-${String(n.getMonth() + 1).padStart(2, '0')}-${String(n.getDate()).padStart(2, '0')}`; } // YYYY-MM-DD (a native date picker's value) + HH:MM parsed into a local Date, // with explicit range checks so 2026-02-31 is rejected instead of silently // rolling over to March. function parseSchedule(dateStr, timeStr) { const d = String(dateStr || '').trim(); const t = String(timeStr || '').trim(); if (!d || !t) return { error: 'Pick a date and a time.' }; const dm = d.match(/^(\d{4})-(\d{2})-(\d{2})$/); if (!dm) return { error: 'Date must be in yyyy-mm-dd format.' }; const year = Number(dm[1]); const month = Number(dm[2]); const day = Number(dm[3]); if (month < 1 || month > 12) return { error: 'Month must be between 01 and 12.' }; if (day < 1 || day > 31) return { error: 'Day must be between 01 and 31.' }; const tm = t.match(/^(\d{1,2}):(\d{2})$/); if (!tm) return { error: 'Time must be in HH:MM format.' }; const hour = Number(tm[1]); const minute = Number(tm[2]); if (hour > 23 || minute > 59) return { error: 'Time must be between 00:00 and 23:59.' }; const date = new Date(year, month - 1, day, hour, minute, 0, 0); if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) { return { error: 'That date does not exist.' }; } return { date }; } function clipDurationSeconds(clip) { // A recut clip's start/end are the covering source range (segments may be // non-contiguous or reordered); its real duration is the segment sum. const segments = clip.recipe?.segments; if (segments?.length) { return segments.reduce((acc, s) => acc + (s.end - s.start), 0); } return clip.end && clip.start ? clip.end - clip.start : NaN; } function formatDuration(clip) { const secs = Math.floor(clipDurationSeconds(clip)); if (!Number.isFinite(secs) || secs < 0) return null; return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`; } export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, geminiApiKey, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, onConnectSocials, onEditClip = null, onReframeClip = null, suggestedSchedule = null }) { const [showModal, setShowModal] = useState(false); // The "why" line is clamped to two lines so cards in a row stay level; // when it overflows, a hover (desktop) or tap (touch) shows the whole // sentence in a popover that floats over the card instead of growing it. const whyRef = useRef(null); const [whyOpen, setWhyOpen] = useState(false); const [whyClamped, setWhyClamped] = useState(false); useEffect(() => { const el = whyRef.current; if (!el) return; const check = () => setWhyClamped(el.scrollHeight > el.clientHeight + 1); check(); window.addEventListener('resize', check); return () => window.removeEventListener('resize', check); }, [clip.why]); const [showDescModal, setShowDescModal] = useState(false); const [showSubtitleModal, setShowSubtitleModal] = useState(false); const videoRef = React.useRef(null); // Pristine base clip (no burned subtitles/hook), stable regardless of how // clip.video_url mutates after server edits. Used as the compositing base // for the Remotion preview so it never stacks subtitles over an already- // subtitled file (double-subtitle bug). const stripBurns = (filename) => { let f = filename || '', prev; do { prev = f; f = f.replace(/^subtitled_\d+_/, '').replace(/^hooked_\d+_/, '').replace(/^hook_/, ''); } while (f !== prev); return f; }; const originalVideoUrl = getApiUrl((clip.video_url || '').replace(/[^/]+$/, stripBurns((clip.video_url || '').split('/').pop()))); const [currentVideoUrl, setCurrentVideoUrl] = useState(getApiUrl(clip.video_url)); // A delivered clip is tens of MB, and on a slow link the old silent // fetch-then-save took minutes with nothing on screen, which reads as a dead // button. Stream it instead and report progress. const [downloadPct, setDownloadPct] = useState(null); const downloadClip = async () => { try { setDownloadPct(0); // The server packages the saved clip (not the transient blob: // preview this card may be showing) as a `/` folder zip. const response = await fetch(getApiUrl(`/api/jobs/${jobId}/clip/${index}/download`)); if (!response.ok) throw new Error('Download failed'); const total = Number(response.headers.get('content-length')) || 0; let blob; // No body reader (old browser) or no length to measure against: fall // back to the plain path rather than lose the download. if (!response.body || !total) { blob = await response.blob(); } else { const reader = response.body.getReader(); const chunks = []; let received = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); received += value.length; setDownloadPct(Math.min(99, Math.round((received / total) * 100))); } blob = new Blob(chunks, { type: 'application/zip' }); } // The server names the bundle `<title>.zip`. Prefer the RFC 5987 // form when present so non-ASCII titles survive; fall back to the // plain quoted filename, then to a generic numbered name. let filename = `clip-${index + 1}.zip`; const disposition = response.headers.get('content-disposition') || ''; const rfc5987 = disposition.match(/filename\*=UTF-8''([^;]+)/i); const plain = disposition.match(/filename="?([^";]+)"?/i); if (rfc5987) { try { filename = decodeURIComponent(rfc5987[1]); } catch { // malformed percent-encoding — keep the fallback name } } else if (plain) { filename = plain[1]; } const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; a.download = filename; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); document.body.removeChild(a); } catch (err) { console.error('Download error:', err); window.open(currentVideoUrl, '_blank'); } finally { setDownloadPct(null); } }; // Latest file that exists ON THE SERVER (blob: previews don't count). // All server-side operations must chain from this, so burned-in edits // (subtitles, hooks, effects) never get silently dropped. const [serverVideoFile, setServerVideoFile] = useState((clip.video_url || '').split('/').pop()); const [resolution, setResolution] = useState(null); // When an external refresh changes this clip's server file (e.g. bulk // subtitles applied from another card), adopt it so the card shows the // freshly subtitled video instead of a stale one. useEffect(() => { const serverUrl = getApiUrl(clip.video_url); const serverName = (clip.video_url || '').split('/').pop(); if (serverName && serverName !== serverVideoFile) { setServerVideoFile(serverName); setCurrentVideoUrl(serverUrl); if (videoRef.current) videoRef.current.load(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [clip.video_url]); // Publish form state. const [postTitle, setPostTitle] = useState(""); const [postDescription, setPostDescription] = useState(""); const [isScheduling, setIsScheduling] = useState(false); const [scheduleDate, setScheduleDate] = useState(""); const [scheduleTime, setScheduleTime] = useState(""); // Channels from GET /api/postiz/integrations, one row each (disabled ones // included but unselectable). Selected by integration id, not platform name. const [integrations, setIntegrations] = useState([]); const [integrationsLoading, setIntegrationsLoading] = useState(false); const [integrationsError, setIntegrationsError] = useState(null); const [selectedIds, setSelectedIds] = useState([]); const [posting, setPosting] = useState(false); const [postResult, setPostResult] = useState(null); const [copied, setCopied] = useState(null); const handleCopy = async (field, text) => { try { await navigator.clipboard.writeText(text || ''); setCopied(field); setTimeout(() => setCopied(null), 2000); } catch { // clipboard unavailable — silent } }; const [isEditing, setIsEditing] = useState(false); const [isSubtitling, setIsSubtitling] = useState(false); const [isHooking, setIsHooking] = useState(false); const [showHookModal, setShowHookModal] = useState(false); const [showBridgeModal, setShowBridgeModal] = useState(false); const [editError, setEditError] = useState(null); const [clipDuration, setClipDuration] = useState(() => { const secs = clipDurationSeconds(clip); return Number.isFinite(secs) ? secs : 30; }); // Accumulate Remotion layers across operations so an edit composes over the // previous browser-side work instead of silently dropping it. const [activeLayers, setActiveLayers] = useState({ subtitles: null, hook: null, effects: null }); // True when the current server file already carries burned-in content. // Browser (Remotion) renders compose over the ORIGINAL clip, so using them // here would silently drop those burns — chain via server FFmpeg instead. const hasServerBurns = /(^|_)(subtitled|hook|hooked)_/.test(serverVideoFile || ''); // The hook currently burned into the server file (auto-hook or a manual // one). /api/hook REPLACES it; tracked locally so the modal stays honest // after edits without refetching the job. const [burnedHook, setBurnedHook] = useState(clip.auto_hook?.text || null); // Fetch clip duration from transcript endpoint useEffect(() => { if (!jobId || index === undefined) return; apiFetch(`/api/clip/${jobId}/${index}/transcript`) .then(res => res.ok ? res.json() : null) .then(data => { if (data && data.durationSec) setClipDuration(data.durationSec); }) .catch(() => {}); }, [jobId, index]); // Accounts are connected inside the user's own Postiz instance, so // "connect" opens it (or Settings when no URL is configured yet). const handleConnectAccounts = () => { setShowModal(false); if (onConnectSocials) onConnectSocials(); else if (postizUrl) window.open(postizUrl, '_blank', 'noopener'); }; // Every integration is a selectable row; disabled ones are listed but not // selectable, and every enabled channel starts selected. const toggleIntegration = (id) => { setSelectedIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id])); }; // Load the full channel list whenever the publish modal opens. The list is // keyed by integration id, so multiple channels on the same platform (e.g. // two YouTube channels) stay distinct. useEffect(() => { if (!showModal) return undefined; let cancelled = false; const load = async () => { if (!postizKey || !postizUrl) { if (!cancelled) { setIntegrations([]); setIntegrationsLoading(false); setIntegrationsError(null); } return; } setIntegrationsLoading(true); setIntegrationsError(null); try { const headers = { 'X-Postiz-Url': postizUrl.replace(/\/$/, '') }; headers['X-Postiz-Key'] = postizKey; const res = await apiFetch('/api/postiz/integrations', { headers }); if (!res.ok) { const text = await res.text(); let detail = text; try { const j = JSON.parse(text); if (typeof j.detail === 'string') detail = j.detail; } catch { /* keep the raw body */ } throw new Error(detail || 'Could not reach Postiz.'); } const data = await res.json(); const list = Array.isArray(data) ? data : (data.integrations || []); if (cancelled) return; setIntegrations(list); setSelectedIds(list.filter((c) => !c.disabled).map((c) => c.id)); } catch (e) { if (cancelled) return; setIntegrations([]); setIntegrationsError(e.message || 'Could not reach Postiz.'); } finally { if (!cancelled) setIntegrationsLoading(false); } }; load(); return () => { cancelled = true; }; }, [showModal, postizKey, postizUrl]); // Reset the form each time the modal opens; the effect above also reloads // the channel list and reselects every enabled channel. When the results // panel has a global schedule start date, the post is prefilled with this // clip's slot for its virality rank and scheduling is switched on, so the // suggested time is visible up front (the user can uncheck to post now). useEffect(() => { if (showModal) { setPostTitle(clip.video_title_for_youtube_short || "Viral Short"); setPostDescription(clip.video_description_for_instagram || clip.video_description_for_tiktok || ""); setIsScheduling(!!suggestedSchedule); setScheduleDate(suggestedSchedule?.date ?? ""); setScheduleTime(suggestedSchedule?.time ?? ""); setPostResult(null); } }, [showModal, clip, suggestedSchedule]); const handleAutoEdit = async () => { setIsEditing(true); setEditError(null); try { const apiKey = geminiApiKey || localStorage.getItem('gemini_key'); // Managed (paid) users get the Gemini key resolved server-side; // only BYOK/self-host needs a local key. if (!apiKey) { throw new Error("Gemini API Key is missing. Please set it in Settings."); } const geminiHeaders = apiKey ? { 'X-Gemini-Key': apiKey } : {}; // Try Remotion effects endpoint first const effectsRes = hasServerBurns ? null : await apiFetch('/api/effects/generate', { method: 'POST', headers: { 'Content-Type': 'application/json', ...geminiHeaders }, body: JSON.stringify({ job_id: jobId, clip_index: index, input_filename: serverVideoFile }) }); if (effectsRes && effectsRes.ok) { const data = await effectsRes.json(); if (data.effects && data.effects.segments) { const newLayers = { ...activeLayers, effects: data.effects }; setActiveLayers(newLayers); const blobUrl = await renderInBrowser({ videoUrl: originalVideoUrl, durationInSeconds: clipDuration, subtitles: newLayers.subtitles, hook: newLayers.hook, effects: newLayers.effects, }); setCurrentVideoUrl(blobUrl); if (videoRef.current) videoRef.current.load(); return; } } // Fallback: legacy FFmpeg edit endpoint const res = await apiFetch('/api/edit', { method: 'POST', headers: { 'Content-Type': 'application/json', ...geminiHeaders }, body: JSON.stringify({ job_id: jobId, clip_index: index, input_filename: serverVideoFile }) }); if (!res.ok) { const errText = await res.text(); try { const jsonErr = JSON.parse(errText); throw new Error(jsonErr.detail || errText); } catch (e) { throw new Error(errText); } } const data = await res.json(); if (data.new_video_url) { setCurrentVideoUrl(getApiUrl(data.new_video_url)); setServerVideoFile(data.new_video_url.split('/').pop()); if (videoRef.current) { videoRef.current.load(); } } } catch (e) { setEditError(e.message); setTimeout(() => setEditError(null), 5000); } finally { setIsEditing(false); } }; // Clips are captioned by default, so "no captions" has to be reachable. // Nothing is re-encoded: the server still holds the clean file next to the // captioned one and just points this clip back at it. const handleRemoveSubtitles = async () => { setIsSubtitling(true); setEditError(null); try { const res = await apiFetch('/api/subtitle/remove', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ job_id: jobId, clip_index: index, input_filename: serverVideoFile, }), }); if (!res.ok) throw new Error(await res.text()); const data = await res.json(); if (data.new_video_url) { const serverUrl = getApiUrl(data.new_video_url); setServerVideoFile(data.new_video_url.split('/').pop()); const remaining = { ...activeLayers, subtitles: null }; setActiveLayers(remaining); if (remaining.hook || remaining.effects) { setCurrentVideoUrl(await renderInBrowser({ videoUrl: serverUrl, durationInSeconds: clipDuration, subtitles: null, hook: remaining.hook, effects: remaining.effects, })); } else { setCurrentVideoUrl(serverUrl); } if (videoRef.current) videoRef.current.load(); setShowSubtitleModal(false); } } catch (e) { setEditError(e.message); setTimeout(() => setEditError(null), 5000); } finally { setIsSubtitling(false); } }; const handleSubtitle = async (options) => { setIsSubtitling(true); setEditError(null); try { // Karaoke styles are burned server-side (ASS word-highlight render); // the in-browser Remotion path only handles classic styles, and only // when the server file has no burned-in content to preserve. if (options.remotion && options.style !== 'karaoke' && !hasServerBurns) { // Accumulate layer and render all layers together const newLayers = { ...activeLayers, subtitles: options.remotion }; setActiveLayers(newLayers); const blobUrl = await renderInBrowser({ videoUrl: originalVideoUrl, durationInSeconds: clipDuration, subtitles: newLayers.subtitles, hook: newLayers.hook, effects: newLayers.effects, }); setCurrentVideoUrl(blobUrl); if (videoRef.current) videoRef.current.load(); setShowSubtitleModal(false); return; } // Fallback: legacy FFmpeg const res = await apiFetch('/api/subtitle', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ job_id: jobId, clip_index: index, 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 || 'classic', 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, input_filename: serverVideoFile, // Edited caption text (clip-relative ms); null = server // regenerates from the transcript as before. words: options.captions || null }) }); if (!res.ok) throw new Error(await res.text()); const data = await res.json(); if (data.new_video_url) { const serverUrl = getApiUrl(data.new_video_url); setServerVideoFile(data.new_video_url.split('/').pop()); // Subtitles are burned into the server file now — drop the // browser subtitle layer and re-compose any remaining browser // layers (hook/effects) over the new file so they aren't lost. const remaining = { ...activeLayers, subtitles: null }; setActiveLayers(remaining); if (remaining.hook || remaining.effects) { const blobUrl = await renderInBrowser({ videoUrl: serverUrl, durationInSeconds: clipDuration, subtitles: null, hook: remaining.hook, effects: remaining.effects, }); setCurrentVideoUrl(blobUrl); } else { setCurrentVideoUrl(serverUrl); } if (videoRef.current) videoRef.current.load(); setShowSubtitleModal(false); } } catch (e) { setEditError(e.message); setTimeout(() => setEditError(null), 5000); } finally { setIsSubtitling(false); } }; const handleHook = async (hookData) => { setIsHooking(true); setEditError(null); try { if (hookData.remotion && !hasServerBurns) { // Accumulate layer and render all layers together const newLayers = { ...activeLayers, hook: hookData.remotion }; setActiveLayers(newLayers); const blobUrl = await renderInBrowser({ videoUrl: originalVideoUrl, durationInSeconds: clipDuration, subtitles: newLayers.subtitles, hook: newLayers.hook, effects: newLayers.effects, }); setCurrentVideoUrl(blobUrl); if (videoRef.current) videoRef.current.load(); setShowHookModal(false); return; } // Fallback: legacy FFmpeg const payload = typeof hookData === 'string' ? { text: hookData, position: 'top', size: 'M' } : hookData; const res = await apiFetch('/api/hook', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ job_id: jobId, clip_index: index, text: payload.text, position: payload.position, size: payload.size, style: payload.style || 'pill', font: payload.font || null, duration_seconds: payload.remotion?.displayDurationSec ?? null, input_filename: serverVideoFile }) }); if (!res.ok) throw new Error(await res.text()); const data = await res.json(); if (data.new_video_url) { setCurrentVideoUrl(getApiUrl(data.new_video_url)); setServerVideoFile(data.new_video_url.split('/').pop()); setBurnedHook(data.burned_hook?.text ?? payload.text ?? null); if (videoRef.current) videoRef.current.load(); setShowHookModal(false); } } catch (e) { setEditError(e.message); setTimeout(() => setEditError(null), 5000); } finally { setIsHooking(false); } }; // Strip the burned hook (auto-hook or manual) off the server file. const handleRemoveHook = async () => { setIsHooking(true); setEditError(null); try { const res = await apiFetch('/api/hook', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ job_id: jobId, clip_index: index, remove: true, input_filename: serverVideoFile, }), }); if (!res.ok) throw new Error(await res.text()); const data = await res.json(); if (data.new_video_url) { setCurrentVideoUrl(getApiUrl(data.new_video_url)); setServerVideoFile(data.new_video_url.split('/').pop()); setBurnedHook(null); if (videoRef.current) videoRef.current.load(); setShowHookModal(false); } } catch (e) { setEditError(e.message); setTimeout(() => setEditError(null), 5000); } finally { setIsHooking(false); } }; // Publishing needs both the Postiz base URL and API key; clipping does not. const canPost = !!postizKey && !!postizUrl; // No channels only counts once a load has finished without error, so the // "connect accounts" prompt never flashes while the list is in flight. const noChannels = !integrationsLoading && !integrationsError && integrations.length === 0; const handlePost = async () => { if (!canPost) { setPostResult({ success: false, msg: "Postiz is not configured. Add your base URL and API key in Settings." }); return; } const enabledIds = integrations.filter((c) => !c.disabled).map((c) => c.id); const chosen = selectedIds.filter((id) => enabledIds.includes(id)); if (chosen.length === 0) { setPostResult({ success: false, msg: "Select at least one channel." }); return; } // The date/time is only required when scheduling; "publish now" needs none. let scheduledIso = null; if (isScheduling) { const parsed = parseSchedule(scheduleDate, scheduleTime); if (parsed.error) { setPostResult({ success: false, msg: parsed.error }); return; } scheduledIso = parsed.date.toISOString(); } setPosting(true); setPostResult(null); try { const payload = { job_id: jobId, clip_index: index, integration_ids: chosen, title: postTitle, description: postDescription }; if (scheduledIso) { payload.scheduled_date = scheduledIso; payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; } const headers = { 'Content-Type': 'application/json' }; if (postizKey) headers['X-Postiz-Key'] = postizKey; if (postizUrl) headers['X-Postiz-Url'] = postizUrl.replace(/\/$/, ''); const res = await apiFetch('/api/postiz/post', { method: 'POST', headers, body: JSON.stringify(payload) }); if (!res.ok) { const errText = await res.text(); let detail = errText; try { const jsonErr = JSON.parse(errText); if (typeof jsonErr.detail === 'string') detail = jsonErr.detail; } catch { /* keep the raw body */ } throw new Error(detail || 'Publish failed.'); } const data = await res.json(); const posted = Array.isArray(data.posted) ? data.posted : []; const names = posted.map((p) => p.name || p.identifier || p.platform).filter(Boolean); const target = names.length ? names.join(', ') : `${chosen.length} channel${chosen.length === 1 ? '' : 's'}`; const when = scheduledIso ? `on ${scheduleDate} at ${scheduleTime} (${payload.timezone})` : 'now'; setPostResult({ success: true, msg: `Posted to ${target} ${when}.` }); // Keep the confirmation up long enough to read it before closing. setTimeout(() => { setShowModal(false); setPostResult(null); }, 4000); } catch (e) { setPostResult({ success: false, msg: e.message || 'Publish failed.' }); } finally { setPosting(false); } }; const durationReadout = formatDuration(clip); return ( <div className="card overflow-hidden flex flex-col md:flex-row group hover:border-rule2 transition-colors animate-fade md:min-h-[420px]" style={{ animationDelay: `${index * 0.1}s` }}> {/* Left: Video Preview — 9:16 column matching the fixed card height */} {/* A full-width 9:16 preview on a phone is ~640px tall on its own, which pushed the title, captions and every action off-screen. Capping the height and centring keeps the whole card scannable without letterboxing the clip. */} <div className="w-full max-w-[calc(64vh*0.5625)] md:max-w-none mx-auto md:mx-0 md:w-[236px] bg-black relative shrink-0 aspect-[9/16] md:aspect-auto group/video"> <video ref={videoRef} src={currentVideoUrl} controls className="w-full h-full object-contain" playsInline onLoadedMetadata={(e) => { if (e.target.videoWidth) setResolution(`${e.target.videoWidth}×${e.target.videoHeight}`); }} onPlay={() => { const currentTime = videoRef.current ? videoRef.current.currentTime : 0; onPlay && onPlay(clip.start + currentTime); }} onPause={() => onPause && onPause()} onEnded={() => { if (videoRef.current) { videoRef.current.currentTime = 0; videoRef.current.play(); } }} /> <div className="absolute top-3 left-3 flex gap-2"> {/* Stays the clip's own number, not its rank: the cards are ordered by score, but this is what the downloaded file is called (clip-N.mp4) and what every api call indexes. */} <span className="bg-black/70 text-ink font-mono text-micro uppercase px-2 py-1 rounded-full"> Clip {index + 1} </span> {/* A bare number on a thumbnail reads as a duration, a position, anything — it has to name itself and carry its scale, or it is decoration. */} {Number.isFinite(clip.predicted_score) && ( <span className="bg-black/70 font-mono text-micro uppercase px-2 py-1 rounded-full flex items-center gap-1" title="clipwright' prediction of how well this clip will perform, from 0 to 100" > <TrendingUp size={11} className="shrink-0 text-muted" /> <span className="text-muted">viral</span> <b className={ clip.predicted_score >= 80 ? 'text-ok' : clip.predicted_score >= 65 ? 'text-brass' : 'text-ink2' }> {clip.predicted_score} </b> <span className="text-muted">/100</span> </span> )} </div> {/* Auto Edit Overlay if Processing */} {isEditing && ( <div className="absolute inset-0 bg-black/70 flex flex-col items-center justify-center z-10 p-4 text-center"> <Loader2 size={28} className="text-brass animate-spin mb-3" /> <span className="text-xs text-ink lowercase">ai magic in progress…</span> <span className="readout mt-1.5">APPLYING VIRAL EDITS · ZOOMS</span> </div> )} </div> {/* Right: Content & Details */} <div className="flex-1 p-4 md:p-5 flex flex-col overflow-hidden min-w-0"> <div className="mb-4"> <h3 className="text-base font-medium text-ink leading-tight line-clamp-2 mb-2 break-words" title={clip.video_title_for_youtube_short}> {clip.video_title_for_youtube_short || "Viral Clip Generated"} </h3> {/* The score alone says how much, not why. One line from the selection pass on what this moment has going for it. */} {clip.why && ( <div className="relative mb-2" onMouseEnter={() => setWhyOpen(true)} onMouseLeave={() => setWhyOpen(false)} > <p ref={whyRef} className={`text-xs text-muted leading-snug line-clamp-2 break-words ${whyClamped ? 'cursor-pointer' : ''}`} onClick={() => whyClamped && setWhyOpen(v => !v)} aria-label="why clipwright picked this moment" > {clip.why} </p> {whyClamped && whyOpen && ( <div role="tooltip" className="absolute left-0 right-0 top-full mt-1 z-20 bg-paper border border-rule rounded-input px-3 py-2 text-xs text-ink leading-snug shadow-lg" > {clip.why} </div> )} </div> )} <div className="flex flex-wrap gap-1.5"> {durationReadout && <span className="readout bg-paper3 px-2 py-0.5 rounded-full shrink-0">{durationReadout}</span>} {resolution && <span className="readout bg-paper3 px-2 py-0.5 rounded-full shrink-0">{resolution}</span>} <span className="readout bg-paper3 px-2 py-0.5 rounded-full shrink-0">#shorts</span> <span className="readout bg-paper3 px-2 py-0.5 rounded-full shrink-0">#viral</span> </div> </div> {/* Descriptions (compact) — full text lives in the modal */} <div className="flex-1 min-h-0 space-y-2 mb-4"> <div className="bg-paper rounded-input px-3 py-2 border border-rule flex items-center gap-2 min-w-0 overflow-hidden"> <span className="eyebrow shrink-0">YOUTUBE</span> <p className="text-xs text-ink2 truncate flex-1 min-w-0"> {clip.video_title_for_youtube_short || "Viral Short Video"} </p> <button onClick={() => handleCopy('youtube', clip.video_title_for_youtube_short || "Viral Short Video")} aria-label="copy youtube title" className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0" > {copied === 'youtube' ? <Check size={14} className="text-ok" /> : <Copy size={14} />} </button> </div> <div className="bg-paper rounded-input px-3 py-2 border border-rule flex items-center gap-2 min-w-0 overflow-hidden"> <span className="eyebrow shrink-0">TIKTOK · IG</span> <p className="text-xs text-ink2 truncate flex-1 min-w-0"> {clip.video_description_for_tiktok || clip.video_description_for_instagram} </p> <button onClick={() => handleCopy('caption', clip.video_description_for_tiktok || clip.video_description_for_instagram)} aria-label="copy caption" className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0" > {copied === 'caption' ? <Check size={14} className="text-ok" /> : <Copy size={14} />} </button> </div> <button onClick={() => setShowDescModal(true)} className="w-full flex items-center justify-center gap-2 py-2 rounded-input border border-dashed border-rule text-xs lowercase text-muted hover:text-brass hover:border-rule2 transition-colors" > <FileText size={14} /> view descriptions </button> </div> {/* Error Message */} {editError && ( <div className="mb-3 px-3 py-2 rounded-input text-xs text-danger bg-[color-mix(in_oklab,var(--color-danger)_10%,transparent)] flex items-center gap-2"> <AlertCircle size={14} className="shrink-0" /> {editError} </div> )} {/* Actions Footer */} <div className="grid grid-cols-[repeat(auto-fill,minmax(104px,1fr))] gap-2 mt-auto pt-4 border-t border-rule"> {onEditClip && ( <button onClick={() => onEditClip(index)} className={QUIET_BTN} > <Scissors size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" /> edit clip </button> )} {onReframeClip && ( <button onClick={() => onReframeClip(index)} className={QUIET_BTN} > <Crosshair size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" /> reframing </button> )} <button onClick={handleAutoEdit} disabled={isEditing} className={QUIET_BTN} > {isEditing ? <Loader2 size={16} className="animate-spin text-brass shrink-0" /> : <Wand2 size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" />} {isEditing ? 'editing…' : 'auto edit'} </button> <button onClick={() => setShowSubtitleModal(true)} disabled={isSubtitling} className={QUIET_BTN} > {isSubtitling ? <Loader2 size={16} className="animate-spin text-brass shrink-0" /> : <Type size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" />} {isSubtitling ? 'adding…' : 'subtitles'} </button> <button onClick={() => setShowHookModal(true)} disabled={isHooking} className={QUIET_BTN} > {isHooking ? <Loader2 size={16} className="animate-spin text-brass shrink-0" /> : <Wand2 size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" />} {isHooking ? 'saving…' : 'edit hook'} </button> <button onClick={() => setShowBridgeModal(true)} className={QUIET_BTN} title="Shorts → long-form bridge: related video, first comment, Studio checklist" > <Link2 size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" /> bridge </button> <button onClick={() => setShowModal(true)} className="btn-primary flex-col gap-1 py-2.5 sm:py-2 px-1 text-[11px] leading-none rounded-input whitespace-nowrap" > <Share2 size={16} className="shrink-0" /> post </button> <button onClick={downloadClip} className={`${QUIET_BTN}${onEditClip ? ' col-span-2' : ''}`} > <Download size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" /> {downloadPct === null ? 'download' : `downloading ${downloadPct}%`} </button> </div> </div> {/* Descriptions Modal */} <Modal isOpen={showDescModal} onClose={() => setShowDescModal(false)} eyebrow="GENERATED COPY" title="descriptions" size="md" > <div className="space-y-4"> <div> <div className="flex items-center justify-between gap-2 mb-1.5"> <label className="eyebrow">YOUTUBE TITLE</label> <button onClick={() => handleCopy('youtube', clip.video_title_for_youtube_short || "Viral Short Video")} aria-label="copy youtube title" className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0" > {copied === 'youtube' ? <Check size={14} className="text-ok" /> : <Copy size={14} />} </button> </div> <p className="text-sm text-ink2 select-all break-words bg-paper rounded-input p-3 border border-rule"> {clip.video_title_for_youtube_short || "Viral Short Video"} </p> </div> <div> <div className="flex items-center justify-between gap-2 mb-1.5"> <label className="eyebrow">TIKTOK · IG CAPTION</label> <button onClick={() => handleCopy('caption', clip.video_description_for_tiktok || clip.video_description_for_instagram)} aria-label="copy caption" className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0" > {copied === 'caption' ? <Check size={14} className="text-ok" /> : <Copy size={14} />} </button> </div> <p className="text-sm text-ink2 select-all break-words bg-paper rounded-input p-3 border border-rule whitespace-pre-wrap"> {clip.video_description_for_tiktok || clip.video_description_for_instagram} </p> </div> </div> </Modal> {/* Post Modal */} <Modal isOpen={showModal} onClose={() => setShowModal(false)} eyebrow="PUBLISH" title="post clip" size="md" footer={ canPost && noChannels ? ( <button onClick={handleConnectAccounts} className="btn-primary w-full"> <Link2 size={16} /> connect accounts </button> ) : ( <button onClick={handlePost} disabled={posting || !canPost} className="btn-primary w-full" > {posting ? <><Loader2 size={16} className="animate-spin" /> {isScheduling ? 'scheduling…' : 'publishing…'}</> : <><Share2 size={16} /> {isScheduling ? 'schedule post' : 'publish now'}</>} </button> ) } > {!canPost && ( <div className="mb-4 px-3 py-2 rounded-input text-xs text-warn bg-[color-mix(in_oklab,var(--color-warn)_10%,transparent)] flex items-start gap-2"> <AlertCircle size={14} className="mt-0.5 shrink-0" /> <div className="lowercase">configure Postiz in settings first.</div> </div> )} <div className="space-y-4"> {/* Title & Description */} <div> <label className="eyebrow block mb-1.5">TITLE</label> <input type="text" value={postTitle} onChange={(e) => setPostTitle(e.target.value)} className="input-field" placeholder="enter a catchy title…" /> </div> <div> <label className="eyebrow block mb-1.5">CAPTION</label> <textarea value={postDescription} onChange={(e) => setPostDescription(e.target.value)} rows={4} className="input-field resize-none" placeholder="write a caption for your post…" /> </div> {/* Scheduling — native date picker + HH:MM */} <div className="p-3 bg-paper rounded-input border border-rule"> <label className="flex items-center justify-between cursor-pointer"> <span className="flex items-center gap-2 text-sm text-ink2 lowercase"> <Calendar size={16} className={isScheduling ? 'text-brass' : 'text-muted'} /> schedule post </span> <input type="checkbox" checked={isScheduling} onChange={(e) => setIsScheduling(e.target.checked)} className="w-4 h-4 accent-brass cursor-pointer" /> </label> {isScheduling && ( <div className="mt-3 animate-fade"> <label className="eyebrow block mb-1.5">DATE · TIME</label> <div className="flex gap-2"> <input type="date" value={scheduleDate} onChange={(e) => setScheduleDate(e.target.value)} min={todayInputValue()} aria-label="date" className="input-field flex-1 [color-scheme:dark]" /> <input type="time" value={scheduleTime} onChange={(e) => setScheduleTime(e.target.value)} aria-label="time (HH:MM)" className="input-field w-[7.5rem] [color-scheme:dark]" /> </div> <p className="text-xs text-muted mt-1.5">pick a day and a time, in your local timezone</p> {suggestedSchedule && ( <p className="text-xs text-muted mt-1">auto-filled from the schedule start date — change it freely</p> )} </div> )} </div> {/* Channels — every integration is selectable, by id. */} {canPost && ( <div> <label className="eyebrow block mb-2">CHANNELS</label> {integrationsLoading && ( <p className="text-xs text-muted lowercase flex items-center gap-2"> <Loader2 size={14} className="animate-spin" /> loading channels… </p> )} {!integrationsLoading && integrationsError && ( <div className="px-3 py-2 rounded-input text-xs text-danger bg-[color-mix(in_oklab,var(--color-danger)_10%,transparent)] flex items-start gap-2"> <AlertCircle size={14} className="mt-0.5 shrink-0" /> <span className="break-words">{integrationsError}</span> </div> )} {!integrationsLoading && !integrationsError && integrations.length === 0 && ( <p className="text-xs text-muted lowercase"> no channels connected yet — add them in Postiz first. </p> )} {integrations.length > 0 && ( <div className="space-y-1.5"> {integrations.map((ch) => { const isDisabled = !!ch.disabled; const checked = !isDisabled && selectedIds.includes(ch.id); return ( <label key={ch.id} className={`flex items-center gap-2.5 px-3 py-2 rounded-input border transition-colors ${isDisabled ? 'border-rule opacity-50 cursor-not-allowed' : checked ? 'border-brass bg-paper3 cursor-pointer' : 'border-rule hover:bg-paper3 cursor-pointer'}`} > <input type="checkbox" checked={checked} disabled={isDisabled} onChange={() => toggleIntegration(ch.id)} className="w-4 h-4 accent-brass cursor-pointer disabled:cursor-not-allowed" /> <span className="w-6 h-6 rounded-input bg-paper3 flex items-center justify-center shrink-0 text-ink2"> <PlatformIcon identifier={ch.identifier} size={14} /> </span> <span className="min-w-0 flex-1"> <span className="block text-sm text-ink2 truncate">{ch.name || ch.identifier}</span> <span className="block text-xs text-muted truncate">{ch.identifier}{ch.profile ? ` · ${ch.profile}` : ''}</span> </span> {isDisabled && <span className="readout shrink-0">off</span>} </label> ); })} </div> )} </div> )} {postResult && ( <div className={postResult.success ? 'badge-ok' : 'badge-danger'}> {postResult.success ? <Check size={12} className="shrink-0" /> : <AlertCircle size={12} className="shrink-0" />} {postResult.msg} </div> )} </div> </Modal> <SubtitleModal isOpen={showSubtitleModal} onClose={() => setShowSubtitleModal(false)} onGenerate={handleSubtitle} onApplyAll={onBulkSubtitle ? async (options) => { await onBulkSubtitle(options); setShowSubtitleModal(false); } : undefined} onRemove={handleRemoveSubtitles} bulkCount={clipCount} bulkProgress={bulkProgress} isProcessing={isSubtitling || (bulkProgress?.running ?? false)} videoUrl={originalVideoUrl} jobId={jobId} clipIndex={index} existingHook={activeLayers.hook} /> <HookModal isOpen={showHookModal} onClose={() => setShowHookModal(false)} onGenerate={handleHook} isProcessing={isHooking} videoUrl={originalVideoUrl} initialText={clip.viral_hook_text} durationInSeconds={clip.end && clip.start ? clip.end - clip.start : 30} existingSubtitles={activeLayers.subtitles} hasCaptions={!!activeLayers.subtitles || /(^|_)subtitled_/.test(serverVideoFile || '')} serverRender={hasServerBurns} burnedHook={burnedHook} onRemove={burnedHook ? handleRemoveHook : null} /> <BridgeModal isOpen={showBridgeModal} onClose={() => setShowBridgeModal(false)} jobId={jobId} clipIndex={index} /> </div> ); }