Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

25.8 KB
Raw Blame
// Tab "Edit video của bạn" = màn TẠO MỚI 3 bước: Clip → Cách dựng (lưới thẻ dọc) → Dựng (tiến độ, xong mở Studio).
// Bước 1 có luôn danh sách các bản đã dựng (bấm → Studio #/edit/<id>). Cột trái: clip, nhạc nền, độ dài, tên riêng, dặn thêm.
// API: GET /api/edit-options, GET/POST /api/edit-setup, GET/POST /api/edits, GET/DELETE /api/edits/:id (edit/http.mjs).
// Chữ từ server / gói (tên cách dựng, tên file) chỉ vào DOM qua textContent (luật P2, L9).
import { $, $$, el, t, I, fmtMB, fmtDur, safeUrl, store as ls } from './util.js';

const S = { opts: null, style: null, video: null, videoDur: null, music: null, musicSel: 'style', names: [], target: null, step: 1, uploading: false, list: null, noServer: false, job: null, timer: null };
const HEX = /^#[0-9A-Fa-f]{6}$/;
const SRC = ['builtin', 'local', 'pack'];
const srcOf = (s) => (SRC.includes(s?.source) ? s.source : 'builtin');
const styleName = (s) => (I.lang === 'en' && s.nameEn ? s.nameEn : s.name);
const styleSummary = (s) => (I.lang === 'en' && s.summaryEn ? s.summaryEn : s.summary);
const styleById = (id) => (S.opts?.styles || []).find((s) => s.id === id);
const stLabel = (s) => (['queued', 'running', 'done', 'error'].includes(s) ? t('ed.st.' + s) : s);

