import { useCallback, useEffect, useRef, useState } from 'react'; import { AlertCircle, ArrowDown, ArrowUp, Check, ChevronDown, Download, Loader2, Plus, Radio, Save, Trash2, Upload, X, } from 'lucide-react'; import { apiFetch, apiJson } from '../lib/api'; // Channel profiles (PLAN #1): one channel's packaging rules — the title // constraints, hook patterns and thumbnail direction the pipeline reads. This // panel is the CRUD surface over /api/channels; the backend owns validation, // this only does enough up front to catch an obviously bad slug. // Enum mirrors the backend schema (clipwright/pipeline/profiles.py), kept in // display order rather than sorted so the picker reads the way it is written. const KEYWORD_POSITIONS = ['start', 'middle', 'end', 'any']; const NUMBER_POLICIES = ['allow', 'avoid', 'require']; const REQUIRED_SIGNALS = ['consequence', 'curiosity', 'either', 'none']; const THUMBNAIL_ROLES = ['curiosity', 'emotion', 'technical']; // Same slug contract as the server: no separators, no traversal segments. const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/; // A single exported profile file may omit `slug` (the old channels/*.json used // the file name as the id). Derive one so selecting such a file just works: // the file name wins, then the profile's own name. Bundle/list entries derive // from their own name only — a shared file name would collide. const slugify = (value) => String(value ?? '') .normalize('NFKD') .replace(/[\u0300-\u036f]/g, '') .trim() .toLowerCase() .replace(/[^a-z0-9_-]+/g, '-') .replace(/^[-_]+|[-_]+$/g, ''); const deriveSlug = (item, fallback) => { if (!item || typeof item !== 'object' || Array.isArray(item) || item.slug) return item; const candidate = slugify(fallback) || slugify(item.name); return SLUG_RE.test(candidate) ? { ...item, slug: candidate } : item; }; const withImportedSlugs = (parsed, filename) => { if (Array.isArray(parsed)) return parsed.map((item) => deriveSlug(item, '')); if (parsed && typeof parsed === 'object' && Array.isArray(parsed.profiles)) { return { ...parsed, profiles: parsed.profiles.map((item) => deriveSlug(item, '')) }; } const stem = String(filename || '').replace(/\.[^.]+$/, ''); return deriveSlug(parsed, stem); }; // A fresh profile. A function, not a constant, so nested arrays are never // shared between two opens of the form. const emptyForm = () => ({ slug: '', name: '', language: 'en', tone: '', title_rules: { max_chars: 70, mobile_chars: 40, banned_patterns: [], keyword_position: 'start', number_policy: 'allow', required_signal: 'either', banned_openers: [], }, hook_patterns: [], hook_style: '', description_template: '', links: [], thumbnail: { role_order: ['curiosity', 'emotion', 'technical'], palette: [], presenter_photo: false, }, default_postiz_integration_id: '', published_video_history: [], }); // Backend profile -> editable form state. Every field is defaulted so a // partially-specified profile (the schema makes them all optional) still // renders a complete form. const profileToForm = (data) => { const t = data?.title_rules || {}; const th = data?.thumbnail || {}; return { slug: data?.slug || '', name: data?.name ?? '', language: data?.language ?? 'en', tone: data?.tone ?? '', title_rules: { max_chars: t.max_chars ?? 70, mobile_chars: t.mobile_chars ?? 40, banned_patterns: Array.isArray(t.banned_patterns) ? t.banned_patterns : [], keyword_position: t.keyword_position || 'start', number_policy: t.number_policy || 'allow', required_signal: t.required_signal || 'either', banned_openers: Array.isArray(t.banned_openers) ? t.banned_openers : [], }, hook_patterns: Array.isArray(data?.hook_patterns) ? data.hook_patterns : [], hook_style: data?.hook_style ?? '', description_template: data?.description_template ?? '', links: Array.isArray(data?.links) ? data.links : [], thumbnail: { role_order: Array.isArray(th.role_order) && th.role_order.length ? th.role_order : ['curiosity', 'emotion', 'technical'], palette: Array.isArray(th.palette) ? th.palette : [], presenter_photo: !!th.presenter_photo, }, default_postiz_integration_id: data?.default_postiz_integration_id ?? '', // Held verbatim: the panel never edits history, but a save must not // drop it. published_video_history: Array.isArray(data?.published_video_history) ? data.published_video_history : [], }; }; const toInt = (value, fallback) => { const n = typeof value === 'number' ? value : parseInt(String(value).trim(), 10); return Number.isFinite(n) ? n : fallback; }; // Form state -> PUT/POST body. `slug` is handled by the caller: it is part of // the create body only and never sent on update. const formToPayload = (form) => ({ name: form.name.trim(), language: form.language.trim() || 'en', tone: form.tone, title_rules: { max_chars: toInt(form.title_rules.max_chars, 70), mobile_chars: toInt(form.title_rules.mobile_chars, 40), banned_patterns: form.title_rules.banned_patterns, keyword_position: form.title_rules.keyword_position, number_policy: form.title_rules.number_policy, required_signal: form.title_rules.required_signal, banned_openers: form.title_rules.banned_openers, }, hook_patterns: form.hook_patterns, hook_style: form.hook_style, description_template: form.description_template, links: form.links, thumbnail: { role_order: form.thumbnail.role_order, palette: form.thumbnail.palette, presenter_photo: !!form.thumbnail.presenter_photo, }, default_postiz_integration_id: form.default_postiz_integration_id.trim() || null, published_video_history: form.published_video_history, }); // Prefer the server's own explanation (FastAPI {"detail": "..."}) over a // generic fallback, same convention as the rest of the app. const errText = (err, fallback) => err?.detail || err?.message || fallback; const Field = ({ label, hint, className = '', children }) => (

{label}

{children} {hint &&

{hint}

}
); // Numbered rule-of-thirds section: a mono ordinal, a label, then a hairline // running to the edge. Breaks a long spec sheet into something scannable. const Section = ({ n, title, children }) => (
{n}

{title}

{children}
); // Chip input for every string-list field. Enter commits, Backspace on an empty // draft removes the last chip, blur commits whatever is typed. function TagInput({ values, onChange, placeholder = 'type and press enter' }) { const [draft, setDraft] = useState(''); const commit = () => { const v = draft.trim(); if (!v) return; if (!values.includes(v)) onChange([...values, v]); setDraft(''); }; return (
{values.map((v) => ( {v} ))} setDraft(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); commit(); } else if (e.key === 'Backspace' && !draft && values.length) { onChange(values.slice(0, -1)); } }} onBlur={commit} placeholder={values.length ? '' : placeholder} className="flex-1 min-w-[7rem] bg-transparent px-1.5 py-1 text-sm text-ink2 placeholder:text-muted/70 outline-none" />
); } // Ordered list of thumbnail concept roles: reorder with the arrows, drop or // re-add with the x / + controls. function RoleOrderField({ value, onMove, onToggle }) { const ordered = Array.isArray(value) ? value : []; const missing = THUMBNAIL_ROLES.filter((r) => !ordered.includes(r)); return (
{missing.length > 0 && (
{missing.map((role) => ( ))}
)} {ordered.length === 0 && (

Add at least one role so thumbnails have a concept to follow.

)}
); } // The app's standard pill switch (same markup as the subtitle editor). function Toggle({ checked, onChange, label, hint }) { return ( ); } function EditorSkeleton() { return (