import React, { useState, useEffect } from 'react'; import { Copy, Check, CheckCircle2, AlertCircle, Loader2, Link2, Youtube, MessageSquare } from 'lucide-react'; import Modal from './ui/Modal'; import { apiFetch } from '../lib/api'; // Shorts -> long-form bridge (PLAN #6). The related-video link and comment // pinning are Studio-UI only, so this panel always carries the manual steps: // it never pretends the server can set them. // // Copy it? Use the copy buttons. Post the first comment automatically? Only // when you click it, and only on a server with the YouTube Data API wired up. // Accept a full YouTube URL or a bare id and return just the id. The published // Short's id is what the comment endpoint needs; people usually have the URL. function videoIdFrom(raw) { const value = String(raw || '').trim(); if (!value) return ''; const urlMatch = value.match(/(?:v=|\/shorts\/|youtu\.be\/|\/embed\/)([A-Za-z0-9_-]{6,})/); if (urlMatch) return urlMatch[1]; const bare = value.match(/^([A-Za-z0-9_-]{6,})$/); return bare ? bare[1] : value; } export default function BridgeModal({ isOpen, onClose, jobId, clipIndex }) { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [copied, setCopied] = useState(null); // Checked-off Studio steps, remembered per clip so closing the sheet while // working through the manual steps doesn't lose your place. const storageKey = `cw_bridge_check_${jobId}_${clipIndex}`; const [checkedSteps, setCheckedSteps] = useState({}); const [videoId, setVideoId] = useState(''); const [posting, setPosting] = useState(false); const [postStatus, setPostStatus] = useState(null); useEffect(() => { if (!isOpen) return undefined; let cancelled = false; setLoading(true); setError(null); setData(null); setPostStatus(null); setVideoId(''); try { setCheckedSteps(JSON.parse(localStorage.getItem(storageKey)) || {}); } catch { setCheckedSteps({}); } apiFetch(`/api/clip/${jobId}/${clipIndex}/bridge`) .then(async (res) => { if (!res.ok) { let detail = ''; const text = await res.text().catch(() => ''); 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 load the bridge (${res.status}).`); } return res.json(); }) .then((payload) => { if (!cancelled) setData(payload); }) .catch((e) => { if (!cancelled) setError(e.message || 'Could not load the bridge.'); }) .finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [isOpen, jobId, clipIndex]); const handleCopy = async (field, text) => { try { await navigator.clipboard.writeText(text || ''); setCopied(field); setTimeout(() => setCopied(null), 2000); } catch { // clipboard unavailable — silent } }; const toggleStep = (i) => { setCheckedSteps((prev) => { const next = { ...prev, [i]: !prev[i] }; try { localStorage.setItem(storageKey, JSON.stringify(next)); } catch { /* storage unavailable */ } return next; }); }; const handlePostComment = async () => { const vid = videoIdFrom(videoId); if (!vid) return; setPosting(true); setPostStatus(null); try { const res = await apiFetch(`/api/clip/${jobId}/${clipIndex}/bridge/comment`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: vid, text: data?.first_comment || undefined }), }); if (!res.ok) { let detail = ''; const text = await res.text().catch(() => ''); try { const j = JSON.parse(text); if (typeof j.detail === 'string') detail = j.detail; } catch { /* keep the raw body */ } // A 400 here almost always means the YouTube integration is not // configured; say that plainly and point at the manual route. const fallback = res.status === 400 ? "This server can't post comments yet — the YouTube Data API isn't set up. Copy the comment above and post it in Studio instead." : `Could not post the comment (${res.status}).`; setPostStatus({ ok: false, msg: detail || fallback }); return; } await res.json().catch(() => ({})); setPostStatus({ ok: true, msg: 'Comment posted. Open YouTube Studio and pin it — pinning stays manual.' }); } catch (e) { setPostStatus({ ok: false, msg: e.message || 'Could not post the comment.' }); } finally { setPosting(false); } }; // The endpoint reports whether comment posting is available on this server. // An older/absent field is treated as "try it" — a 400 is handled above. const configured = data ? data.comment_api_configured !== false : true; const canPostComment = configured && !!videoId.trim() && !!data?.first_comment; return ( {loading && (
loading bridge…
)} {!loading && error && (
{error}
)} {!loading && !error && data && (

Funnel viewers of this Short to a long-form video. The related-video link and the comment pin live only in YouTube Studio, so those steps stay manual.

{/* Related-video target */}
{data.related_video_url ? (
{data.related_video_url}
) : (
No related video set for this clip yet. Paste the long-form URL into YouTube Studio's {' '}Related video field when you set it up — the checklist below has the steps.
)}
{/* Manual Studio checklist */}
manual · no api
{Array.isArray(data.checklist) && data.checklist.length > 0 ? (
    {data.checklist.map((step, i) => { const done = !!checkedSteps[i]; return (
  1. ); })}
) : (

no checklist saved for this clip.

)}
{/* Copy-paste copy */}
{data.description_bridge ? (

{data.description_bridge}

) : (

no description copy generated for this clip.

)}
{data.first_comment ? (

{data.first_comment}

) : (

no first comment generated for this clip.

)}
{/* Optional opt-in comment posting */}
opt-in

Optional. clipwright never posts on its own — this runs only when you click the button. Pinning the comment still has to be done by hand in Studio.

{!configured ? (
This server has no YouTube Data API credentials, so it can't post for you. Copy the comment above and post it in Studio instead.
) : (
setVideoId(e.target.value)} className="input-field sm:flex-1" placeholder="published Short video id or URL" aria-label="published Short video id or URL" />
{postStatus && (
{postStatus.ok ? : } {postStatus.msg}
)}
)}

related-video link + pin: Studio only

)}
); }