// ---- tab Dựng từ mẫu / Edit video của bạn ----
const tabs = $$('.tab');
function show(which) {
  tabs.forEach((x) => x.setAttribute('aria-selected', String(x.dataset.tab === which)));
  $('main.layout').hidden = which !== 'tpl';
  $('#editTab').hidden = which !== 'edit';
  try { localStorage.setItem('lumreels.tab', which); } catch { /* bỏ qua */ }
  if (which === 'edit' && !S.opts && !S.noServer) init();
  if (which === 'edit' && location.hash !== '#edit' && !/^#\/edit\//.test(location.hash)) history.replaceState(null, '', '#edit');
  if (which === 'tpl' && location.hash === '#edit') history.replaceState(null, '', location.pathname + location.search);
}
tabs.forEach((x) => x.addEventListener('click', () => show(x.dataset.tab)));
document.addEventListener('keydown', (e) => {
  if (!e.target.closest?.('.tabs') || !['ArrowLeft', 'ArrowRight'].includes(e.key)) return;
  const list = [...tabs]; const i = list.indexOf(document.activeElement);
  const n = list[(i + (e.key === 'ArrowRight' ? 1 : list.length - 1)) % list.length]; n.focus(); n.click();
});
window.addEventListener('hashchange', () => { if (location.hash === '#edit') show('edit'); });
// đóng Studio → về màn tạo mới, tải lại danh sách (có thể vừa xuất bản mới)
window.addEventListener('lumreels:studio', (e) => { if (!e.detail.open && !/^#reel\//.test(location.hash)) { show('edit'); if (S.opts) loadList(); } });

// ---- nạp ----
async function init() {
  try { S.opts = await fetch('/api/edit-options').then((r) => r.json()); } catch { S.noServer = true; $('#edSetup').hidden = false; $('#edSetupText').textContent = t('ed.noServer'); return; }
  const o = S.opts;
  if (!o.ready) {
    $('#edSetup').hidden = false; $('#edSetupText').textContent = t('ed.setupText'); $('#edSetupCmd').textContent = o.setup;
    fetch('/api/edit-setup').then((r) => r.json()).then((st) => { if (st.running) watchInstall(); }).catch(() => {});
  } else $('#edSetup').hidden = true;
  S.style = ls.get('lumreels.cr.style') || o.styles[0]?.id || null;
  if (!styleById(S.style)) S.style = o.styles[0]?.id || null;
  renderStyles(); renderMusic(); renderNames(); renderLen(); renderRatio(); renderClip(); setStep(1); loadList();
}

// ---- bước ----
function setStep(n) {
  if (n === 2 && !S.video) n = 1;
  S.step = n;
  $$('.cr-pane').forEach((p) => { p.hidden = Number(p.dataset.pane) !== n; });
  $$('#crSteps li[data-step]').forEach((li) => {
    const k = Number(li.dataset.step);
    li.className = k < n || (k === 1 && S.video && n !== 1) ? 'done' : k === n ? 'on' : '';
    const b = li.querySelector('button');
    b.disabled = (k === 2 && !S.video) || (k === 3 && !S.job);
    if (k === n) b.setAttribute('aria-current', 'step'); else b.removeAttribute('aria-current');
    b.querySelector('.n').textContent = li.className === 'done' && k !== n ? '✓' : String(k);
  });
  $('#crBack').hidden = n === 1;
  $('#editTab').dataset.step = String(n);
  refreshFoot();
}
$('#crSteps').addEventListener('click', (e) => { const li = e.target.closest('li[data-step]'); if (li && !li.querySelector('button').disabled) setStep(Number(li.dataset.step)); });
$('#crBack').addEventListener('click', () => setStep(Math.max(1, S.step - 1)));

// ---- lưới cách dựng ----
function styleCard(s) {
  const on = s.id === S.style;
  const b = el('button', 'sty' + (on ? ' on' : ''), null, { type: 'button', role: 'radio', 'aria-checked': String(on), 'data-id': s.id });
  b.tabIndex = on ? 0 : -1;
  b.setAttribute('aria-label', t('ed.styleAria', { name: styleName(s), summary: styleSummary(s) }) + ' · ' + t('src.' + srcOf(s)));
  const pic = el('span', 'pic');
  const thumb = safeUrl(s.thumb);
  if (thumb) { const img = el('img', null, null, { alt: '', loading: 'lazy', decoding: 'async', width: '360', height: '640' }); img.src = thumb; pic.append(img); }
  else { const ph = el('span', 'ph', styleName(s)); ph.style.setProperty('--sty-acc', HEX.test(String(s.accent || '')) ? s.accent : '#FF6B2C'); pic.append(ph); }
  if (srcOf(s) !== 'builtin') pic.append(el('span', 'src src-' + srcOf(s), t('src.' + srcOf(s))));
  b.append(pic, el('span', 'n', styleName(s)));
  return b;
}
function renderStyles() {
  const list = S.opts?.styles || [];
  $('#edStyles').replaceChildren(...list.map(styleCard));
  renderStyleDesc();
}
function renderStyleDesc() { const s = styleById(S.style); $('#edStyleDesc').textContent = s ? styleSummary(s) : ''; }
function pickStyle(b, focus) {
  S.style = b.dataset.id; ls.set('lumreels.cr.style', S.style);
  $$('#edStyles .sty').forEach((x) => { const on = x === b; x.setAttribute('aria-checked', String(on)); x.classList.toggle('on', on); x.tabIndex = on ? 0 : -1; });
  renderStyleDesc(); refreshFoot();
  const s = styleById(S.style); if (s?.target && S.target == null) renderLen();
  if (focus) { b.focus(); b.scrollIntoView({ block: 'nearest' }); }
}
$('#edStyles').addEventListener('click', (e) => { const b = e.target.closest('.sty'); if (b) pickStyle(b); });
$('#edStyles').addEventListener('dblclick', (e) => { if (e.target.closest('.sty') && !$('#edGo').disabled) $('#edGo').click(); });
$('#edStyles').addEventListener('keydown', (e) => {
  const list = $$('#edStyles .sty'); const i = list.indexOf(document.activeElement); if (i < 0) return;
  const cols = Math.max(1, getComputedStyle($('#edStyles')).gridTemplateColumns.split(' ').length);
  const step = { ArrowDown: cols, ArrowRight: 1, ArrowUp: -cols, ArrowLeft: -1 }[e.key];
  if (step) { e.preventDefault(); pickStyle(list[(i + step + list.length) % list.length], true); }
  else if (e.key === 'Home' || e.key === 'End') { e.preventDefault(); pickStyle(e.key === 'Home' ? list[0] : list[list.length - 1], true); }
});
window.addEventListener('lumreels:packs', async () => {
  if (!S.opts) return;
  try {
    const o = await fetch('/api/edit-options').then((r) => r.json());
    S.opts = { ...S.opts, styles: o.styles };
    if (!styleById(S.style)) S.style = o.styles[0]?.id || null;
    renderStyles(); refreshFoot();
  } catch { /* bỏ qua */ }
});

// ---- nhạc nền: chip ----
function renderMusic() {
  const box = $('#crMusic');
  const chips = [['style', t('cr.musicStyle')], ...(S.opts?.music || []).map((m) => [m.id, m.id.charAt(0).toUpperCase() + m.id.slice(1), I.srv(m.desc)]), ['none', t('ed.noMusic')]];
  const kids = chips.map(([v, label, title]) => {
    const on = S.musicSel === v;
    const b = el('button', 'chip' + (on ? ' on' : ''), label, { type: 'button', role: 'radio', 'aria-checked': String(on), 'data-v': v });
    if (title) b.title = title;
    return b;
  });
  const up = el('button', 'chip add' + (S.musicSel === 'file' ? ' on' : ''), S.music ? S.music.name : t('cr.musicUpload'), { type: 'button', role: 'radio', 'aria-checked': String(S.musicSel === 'file'), 'data-v': 'file' });
  kids.push(up);
  box.replaceChildren(...kids);
  $('#edMusicName').textContent = S.music && S.musicSel === 'file' ? fmtMB(S.music.size) : '';
}
$('#crMusic').addEventListener('click', (e) => {
  const b = e.target.closest('.chip'); if (!b) return;
  if (b.dataset.v === 'file') { $('#edMusicFile').click(); return; }
  S.musicSel = b.dataset.v; renderMusic(); refreshFoot();
});
$('#edMusicFile').addEventListener('change', (e) => { const f = e.target.files[0]; e.target.value = ''; if (!f) return; S.music = f; S.musicSel = 'file'; renderMusic(); refreshFoot(); });

// ---- khung hình (tỉ lệ bản ra): 9:16 · 16:9 · 4:3 · 3:4 — clip ngang + 16:9 thì giữ nguyên khung, không cắt ----
const RATIO_DIMS = { '9:16': [1080, 1920], '16:9': [1920, 1080], '4:3': [1440, 1080], '3:4': [1080, 1440] };
S.ratio = RATIO_DIMS[ls.get('lumreels.cr.ratio')] ? ls.get('lumreels.cr.ratio') : '9:16';
function renderRatio(focus) {
  $$('#crRatio .ratio').forEach((b) => { const on = b.dataset.ratio === S.ratio; b.classList.toggle('on', on); b.setAttribute('aria-checked', String(on)); b.tabIndex = on ? 0 : -1; if (on && focus) b.focus(); });
  const [w, h] = RATIO_DIMS[S.ratio];
  $('#crRatioSize').textContent = `${w}×${h}`;
  // clip đã chọn: báo trước có cắt khung hay giữ nguyên
  const v = $('#crClipVid'); const vw = v?.videoWidth; const vh = v?.videoHeight;
  const same = S.video && vw && vh && Math.abs(vw / vh - w / h) < 0.02 * (w / h);
  $('#crRatioHint').textContent = same ? t('cr.ratioSame') : t('cr.ratioHint.' + S.ratio.replace(':', 'x'));
  refreshFoot();
}
function setRatio(r, focus) { if (!RATIO_DIMS[r]) return; S.ratio = r; ls.set('lumreels.cr.ratio', r); renderRatio(focus); }
$('#crRatio').addEventListener('click', (e) => { const b = e.target.closest('.ratio'); if (b) setRatio(b.dataset.ratio); });
$('#crRatio').addEventListener('keydown', (e) => {
  const d = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[e.key]; if (!d) return;
  e.preventDefault(); const ids = Object.keys(RATIO_DIMS); setRatio(ids[(ids.indexOf(S.ratio) + d + ids.length) % ids.length], true);
});

// ---- độ dài bản ra ----
function renderLen() {
  const r = $('#crLen'); const auto = S.target == null;
  const s = styleById(S.style);
  if (auto) r.value = String(s?.target || 40);
  $('#crLenAuto').textContent = t(auto ? 'cr.lenAutoOn' : 'cr.lenAuto');
  $('#crLenV').textContent = auto ? t('cr.lenAutoV') : t('cr.lenV', { s: r.value });
  r.closest('.cr-range').classList.toggle('auto', auto);
  const pct = ((Number(r.value) - 15) / (180 - 15)) * 100;
  r.style.setProperty('--p', pct + '%');
  refreshFoot();
}
$('#crLen').addEventListener('input', () => { S.target = Number($('#crLen').value); renderLen(); });
$('#crLenAuto').addEventListener('click', () => { S.target = S.target == null ? Number($('#crLen').value) : null; renderLen(); });

// ---- tên riêng: chip + Thêm ----
function renderNames() {
  const box = $('#crNames');
  const kids = S.names.map((n, i) => {
    const b = el('button', 'chip', null, { type: 'button', 'data-i': String(i), 'aria-label': t('cr.removeName', { n }) });
    b.append(el('span', null, n), el('span', 'x', '×', { 'aria-hidden': 'true' }));
    return b;
  });
  const add = el('button', 'chip add', '+ ' + t('cr.addName'), { type: 'button', 'data-add': '1' });
  kids.push(add);
  box.replaceChildren(...kids);
}
$('#crNames').addEventListener('click', (e) => {
  const b = e.target.closest('.chip'); if (!b) return;
  if (b.dataset.add) { const i = $('#edNames'); i.hidden = false; i.focus(); return; }
  S.names.splice(Number(b.dataset.i), 1); saveNames(); renderNames();
});
function addNames(v) {
  for (const n of String(v).split(/[,;\n]/).map((x) => x.trim()).filter(Boolean)) if (!S.names.includes(n) && S.names.length < 40) S.names.push(n.slice(0, 60));
  saveNames(); renderNames();
}
const saveNames = () => ls.set('lumreels.cr.names', S.names);
$('#edNames').addEventListener('keydown', (e) => {
  if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); addNames(e.target.value); e.target.value = ''; }
  else if (e.key === 'Escape') { e.target.value = ''; e.target.hidden = true; }
});
$('#edNames').addEventListener('blur', (e) => { if (e.target.value.trim()) addNames(e.target.value); e.target.value = ''; e.target.hidden = true; });
S.names = (ls.get('lumreels.cr.names', []) || []).filter((x) => typeof x === 'string').slice(0, 40);

// ---- clip ----
const drop = $('#edDrop');
function pickVideo(f) {
  if (!f) return;
  if (!/^video\//.test(f.type) && !/\.(mp4|mov|m4v|mkv|webm|avi|3gp)$/i.test(f.name)) { setErr(t('ed.notVideo')); return; }
  if (S.opts && f.size > S.opts.maxUploadBytes) { setErr(t('ed.tooBig', { size: fmtMB(f.size) })); return; }
  S.video = f; S.videoDur = null; setErr('');
  renderClip(); setStep(2);
}
function renderClip() {
  const f = S.video;
  $('#crClip').hidden = !f; $('#crClipNone').hidden = !!f; $('#crChange').hidden = !f;
  drop.classList.toggle('has', !!f);
  $('.big', drop).textContent = f ? f.name : t('ed.dropBig');
  $('.small', drop).textContent = f ? t('ed.changeFile', { size: fmtMB(f.size) }) : t('ed.dropSmall');
  if (!f) return;
  $('#crClipName').textContent = f.name;
  $('#crClipInfo').textContent = fmtMB(f.size) + (S.videoDur ? ` · ${fmtDur(S.videoDur)}` : '');
  const v = $('#crClipVid');
  if (v.dataset.name !== f.name + f.size) {
    if (v.src) URL.revokeObjectURL(v.src);
    v.dataset.name = f.name + f.size; v.src = URL.createObjectURL(f);
    v.onloadedmetadata = () => { S.videoDur = v.duration; v.currentTime = Math.min(v.duration / 3, 20); $('#crClipDur').textContent = fmtDur(v.duration); renderClip(); refreshFoot(); if (S.opts) renderRatio(); };
  }
}
drop.addEventListener('click', () => $('#edVideo').click());
drop.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); $('#edVideo').click(); } });
$('#edVideo').addEventListener('change', (e) => { pickVideo(e.target.files[0]); e.target.value = ''; });
$('#crChange').addEventListener('click', () => $('#edVideo').click());
['dragenter', 'dragover'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add('over'); }));
['dragleave', 'drop'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.remove('over'); }));
drop.addEventListener('drop', (e) => pickVideo(e.dataTransfer.files[0]));
const setErr = (x) => { $('#edErr').textContent = x; };

