clipwright/dashboard/src/components/BridgeModal.jsx
pedro-bento 2dc1ba1eea
All checks were successful
CI / backend-e2e (push) Successful in 1m20s
CI / unit (push) Successful in 45s
CI / dashboard-e2e (push) Successful in 2m31s
feat/youtube-growth-toolkit (#8)
Reviewed-on: #8
Co-authored-by: pedro-bento <mail@pbento.pt>
Co-committed-by: pedro-bento <mail@pbento.pt>
2026-10-05 20:33:56 +01:00

331 lines
18 KiB
JavaScript

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 (
<Modal
isOpen={isOpen}
onClose={onClose}
eyebrow="YOUTUBE · BRIDGE"
title="shorts → long-form"
size="lg"
>
{loading && (
<div className="flex items-center justify-center gap-2 py-10 text-sm text-muted lowercase">
<Loader2 size={16} className="animate-spin text-brass" /> loading bridge…
</div>
)}
{!loading && error && (
<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">{error}</span>
</div>
)}
{!loading && !error && data && (
<div>
<p className="text-xs text-muted leading-snug mb-5">
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.
</p>
{/* Related-video target */}
<section className="mb-5">
<label className="eyebrow block mb-1.5">RELATED VIDEO TARGET</label>
{data.related_video_url ? (
<div className="flex items-center gap-2 bg-paper rounded-input border border-rule px-3 py-2 min-w-0">
<Youtube size={14} className="text-muted shrink-0" />
<a
href={data.related_video_url}
target="_blank"
rel="noopener noreferrer"
className="text-xs text-ink2 truncate flex-1 min-w-0 hover:text-brass transition-colors"
>
{data.related_video_url}
</a>
<button
onClick={() => handleCopy('target', data.related_video_url)}
aria-label="copy related video url"
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
>
{copied === 'target' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
</button>
</div>
) : (
<div className="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" />
<span>
No related video set for this clip yet. Paste the long-form URL into YouTube Studio's
{' '}<b className="font-medium">Related video</b> field when you set it up — the checklist below has the steps.
</span>
</div>
)}
</section>
{/* Manual Studio checklist */}
<section className="mb-5">
<div className="flex items-center justify-between gap-2 mb-2">
<label className="eyebrow">STUDIO CHECKLIST</label>
<span className="readout">manual · no api</span>
</div>
{Array.isArray(data.checklist) && data.checklist.length > 0 ? (
<ol className="space-y-1.5">
{data.checklist.map((step, i) => {
const done = !!checkedSteps[i];
return (
<li key={i}>
<button
type="button"
onClick={() => toggleStep(i)}
aria-pressed={done}
className={`w-full text-left flex items-start gap-2.5 px-3 py-2 rounded-input border transition-colors ${done ? 'border-rule bg-paper opacity-70' : 'border-rule hover:bg-paper3'}`}
>
{done
? <CheckCircle2 size={15} className="text-ok mt-0.5 shrink-0" />
: <span className="mt-0.5 w-[15px] h-[15px] rounded-full border border-rule2 shrink-0" aria-hidden="true" />}
<span className={`text-xs leading-snug ${done ? 'text-muted' : 'text-ink2'}`}>{step}</span>
</button>
</li>
);
})}
</ol>
) : (
<p className="text-xs text-muted lowercase">no checklist saved for this clip.</p>
)}
</section>
{/* Copy-paste copy */}
<section className="mb-5">
<div className="flex items-center justify-between gap-2 mb-1.5">
<label className="eyebrow">DESCRIPTION BRIDGE</label>
<button
onClick={() => handleCopy('desc', data.description_bridge)}
aria-label="copy description bridge"
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
>
{copied === 'desc' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
</button>
</div>
{data.description_bridge ? (
<p className="text-xs text-ink2 select-all break-words whitespace-pre-wrap bg-paper rounded-input p-3 border border-rule max-h-40 overflow-y-auto custom-scrollbar">
{data.description_bridge}
</p>
) : (
<p className="text-xs text-muted lowercase bg-paper rounded-input p-3 border border-dashed border-rule">
no description copy generated for this clip.
</p>
)}
</section>
<section className="mb-5">
<div className="flex items-center justify-between gap-2 mb-1.5">
<label className="eyebrow">FIRST COMMENT</label>
<button
onClick={() => handleCopy('comment', data.first_comment)}
aria-label="copy first comment"
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
>
{copied === 'comment' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
</button>
</div>
{data.first_comment ? (
<p className="text-xs text-ink2 select-all break-words whitespace-pre-wrap bg-paper rounded-input p-3 border border-rule">
{data.first_comment}
</p>
) : (
<p className="text-xs text-muted lowercase bg-paper rounded-input p-3 border border-dashed border-rule">
no first comment generated for this clip.
</p>
)}
</section>
{/* Optional opt-in comment posting */}
<section className="border-t border-rule pt-4">
<div className="flex items-center gap-2 mb-1.5">
<label className="eyebrow">POST FIRST COMMENT</label>
<span className="badge-ok">opt-in</span>
</div>
<p className="text-xs text-muted leading-snug mb-3">
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.
</p>
{!configured ? (
<div className="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" />
<span>
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.
</span>
</div>
) : (
<div className="space-y-2">
<div className="flex flex-col sm:flex-row gap-2">
<input
type="text"
value={videoId}
onChange={(e) => 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"
/>
<button
onClick={handlePostComment}
disabled={posting || !canPostComment}
className="btn-primary shrink-0"
title={!data.first_comment ? 'No comment text to post' : (videoId.trim() ? undefined : 'Enter the published Short id first')}
>
{posting
? <><Loader2 size={15} className="animate-spin" /> posting…</>
: <><MessageSquare size={15} /> post comment</>}
</button>
</div>
{postStatus && (
<div className={`px-3 py-2 rounded-input text-xs flex items-start gap-2 ${postStatus.ok
? 'text-ok bg-[color-mix(in_oklab,var(--color-ok)_10%,transparent)]'
: 'text-danger bg-[color-mix(in_oklab,var(--color-danger)_10%,transparent)]'}`}
>
{postStatus.ok
? <Check size={14} className="mt-0.5 shrink-0" />
: <AlertCircle size={14} className="mt-0.5 shrink-0" />}
<span className="break-words">{postStatus.msg}</span>
</div>
)}
</div>
)}
<p className="readout mt-3 flex items-center gap-1.5">
<Link2 size={12} className="shrink-0" /> related-video link + pin: Studio only
</p>
</section>
</div>
)}
</Modal>
);
}