clipwright/dashboard/src/components/ChannelProfiles.jsx
pedro-bento 47add55c5f
All checks were successful
CI / unit (push) Successful in 45s
CI / backend-e2e (push) Successful in 1m23s
CI / dashboard-e2e (push) Successful in 2m26s
fix(dashboard): derive a slug when importing a single profile file (#10)
A single exported profile may omit `slug` (the old channels/*.json used the
file name as the id), so picking one in the UI failed with "profile entry is
missing a slug". Derive the slug from the file name (falling back to the
profile name) for a single-profile file; bundle/list entries derive from
their own name only, so a shared file name cannot collide.

Reviewed-on: #10
Co-authored-by: pedro-bento <mail@pbento.pt>
Co-committed-by: pedro-bento <mail@pbento.pt>
2026-10-06 13:27:09 +01:00

1058 lines
50 KiB
JavaScript

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 }) => (
<div className={`min-w-0 ${className}`}>
<p className="eyebrow mb-1.5">{label}</p>
{children}
{hint && <p className="text-xs text-muted mt-1.5 leading-relaxed">{hint}</p>}
</div>
);
// 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 }) => (
<section className="border-t border-rule pt-6 mt-6 [&:first-of-type]:border-t-0 [&:first-of-type]:pt-0 [&:first-of-type]:mt-0">
<div className="flex items-center gap-3 mb-4">
<span className="readout text-brass shrink-0">{n}</span>
<h3 className="eyebrow shrink-0">{title}</h3>
<span className="flex-1 h-px bg-[color:var(--color-rule)]" aria-hidden="true" />
</div>
{children}
</section>
);
// 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 (
<div className="rounded-input bg-paper border border-rule2 px-2 py-1.5 flex flex-wrap items-center gap-1.5 transition-colors focus-within:border-[color:var(--color-accent)]">
{values.map((v) => (
<span
key={v}
className="inline-flex items-center gap-1 pl-2.5 pr-1 py-1 rounded-full bg-paper3 text-xs text-ink2 max-w-full"
>
<span className="truncate">{v}</span>
<button
type="button"
onClick={() => onChange(values.filter((x) => x !== v))}
aria-label={`remove ${v}`}
className="shrink-0 p-0.5 text-muted hover:text-ink transition-colors"
>
<X size={11} />
</button>
</span>
))}
<input
value={draft}
onChange={(e) => 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"
/>
</div>
);
}
// 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 (
<div className="space-y-2">
<ul className="space-y-1.5">
{ordered.map((role, i) => (
<li
key={role}
className="flex items-center gap-1.5 rounded-input border border-rule bg-paper pl-2.5 pr-1 py-1.5"
>
<span className="readout w-4 text-center shrink-0">{i + 1}</span>
<span className="flex-1 min-w-0 text-sm lowercase text-ink2 truncate">{role}</span>
<button
type="button"
onClick={() => onMove(i, -1)}
disabled={i === 0}
aria-label={`move ${role} up`}
className="p-1 text-muted hover:text-ink disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
>
<ArrowUp size={13} />
</button>
<button
type="button"
onClick={() => onMove(i, 1)}
disabled={i === ordered.length - 1}
aria-label={`move ${role} down`}
className="p-1 text-muted hover:text-ink disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
>
<ArrowDown size={13} />
</button>
<button
type="button"
onClick={() => onToggle(role)}
aria-label={`remove ${role}`}
className="p-1 text-muted hover:text-danger transition-colors"
>
<X size={13} />
</button>
</li>
))}
</ul>
{missing.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{missing.map((role) => (
<button
key={role}
type="button"
onClick={() => onToggle(role)}
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full border border-dashed border-rule2 text-xs lowercase text-muted hover:text-ink2 hover:border-brass transition-colors"
>
<Plus size={11} /> {role}
</button>
))}
</div>
)}
{ordered.length === 0 && (
<p className="text-xs text-warn leading-relaxed">Add at least one role so thumbnails have a concept to follow.</p>
)}
</div>
);
}
// The app's standard pill switch (same markup as the subtitle editor).
function Toggle({ checked, onChange, label, hint }) {
return (
<label className="flex items-start gap-3 cursor-pointer select-none">
<span className="relative inline-flex items-center shrink-0 mt-0.5">
<input
type="checkbox"
checked={checked}
onChange={(e) => onChange(e.target.checked)}
className="sr-only peer"
/>
<span className="w-8 h-4 rounded-full bg-paper3 peer-checked:bg-brass transition-colors after:content-[''] after:absolute after:top-0 after:left-0 after:h-4 after:w-4 after:rounded-full after:bg-ink after:transition-all peer-checked:after:translate-x-full" />
</span>
<span className="min-w-0">
<span className="block text-sm lowercase text-ink2">{label}</span>
{hint && <span className="block text-xs text-muted mt-0.5 leading-relaxed">{hint}</span>}
</span>
</label>
);
}
function EditorSkeleton() {
return (
<div className="card p-4 sm:p-6 space-y-6" aria-hidden="true">
<div className="flex items-start justify-between gap-3">
<div className="space-y-2">
<div className="h-3 w-24 rounded-full bg-paper3 animate-pulse" />
<div className="h-6 w-44 rounded bg-paper3 animate-pulse" />
</div>
<div className="h-9 w-28 rounded-full bg-paper3 animate-pulse" />
</div>
{[0, 1].map((i) => (
<div key={i} className="space-y-3 border-t border-rule pt-6">
<div className="h-3 w-20 rounded-full bg-paper3 animate-pulse" />
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="h-10 rounded-input bg-paper3 animate-pulse" />
<div className="h-10 rounded-input bg-paper3 animate-pulse" />
</div>
</div>
))}
</div>
);
}
export default function ChannelProfiles() {
const [channels, setChannels] = useState([]);
const [listState, setListState] = useState('loading'); // loading | ready | error
const [listError, setListError] = useState('');
const [selectedSlug, setSelectedSlug] = useState(null);
const [mode, setMode] = useState('idle'); // idle | new | edit
const [form, setForm] = useState(emptyForm);
const [loadingProfile, setLoadingProfile] = useState(false);
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState('');
const [saved, setSaved] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
const [deleting, setDeleting] = useState(false);
const [importing, setImporting] = useState(false);
const [importError, setImportError] = useState('');
const [importResult, setImportResult] = useState(null);
const [exporting, setExporting] = useState(false);
const [exportError, setExportError] = useState('');
const fileInputRef = useRef(null);
const didAutoSelect = useRef(false);
const savedTimer = useRef(null);
const isNew = mode === 'new';
// Load the selector list. `silent` keeps a post-save refresh from flashing
// the rail back to its loading state.
const loadList = useCallback(async ({ silent = false } = {}) => {
if (!silent) setListState('loading');
setListError('');
try {
const data = await apiJson('/api/channels');
const items = Array.isArray(data?.channels)
? data.channels.filter((c) => c && c.slug)
: [];
setChannels(items);
setListState('ready');
return items;
} catch (err) {
setListError(errText(err, 'Could not reach the channel profiles service.'));
setListState('error');
return [];
}
}, []);
const openProfile = useCallback(async (slug) => {
setSelectedSlug(slug);
setMode('edit');
setSaveError('');
setSaved(false);
setConfirmDelete(false);
setLoadingProfile(true);
try {
const data = await apiJson(`/api/channels/${encodeURIComponent(slug)}`);
setForm(profileToForm(data));
} catch (err) {
setSaveError(errText(err, 'Could not load this profile.'));
} finally {
setLoadingProfile(false);
}
}, []);
// First paint: load the list, then open the first profile so the panel
// never sits on a dead curtain when profiles already exist.
useEffect(() => {
let cancelled = false;
(async () => {
const items = await loadList();
if (cancelled || didAutoSelect.current || !items.length) return;
didAutoSelect.current = true;
openProfile(items[0].slug);
})();
return () => { cancelled = true; };
}, [loadList, openProfile]);
// Drop the "saved" timer if the panel unmounts mid-flash.
useEffect(() => () => {
if (savedTimer.current) window.clearTimeout(savedTimer.current);
}, []);
const setField = (key, value) => setForm((f) => ({ ...f, [key]: value }));
const setTitleRule = (key, value) =>
setForm((f) => ({ ...f, title_rules: { ...f.title_rules, [key]: value } }));
const setThumbnail = (key, value) =>
setForm((f) => ({ ...f, thumbnail: { ...f.thumbnail, [key]: value } }));
const moveRole = (index, dir) => setForm((f) => {
const arr = [...f.thumbnail.role_order];
const j = index + dir;
if (j < 0 || j >= arr.length) return f;
[arr[index], arr[j]] = [arr[j], arr[index]];
return { ...f, thumbnail: { ...f.thumbnail, role_order: arr } };
});
const toggleRole = (role) => setForm((f) => {
const has = f.thumbnail.role_order.includes(role);
const arr = has
? f.thumbnail.role_order.filter((r) => r !== role)
: [...f.thumbnail.role_order, role];
return { ...f, thumbnail: { ...f.thumbnail, role_order: arr } };
});
const flashSaved = () => {
setSaved(true);
if (savedTimer.current) window.clearTimeout(savedTimer.current);
savedTimer.current = window.setTimeout(() => setSaved(false), 2600);
};
const startNew = () => {
setMode('new');
setSelectedSlug(null);
setForm(emptyForm());
setSaveError('');
setSaved(false);
setConfirmDelete(false);
};
const handleSave = async (e) => {
if (e) e.preventDefault();
if (saving) return;
const slug = form.slug.trim();
if (isNew && !SLUG_RE.test(slug)) {
setSaveError('Slug must start with a letter or number, then only letters, numbers, dashes or underscores.');
return;
}
setSaving(true);
setSaveError('');
setSaved(false);
try {
const payload = formToPayload(form);
if (isNew) {
await apiJson('/api/channels', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ slug, ...payload }),
});
} else {
await apiJson(`/api/channels/${encodeURIComponent(selectedSlug)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
}
const items = await loadList({ silent: true });
const nextSlug = isNew ? slug : selectedSlug;
if (items.some((i) => i.slug === nextSlug)) await openProfile(nextSlug);
else { setMode('edit'); setSelectedSlug(nextSlug); }
flashSaved();
} catch (err) {
setSaveError(errText(err, 'Could not save the profile.'));
} finally {
setSaving(false);
}
};
const handleDelete = async () => {
if (!selectedSlug || deleting) return;
setDeleting(true);
setSaveError('');
try {
await apiJson(`/api/channels/${encodeURIComponent(selectedSlug)}`, { method: 'DELETE' });
setConfirmDelete(false);
setSelectedSlug(null);
setMode('idle');
setForm(emptyForm());
const items = await loadList({ silent: true });
if (items.length) await openProfile(items[0].slug);
} catch (err) {
setSaveError(errText(err, 'Could not delete the profile.'));
setConfirmDelete(false);
} finally {
setDeleting(false);
}
};
const handleImportFile = async (e) => {
const file = e.target.files?.[0];
// Reset so picking the same file again still fires a change event.
e.target.value = '';
if (!file) return;
setImporting(true);
setImportError('');
setImportResult(null);
try {
const text = await file.text();
let parsed;
try {
parsed = JSON.parse(text);
} catch {
throw new Error('That file is not valid JSON.');
}
const data = await apiJson('/api/channels/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(withImportedSlugs(parsed, file.name)),
});
setImportResult({
imported: data?.imported ?? 0,
failed: Array.isArray(data?.failed) ? data.failed : [],
});
const items = await loadList({ silent: true });
if (!selectedSlug && items.length) await openProfile(items[0].slug);
} catch (err) {
setImportError(errText(err, 'Import failed.'));
} finally {
setImporting(false);
}
};
const handleExport = async (slug) => {
if (exporting) return;
setExporting(true);
setExportError('');
try {
const path = slug
? `/api/channels/export?slug=${encodeURIComponent(slug)}`
: '/api/channels/export';
const res = await apiFetch(path);
if (!res.ok) {
const raw = await res.text().catch(() => '');
let detail = '';
try { detail = JSON.parse(raw).detail || ''; } catch { /* not JSON */ }
throw new Error(detail || `Export failed (${res.status}).`);
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = slug ? `${slug}.json` : 'channel-profiles.json';
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
} catch (err) {
setExportError(err?.message || 'Export failed.');
} finally {
setExporting(false);
}
};
const editor = () => {
if (listState === 'loading' && channels.length === 0) return <EditorSkeleton />;
if (listState === 'error') {
return (
<div className="card p-6 sm:p-10 text-center animate-fade">
<AlertCircle size={24} className="mx-auto text-danger mb-3" />
<p className="text-sm text-ink2 mb-1">Could not load channel profiles.</p>
<p className="text-xs text-muted mb-5 break-words">{listError}</p>
<button onClick={() => loadList()} className="btn-ghost px-5 py-2.5 text-sm">retry</button>
</div>
);
}
if (mode === 'idle' && channels.length === 0) {
return (
<div className="card p-6 sm:p-10 text-center animate-fade">
<div className="w-12 h-12 mx-auto mb-4 rounded-input bg-paper3 flex items-center justify-center">
<Radio size={22} className="text-brass" />
</div>
<h2 className="font-display lowercase text-xl text-ink mb-2">no channel profiles yet</h2>
<p className="text-sm text-muted leading-relaxed max-w-md mx-auto mb-6">
A profile is one channel&apos;s packaging rules — how its titles are shaped,
which hooks land, and how thumbnails are art-directed. Start from scratch,
or import a JSON bundle.
</p>
<div className="flex flex-wrap items-center justify-center gap-3">
<button onClick={startNew} className="btn-primary px-5 py-2.5 text-sm">
<Plus size={15} /> new profile
</button>
<button onClick={() => fileInputRef.current?.click()} className="btn-ghost px-5 py-2.5 text-sm">
<Upload size={15} /> import json
</button>
</div>
</div>
);
}
if (loadingProfile) return <EditorSkeleton />;
if (mode === 'idle') {
return (
<div className="card p-6 sm:p-10 text-center animate-fade">
<p className="text-sm text-muted mb-5">Select a profile to edit, or start a new one.</p>
<button onClick={startNew} className="btn-ghost px-5 py-2.5 text-sm">
<Plus size={15} /> new profile
</button>
</div>
);
}
return (
<form onSubmit={handleSave} className="card p-4 sm:p-6 animate-fade">
{/* Editor head: which profile, and the save action. */}
<div className="flex flex-wrap items-start justify-between gap-3 mb-2">
<div className="min-w-0">
<p className="eyebrow mb-1">{isNew ? 'new profile' : 'editing profile'}</p>
<h2 className="font-display lowercase text-2xl text-ink truncate">
{form.name || form.slug || 'untitled'}
</h2>
{!isNew && <p className="readout mt-1.5">{selectedSlug}</p>}
</div>
{!isNew && (
<button
type="button"
onClick={() => handleExport(selectedSlug)}
disabled={exporting}
className="btn-quiet px-3 py-1.5 text-xs shrink-0"
title="Export this profile"
>
{exporting ? <Loader2 size={13} className="animate-spin" /> : <Download size={13} />}
export
</button>
)}
</div>
{/* 01 · identity */}
<Section n="01" title="identity">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<Field
label="slug"
hint={isNew
? 'Letters, numbers, dashes, underscores. Becomes the profile id and cannot change later.'
: 'The profile id. Locked after creation.'}
>
<input
value={isNew ? form.slug : (selectedSlug || '')}
onChange={isNew ? (e) => setField('slug', e.target.value) : undefined}
readOnly={!isNew}
placeholder="my-channel"
spellCheck={false}
autoComplete="off"
className={`input-field font-mono ${!isNew ? 'opacity-60 cursor-not-allowed' : ''}`}
/>
</Field>
<Field label="name" hint="Display name in the picker. Falls back to the slug when empty.">
<input
value={form.name}
onChange={(e) => setField('name', e.target.value)}
placeholder="Channel name"
className="input-field"
/>
</Field>
<Field label="language">
<input
value={form.language}
onChange={(e) => setField('language', e.target.value)}
placeholder="en"
className="input-field"
/>
</Field>
<Field label="tone" hint="A short line the model reads as voice guidance.">
<input
value={form.tone}
onChange={(e) => setField('tone', e.target.value)}
placeholder="calm, curious, never hype"
className="input-field"
/>
</Field>
</div>
</Section>
{/* 02 · title rules */}
<Section n="02" title="title rules">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<Field label="max characters">
<input
type="number" min="0"
value={form.title_rules.max_chars}
onChange={(e) => setTitleRule('max_chars', e.target.value)}
className="input-field"
/>
</Field>
<Field label="mobile characters" hint="Where a title truncates on a phone.">
<input
type="number" min="0"
value={form.title_rules.mobile_chars}
onChange={(e) => setTitleRule('mobile_chars', e.target.value)}
className="input-field"
/>
</Field>
<Field label="keyword position">
<select
value={form.title_rules.keyword_position}
onChange={(e) => setTitleRule('keyword_position', e.target.value)}
className="input-field [color-scheme:dark]"
>
{KEYWORD_POSITIONS.map((v) => <option key={v} value={v}>{v}</option>)}
</select>
</Field>
<Field label="number policy">
<select
value={form.title_rules.number_policy}
onChange={(e) => setTitleRule('number_policy', e.target.value)}
className="input-field [color-scheme:dark]"
>
{NUMBER_POLICIES.map((v) => <option key={v} value={v}>{v}</option>)}
</select>
</Field>
<Field label="required signal">
<select
value={form.title_rules.required_signal}
onChange={(e) => setTitleRule('required_signal', e.target.value)}
className="input-field [color-scheme:dark]"
>
{REQUIRED_SIGNALS.map((v) => <option key={v} value={v}>{v}</option>)}
</select>
</Field>
</div>
<div className="grid grid-cols-1 gap-4 mt-4">
<Field label="banned patterns" hint="Enter to add. Substrings a title must not contain.">
<TagInput
values={form.title_rules.banned_patterns}
onChange={(v) => setTitleRule('banned_patterns', v)}
placeholder="in this video"
/>
</Field>
<Field label="banned openers" hint="Enter to add. Words a title may not start with.">
<TagInput
values={form.title_rules.banned_openers}
onChange={(v) => setTitleRule('banned_openers', v)}
placeholder="Explaining"
/>
</Field>
</div>
</Section>
{/* 03 · hooks & description */}
<Section n="03" title="hooks & description">
<div className="grid grid-cols-1 gap-4">
<Field label="hook patterns" hint="Enter to add. Shapes the opening line can take.">
<TagInput
values={form.hook_patterns}
onChange={(v) => setField('hook_patterns', v)}
placeholder="the bug that survived three rewrites"
/>
</Field>
<Field label="hook style" hint="How the hook should land visually and in one line.">
<input
value={form.hook_style}
onChange={(e) => setField('hook_style', e.target.value)}
placeholder="show the working demo first, then state the stake"
className="input-field"
/>
</Field>
<Field label="description template" hint="{hook} and {link} are filled in at publish time.">
<textarea
rows={5}
value={form.description_template}
onChange={(e) => setField('description_template', e.target.value)}
placeholder={'{hook}\n\nFull video: {link}'}
className="input-field resize-y leading-relaxed font-mono text-xs"
/>
</Field>
</div>
</Section>
{/* 04 · links */}
<Section n="04" title="links">
<Field label="links" hint="Enter to add. URLs appended to the description.">
<TagInput
values={form.links}
onChange={(v) => setField('links', v)}
placeholder="https://"
/>
</Field>
</Section>
{/* 05 · thumbnail */}
<Section n="05" title="thumbnail">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
<Field label="role order" hint="The first role drives the primary concept.">
<RoleOrderField
value={form.thumbnail.role_order}
onMove={moveRole}
onToggle={toggleRole}
/>
</Field>
<div className="space-y-4">
<Field label="palette" hint="Enter to add. Colours the thumbnail direction leans on.">
<TagInput
values={form.thumbnail.palette}
onChange={(v) => setThumbnail('palette', v)}
placeholder="mossy green"
/>
</Field>
<Toggle
checked={form.thumbnail.presenter_photo}
onChange={(v) => setThumbnail('presenter_photo', v)}
label="include presenter photo"
hint="Reserve a role for the host's face."
/>
</div>
</div>
</Section>
{/* 06 · publishing */}
<Section n="06" title="publishing">
<Field
label="default postiz integration id"
hint="Optional. Pre-selects a connected channel when posting."
>
<input
value={form.default_postiz_integration_id}
onChange={(e) => setField('default_postiz_integration_id', e.target.value)}
placeholder="e.g. tiktok-business"
className="input-field font-mono"
/>
</Field>
</Section>
{/* 07 · history (read-only) */}
<Section n="07" title="history">
<details className="group rounded-input border border-rule bg-paper">
<summary className="flex items-center justify-between gap-2 px-3 py-2.5 cursor-pointer list-none [&::-webkit-details-marker]:hidden">
<span className="flex items-center gap-2 text-sm lowercase text-ink2">
<ChevronDown size={14} className="transition-transform group-open:rotate-180" />
published video history
</span>
<span className="readout shrink-0">
{form.published_video_history.length} · read-only
</span>
</summary>
<div className="border-t border-rule px-3 py-3">
<pre className="text-[11px] leading-relaxed font-mono text-muted overflow-x-auto custom-scrollbar">
{JSON.stringify(form.published_video_history, null, 2)}
</pre>
<p className="text-xs text-muted mt-2 leading-relaxed">
Kept exactly as loaded and written back on save.
</p>
</div>
</details>
</Section>
{/* Footer: status, delete, save. */}
<div className="mt-6 pt-5 border-t border-rule flex flex-col sm:flex-row sm:items-center gap-3">
<div className="flex-1 min-w-0">
{saveError ? (
<p className="text-sm text-danger leading-relaxed break-words" role="alert">{saveError}</p>
) : saved ? (
<span className="badge-ok"><Check size={12} /> saved</span>
) : (
<span className="readout hidden sm:inline">
{isNew ? 'unsaved profile' : 'edits apply when you save'}
</span>
)}
</div>
<div className="flex items-center gap-2 shrink-0">
{!isNew && (
confirmDelete ? (
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => setConfirmDelete(false)}
className="btn-quiet px-3 py-2 text-xs"
>
cancel
</button>
<button
type="button"
onClick={handleDelete}
disabled={deleting}
className="btn-danger px-3 py-2 text-xs"
>
{deleting ? 'deleting…' : 'delete for good'}
</button>
</div>
) : (
<button
type="button"
onClick={() => setConfirmDelete(true)}
className="btn-danger px-3 py-2 text-xs"
>
<Trash2 size={13} /> delete
</button>
)
)}
<button type="submit" disabled={saving} className="btn-primary px-5 py-2.5 text-sm">
{saving
? <><Loader2 size={14} className="animate-spin" /> saving…</>
: <><Save size={14} /> save profile</>}
</button>
</div>
</div>
</form>
);
};
return (
<div className="h-full overflow-y-auto custom-scrollbar p-4 sm:p-8 animate-fade">
<div className="max-w-6xl mx-auto">
<header className="mb-6 sm:mb-8">
<p className="eyebrow mb-1.5">03 · CHANNELS</p>
<h1 className="font-display lowercase text-2xl text-ink">Channel Profiles</h1>
<p className="text-sm text-muted mt-2 max-w-2xl leading-relaxed">
Per-channel packaging rules for the generator: how titles are shaped, which
hooks land, and how thumbnails are directed.
</p>
</header>
<div className="flex flex-col lg:flex-row gap-6">
{/* Rail: the profile drawer and the transfer controls. */}
<aside className="lg:w-80 shrink-0 lg:sticky lg:top-8 lg:self-start lg:max-h-[calc(100dvh-4rem)] lg:overflow-y-auto custom-scrollbar space-y-4">
<div className="card p-3">
<div className="flex items-center justify-between gap-2 px-1 pb-3 border-b border-rule">
<span className="eyebrow">
{channels.length} {channels.length === 1 ? 'profile' : 'profiles'}
</span>
<button onClick={startNew} className="btn-quiet px-3 py-1.5 text-xs">
<Plus size={13} /> new
</button>
</div>
<nav
className="mt-1.5 space-y-0.5 max-h-[42vh] lg:max-h-[50vh] overflow-y-auto custom-scrollbar"
aria-label="channel profiles"
>
{channels.length === 0 ? (
<p className="px-3 py-6 text-xs text-muted text-center leading-relaxed">
{listState === 'loading' ? 'loading…' : 'no profiles yet'}
</p>
) : channels.map((ch, i) => {
const active = mode === 'edit' && selectedSlug === ch.slug;
return (
<button
key={ch.slug}
onClick={() => openProfile(ch.slug)}
aria-current={active ? 'true' : undefined}
className={`relative w-full flex items-center gap-3 pl-3 pr-2.5 py-2.5 rounded-input text-left transition-colors ${active
? 'bg-paper3 text-ink'
: 'text-muted hover:text-ink2 hover:bg-paper3/50'}`}
>
{active && (
<span className="absolute left-0 top-1.5 bottom-1.5 w-0.5 bg-brass rounded-full" aria-hidden="true" />
)}
<span className="readout w-5 shrink-0 text-center">
{String(i + 1).padStart(2, '0')}
</span>
<span className="min-w-0 flex-1">
<span className={`block truncate text-sm lowercase ${active ? 'text-ink' : 'text-ink2'}`}>
{ch.name || ch.slug}
</span>
<span className="block readout truncate">{ch.slug}</span>
</span>
</button>
);
})}
</nav>
</div>
{/* Import / export. The file input lives here once and both
the empty state and the transfer card trigger it. */}
<div className="card p-4">
<p className="eyebrow mb-3">import / export</p>
<div className="space-y-2">
<button
onClick={() => fileInputRef.current?.click()}
disabled={importing}
className="btn-ghost w-full px-4 py-2.5 text-sm justify-start"
>
{importing
? <><Loader2 size={14} className="animate-spin" /> importing…</>
: <><Upload size={14} /> import json…</>}
</button>
<button
onClick={() => handleExport()}
disabled={exporting}
className="btn-ghost w-full px-4 py-2.5 text-sm justify-start"
>
{exporting
? <><Loader2 size={14} className="animate-spin" /> exporting…</>
: <><Download size={14} /> export all</>}
</button>
</div>
<input
ref={fileInputRef}
type="file"
accept=".json,application/json"
onChange={handleImportFile}
className="hidden"
/>
{importError && (
<p className="text-xs text-danger mt-3 leading-relaxed break-words">{importError}</p>
)}
{exportError && (
<p className="text-xs text-danger mt-3 leading-relaxed break-words">{exportError}</p>
)}
{importResult && (
<div className="mt-3 rounded-input border border-rule bg-paper p-3">
<p className="text-xs text-ink2 flex items-center gap-1.5">
<Check size={12} className="text-ok shrink-0" />
imported {importResult.imported} {importResult.imported === 1 ? 'profile' : 'profiles'}
</p>
{importResult.failed.length > 0 && (
<ul className="mt-2 space-y-1">
{importResult.failed.map((f, i) => (
<li key={`${f.slug || 'item'}-${i}`} className="text-xs text-danger leading-relaxed break-words">
<span className="font-mono">{f.slug || '—'}</span> · {f.error}
</li>
))}
</ul>
)}
</div>
)}
<p className="text-xs text-muted mt-3 leading-relaxed">
Import accepts an export bundle, a list of profiles, or a single profile.
A single file may omit its slug — it is derived from the file name.
</p>
</div>
</aside>
{/* Editor / states. */}
<section className="flex-1 min-w-0">
{editor()}
</section>
</div>
</div>
</div>
);
}