// ---- chân trang: tóm tắt + nút chính ----
function refreshFoot() {
  const sum = [];
  const s = styleById(S.style);
  if (S.video) sum.push(el('span', 'pill', S.video.name));
  if (s && S.step >= 2) sum.push(el('span', 'pill acc', styleName(s)));
  if (S.step >= 2) {
    sum.push(el('span', 'pill', S.musicSel === 'style' ? t('cr.musicStyle') : S.musicSel === 'none' ? t('ed.noMusic') : S.musicSel === 'file' ? (S.music?.name || '') : S.musicSel));
    sum.push(el('span', 'pill', S.target == null ? t('cr.lenAutoV') : t('cr.lenV', { s: S.target })));
    sum.push(el('span', 'pill mono', S.ratio));
  }
  $('#crSum').replaceChildren(...sum);
  const go = $('#edGo'); const lab = $('#edGo span');
  const ready = !!(S.opts?.ready && S.video && S.style) && !S.uploading;
  $('#crEta').textContent = S.step === 2 && S.videoDur ? t('cr.eta', { m: Math.max(2, Math.round(2 + (S.videoDur / 60) * 0.7)) }) : '';
  if (S.step === 1) { go.disabled = !S.video; if (!S.uploading) lab.textContent = t('cr.next'); }
  else if (S.step === 2) { go.disabled = !ready; if (!S.uploading) lab.textContent = t('ed.go'); }
  else { go.disabled = true; if (!S.uploading) lab.textContent = t('ed.go'); }
  $('.cr-foot').hidden = S.step === 3 && !S.uploading;
}
$('#edGo').addEventListener('click', () => {
  if (S.step === 1) { setStep(2); return; }
  if (S.step !== 2) return;
  if (S.musicSel === 'file' && !S.music) { setErr(t('ed.needMusic')); return; }
  const fd = new FormData();
  fd.append('style', S.style);
  fd.append('ratio', S.ratio);
  fd.append('content', $('#edNotes').value.trim());
  fd.append('names', S.names.join(', '));
  fd.append('draft', $('#edDraft').checked ? '1' : '0');
  if (S.target != null) fd.append('target', String(S.target));
  if (S.musicSel === 'none') fd.append('musicStyle', 'none');
  else if (S.musicSel !== 'style' && S.musicSel !== 'file') fd.append('musicStyle', S.musicSel);
  if (S.musicSel === 'file' && S.music) fd.append('music', S.music, S.music.name);
  fd.append('video', S.video, S.video.name); // file sau cùng: trường chữ tới server trước
  S.uploading = true; setErr(''); refreshFoot();
  const lab = $('#edGo span');
  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/api/edits');
  xhr.upload.onprogress = (e) => { if (e.lengthComputable) lab.textContent = t('ed.uploading', { p: Math.round((e.loaded / e.total) * 100) }); };
  xhr.onload = () => {
    S.uploading = false; refreshFoot();
    let j = {}; try { j = JSON.parse(xhr.responseText); } catch { /* bỏ qua */ }
    if (xhr.status !== 202) { setErr(j.error ? I.srv(j.error) : t('err.status', { s: xhr.status })); return; }
    follow(j); loadList();
  };
  xhr.onerror = () => { S.uploading = false; refreshFoot(); setErr(t('ed.uploadCut')); };
  xhr.send(fd);
});

// ---- bước 3: tiến độ dựng ----
function follow(job) { S.job = job; setStep(3); paintBuild(job); poll(); }
async function poll() {
  clearTimeout(S.timer);
  const id = S.job?.id; if (!id) return;
  let v;
  try { v = await fetch(`/api/edits/${encodeURIComponent(id)}`).then((r) => r.json()); } catch { S.timer = setTimeout(poll, 3000); return; }
  if (S.job?.id !== id) return;
  S.job = v; paintBuild(v);
  if (['queued', 'running'].includes(v.status)) S.timer = setTimeout(poll, 1500);
  else { loadList(); if (v.status === 'done' && v.links?.out && S.step === 3 && !$('#editTab').hidden) setTimeout(() => { if (S.job?.id === id && S.step === 3) location.hash = `#/edit/${id}`; }, 900); }
}
function paintBuild(v) {
  const busy = ['queued', 'running'].includes(v.status);
  $('#crBuildName').textContent = v.sourceName || v.id;
  $('#crBuildSub').textContent = `${v.styleName || v.style || ''}`;
  const st = $('#crBuildStatus'); st.className = 'st ' + (v.status === 'done' ? 'done' : v.status === 'error' ? 'error' : 'run');
  st.textContent = v.status === 'queued' ? t('ed.waitTurn') : stLabel(v.status);
  const steps = v.steps || []; const i = Math.max(0, Math.min(steps.length - 1, v.stepIndex ?? 0));
  const p = v.status === 'done' ? 100 : busy ? Math.min(100, ((i + (v.pct || 0) / 100) / Math.max(1, steps.length)) * 100) : 0;
  $('#crBuildBar').style.transform = `scaleX(${p / 100})`;
  $('#crBuildStep').textContent = busy && steps.length && v.status !== 'queued' ? t('ed.stepOf', { i: i + 1, n: steps.length, step: I.srv(steps[i]), p: v.pct || 0 }) : '';
  $('#crBuildErr').textContent = v.status === 'error' ? I.srv(v.error || t('ed.err')) : '';
  const o = $('#crOpen'); o.hidden = !(v.status === 'done' && v.links?.out); o.href = `#/edit/${encodeURIComponent(v.id)}`;
  const lg = $('#crLog'); lg.dataset.logId = v.id; lg.classList.toggle('bad', v.status === 'error'); lg.textContent = t(v.status === 'error' ? 'log.btnErr' : 'log.btn');
  const th = $('#crBuildThumb'); const pv = safeUrl(v.links?.previewFinal || v.links?.preview);
  th.style.backgroundImage = pv ? `url("${pv}")` : '';
  th.style.aspectRatio = (RATIO_DIMS[v.ratio] ? v.ratio : '9:16').replace(':', ' / ');
}
$('#crAnother').addEventListener('click', () => { clearTimeout(S.timer); S.job = null; S.video = null; renderClip(); setStep(1); });

// ---- danh sách bản đã dựng ----
async function loadList() {
  let list = [];
  try { list = await fetch('/api/edits').then((r) => r.json()); } catch { return; }
  S.list = Array.isArray(list) ? list : [];
  renderList();
}
const viewStyleName = (v) => { const s = styleById(v.style); return s ? styleName(s) : v.styleName || v.style; };
function renderList() {
  const list = S.list || [];
  $('#crCount').textContent = list.length ? String(list.length) : '';
  $('#edList').replaceChildren(...(list.length ? list.map((v) => {
    const card = el('div', 'cr-item');
    const a = el('a', 'cr-open', null, { href: v.status === 'done' && v.links?.out ? `#/edit/${encodeURIComponent(v.id)}` : '#edit', 'data-id': v.id });
    const th = el('span', 'th', null, { 'aria-hidden': 'true' });
    const pv = safeUrl(v.links?.previewFinal || v.links?.preview);
    if (pv) th.style.backgroundImage = `url("${pv}")`;
    if (RATIO_DIMS[v.ratio] && v.ratio !== '9:16') { th.style.aspectRatio = v.ratio.replace(':', ' / '); th.append(el('span', 'rt mono', v.ratio)); }
    const dur = v.checks?.edl?.outSeconds;
    if (Number.isFinite(dur)) th.append(el('span', 'd mono', fmtDur(dur)));
    const meta = el('span', 'meta');
    meta.append(el('b', null, v.sourceName || v.id), el('span', 's', viewStyleName(v)));
    const foot = el('span', 'f');
    const busy = ['queued', 'running'].includes(v.status);
    foot.append(el('span', 'st ' + (v.status === 'done' ? 'done' : v.status === 'error' ? 'error' : 'run'), busy && v.action !== 'edit' ? t('st.publishing') : stLabel(v.status)));
    const nr = (v.revisions || []).length;
    if (nr) foot.append(el('span', 'v mono', `r${nr}`));
    meta.append(foot);
    a.append(th, meta);
    const del = el('button', 'cr-del', null, { type: 'button', 'aria-label': t('cr.delete', { name: v.sourceName || v.id }), 'data-id': v.id, title: t('ed.delete') });
    del.append(el('span', null, '×', { 'aria-hidden': 'true' }));
    del.disabled = busy;
    const bad = v.status === 'error' || !!v.reviseError;
    const lg = el('button', 'log-btn cr-log' + (bad ? ' bad' : ''), t(bad ? 'log.btnErr' : 'log.btn'), { type: 'button', 'data-log-kind': 'edit', 'data-log-id': v.id });
    card.append(a, del, lg);
    return card;
  }) : [el('p', 'cr-empty', t('ed.listEmpty'))]));
}
$('#edList').addEventListener('click', async (e) => {
  const d = e.target.closest('.cr-del');
  if (d) {
    if (!confirm(t('ed.confirmDel'))) return;
    const r = await fetch(`/api/edits/${encodeURIComponent(d.dataset.id)}`, { method: 'DELETE' });
    if (!r.ok) { const j = await r.json().catch(() => ({})); setErr(I.srv(j.error || t('err.status', { s: r.status }))); }
    loadList(); return;
  }
  const a = e.target.closest('.cr-open'); if (!a) return;
  const v = (S.list || []).find((x) => x.id === a.dataset.id);
  if (v && !(v.status === 'done' && v.links?.out)) { e.preventDefault(); follow(v); }
});

// ---- cài phần Edit video ----
const INSTALL_FAIL = new Set(['NEED_PYTHON', 'NEED_FFMPEG', 'NEED_NETWORK', 'NEED_NPM']);
let installTimer = null; let lastInstall = null;
function paintInstall(st) {
  lastInstall = st;
  const prog = $('#edInstallProg'); const step = $('#edInstallStep'); const btn = $('#edInstall');
  prog.hidden = false;
  const mm = (s) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
  step.className = 'ed-install-step';
  if (st.running) { step.textContent = t('ed.installStep', { step: st.step ? I.srv(st.step) : t('ed.installStepDefault'), t: mm(st.elapsedS || 0) }); btn.disabled = true; btn.textContent = t('ed.installing'); }
  else if (st.ok) { step.classList.add('ok'); step.textContent = t('ed.installDone', { t: mm(st.elapsedS || 0) }); }
  else { step.classList.add('bad'); step.textContent = INSTALL_FAIL.has(st.word) ? t('ed.fail.' + st.word) : t('ed.installFail'); btn.disabled = false; btn.textContent = t('ed.installRetry'); }
  prog.classList.toggle('stop', !st.running);
  $('#edInstallHint').hidden = !st.hint; $('#edInstallHint').textContent = st.hint || '';
  const log = $('#edInstallLog'); const atEnd = log.scrollTop + log.clientHeight >= log.scrollHeight - 8;
  log.textContent = (st.log || []).join('\n');
  if (atEnd) log.scrollTop = log.scrollHeight;
}
function watchInstall() {
  clearTimeout(installTimer);
  const tick = async () => {
    let st;
    try { st = await fetch('/api/edit-setup').then((r) => r.json()); } catch { installTimer = setTimeout(tick, 3000); return; }
    paintInstall(st);
    if (st.running) { installTimer = setTimeout(tick, 1500); return; }
    if (st.ok && st.ready) setTimeout(() => { S.opts = null; $('#edSetup').hidden = true; init(); }, 1200);
  };
  tick();
}
$('#edInstall').addEventListener('click', async () => {
  $('#edInstall').disabled = true;
  try {
    const r = await fetch('/api/edit-setup', { method: 'POST' });
    if (!r.ok && r.status !== 409) throw new Error((await r.json().catch(() => ({}))).error || 'HTTP ' + r.status);
    watchInstall();
  } catch (e) {
    $('#edInstall').disabled = false;
    $('#edInstallProg').hidden = false; $('#edInstallStep').className = 'ed-install-step bad';
    $('#edInstallStep').textContent = t('ed.installCantStart', { e: e.message });
  }
});

// ---- đổi VI/EN: vẽ lại phần JS sinh ----
window.addEventListener('lumreels:lang', () => {
  if (S.noServer) $('#edSetupText').textContent = t('ed.noServer');
  else if (S.opts && !S.opts.ready) $('#edSetupText').textContent = t('ed.setupText');
  if (lastInstall) paintInstall(lastInstall);
  if (S.opts) { const had = document.activeElement?.closest?.('#edStyles'); renderStyles(); renderMusic(); renderNames(); renderLen(); renderRatio(); if (had) $('#edStyles .sty[aria-checked="true"]')?.focus(); }
  renderClip(); refreshFoot();
  if (S.list) renderList();
  if (S.job && S.step === 3) paintBuild(S.job);
});
renderClip(); renderNames();

// mở lại tab đã chọn lần trước; #/edit/<id> (Studio) cũng thuộc tab Edit
let saved = 'tpl';
try { saved = localStorage.getItem('lumreels.tab') || 'tpl'; } catch { /* bỏ qua */ }
if (location.hash === '#edit' || /^#\/edit\//.test(location.hash)) saved = 'edit';
show(saved);