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.

36.2 KB
Raw Blame
// Studio: mở 1 bản edit toàn màn hình (#/edit/<id> hoặc #/edit/<id>/r<n>) — trình edit kiểu CapCut.
// Thanh trên (← tên · cách dựng · thời lượng, r0…rN, Undo/Redo, Cần xem lại, Xuất bản mới, Tải MP4) · cột icon trái ·
// player giữa (xem trước tức thì, không render) · bảng thuộc tính phải · timeline đáy.
// API: GET /api/edits/:id, GET /api/edits/:id/manual[?rev=], POST …/manual (bản vá), POST …/revise, POST …/music,
//      GET …/strip, GET …/wave (edit/http.mjs).
import { $, el, tx, icon, iconBtn, fmtT, fmtDur, plain, clamp, r2, t, I, getJSON, postJSON, safeUrl, ID_RE, store as ls, narrow, tokens, untokens } from './util.js';
import { Store } from './store.js';
import { Player } from './player.js';
import { Timeline } from './timeline.js';
import { Inspector } from './inspector.js';

const RAIL = [['cap', 'cap', 'st.trCap'], ['music', 'music', 'st.trMusic'], ['zoom', 'zoom', 'st.trZoom'], ['gfx', 'gfx', 'st.trGfx'], null, ['ai', 'ai', 'st.railAi']];
const busyOf = (v) => !!v && ['queued', 'running'].includes(v.status);

class Studio {
  constructor() {
    this.store = new Store();
    this.id = null; this.rev = null; this.job = null; this.sel = null; this.mode = 'cap'; this.edl = null;
    this.review = this.makeReview();
    this.build();
    this.store.on((what) => this.onStore(what));
    window.addEventListener('hashchange', () => this.route());
    window.addEventListener('lumreels:lang', () => { if (this.id) this.repaintAll(); });
    document.addEventListener('keydown', (e) => this.onKey(e), true);
    this.route();
  }

  // ---- khung ----
  build() {
    const R = el('div', 'studio', null, { id: 'studio', hidden: true, role: 'application', 'aria-roledescription': 'video editor' });
    // thanh trên
    const top = el('header', 'st-top');
    this.bBack = iconBtn('back', 'st.back', 'st-back');
    this.bBack.addEventListener('click', () => this.leave());
    const ttl = el('div', 'st-title');
    this.tName = el('b'); this.tSub = el('span');
    this.reelA = el('a', 'st-reel'); this.reelA.hidden = true;
    ttl.append(this.tName, this.tSub);
    this.vers = el('div', 'st-vers', null, { role: 'radiogroup' });
    this.vers.setAttribute('aria-label', t('st.versions')); this.vers.dataset.i18nAria = 'st.versions';
    const mid = el('div', 'st-mid');
    this.bUndo = iconBtn('undo', 'st.undo'); this.bRedo = iconBtn('redo', 'st.redo');
    this.bUndo.addEventListener('click', () => this.store.doUndo());
    this.bRedo.addEventListener('click', () => this.store.doRedo());
    mid.append(this.bUndo, this.bRedo);
    this.bReview = el('button', 'btn warn st-revb', null, { type: 'button' });
    this.bReview.addEventListener('click', () => this.setMode(this.mode === 'review' ? 'cap' : 'review', true));
    this.bReset = tx('button', 'btn ghost st-reset', 'man.reset', { type: 'button' });
    this.bReset.addEventListener('click', () => { if (confirm(t('st.resetAsk'))) this.store.reset(); });
    this.bPub = el('button', 'btn pri st-pub', null, { type: 'button' });
    this.bPub.addEventListener('click', () => this.publish());
    this.bLog = el('button', 'btn ghost st-log', null, { type: 'button', 'data-log-kind': 'edit', 'data-log-id': '' });
    this.aDl = el('a', 'btn st-dl', null, { download: '' });
    this.aDl.append(icon('dl'), tx('span', null, 'ed.mp4'));
    top.append(this.bBack, ttl, this.reelA, this.vers, mid, this.bReview, this.bReset, this.bLog, this.bPub, this.aDl);
    this.prog = el('div', 'st-prog', null, { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100' }); this.prog.append(el('i')); this.prog.hidden = true;
    // giữa
    const main = el('div', 'st-main');
    this.rail = el('nav', 'st-rail');
    this.rail.setAttribute('aria-label', t('st.tools')); this.rail.dataset.i18nAria = 'st.tools';
    this.railBtns = {};
    for (const r of RAIL) {
      if (!r) { this.rail.append(el('span', 'sep')); continue; }
      const [k, ic, key] = r;
      const b = el('button', null, null, { type: 'button', 'data-k': k, 'aria-pressed': 'false' });
      b.append(icon(ic), tx('span', 'l', key));
      if (k === 'cap') { this.capDot = el('span', 'dot'); b.append(this.capDot); }
      b.addEventListener('click', () => this.setMode(k, true));
      this.railBtns[k] = b; this.rail.append(b);
    }
    this.player = new Player({ store: this.store, onTime: (tt) => this.onTime(tt), onPlay: (p) => { this.timeline.follow = p; }, getSel: () => this.sel,
      onRatio: (r) => this.setRatio(r), busy: () => busyOf(this.job) || !!this.publishing });
    this.insp = new Inspector(this.ctx());
    main.append(this.rail, this.player.root, this.insp.root);
    this.timeline = new Timeline(this.ctx());
    // lớp chờ (đang dựng / đang xuất) + thông báo
    this.wait = el('div', 'st-wait', null, { role: 'status', 'aria-live': 'polite' }); this.wait.hidden = true;
    this.waitT = el('p'); this.waitBar = el('div', 'st-wbar'); this.waitBar.append(el('i'));
    this.wait.append(this.waitT, this.waitBar);
    this.toastEl = el('div', 'st-toast', null, { role: 'status', 'aria-live': 'polite' }); this.toastEl.hidden = true;
    this.scrim = el('div', 'st-scrim'); this.scrim.addEventListener('click', () => this.closeSheet());
    R.append(top, this.prog, main, this.timeline.root, this.wait, this.toastEl, this.scrim);
    document.body.append(R);
    this.R = R;
  }
  ctx() {
    const self = this;
    return {
      store: this.store,
      get player() { return self.player; },
      seek: (tt) => this.seek(tt),
      select: (s, o) => this.select(s, o),
      getSel: () => this.sel,
      mode: () => this.mode,
      focusKind: (k, quiet) => { this.vfocus = k === 'video'; if (k === 'video') this.timeline.setFocus('video'); else this.setMode(k, !quiet); },
      flagged: (u) => this.review.flagged(u),
      review: this.review,
      musicLabel: () => this.musicName(this.store.doc?.music.source),
      musicName: (s) => this.musicName(s),
      splitAtHead: (u) => this.splitAtHead(u),
      mergeSel: () => this.mergeSel(),
      deleteSel: () => this.deleteSel(),
      splitClip: () => this.splitClip(),
      onZoomAdd: () => this.addZoom(),
      addZoom: () => this.addZoom(),
      setGfxTime: (u, f, x) => this.setGfxTime(u, f, x),
      uploadMusic: (f) => this.uploadMusic(f),
      revise: (s) => this.revise(s),
      job: () => this.job,
      busy: () => busyOf(this.job) || !!this.publishing,
      closeSheet: () => this.closeSheet(),
      afterInline: () => this.insp.render(),
      onDrag: () => {},
    };
  }

  // ---- định tuyến ----
  route() {
    const m = /^#\/edit\/([\w-]{1,80})(?:\/r(\d{1,4}))?$/.exec(location.hash);
    if (!m) { if (this.id) this.close(); return; }
    const id = m[1]; const rev = m[2] != null ? Number(m[2]) : null;
    if (!ID_RE.test(id)) return;
    if (id === this.id && rev === this.rev && this.store.view) return;
    this.open(id, rev);
  }
  leave() { location.hash = '#edit'; }
  close() {
    this.player.release(); clearTimeout(this.pollT);
    this.id = null; this.rev = null; this.job = null; this.store.view = null; this.sel = null;
    this.R.hidden = true; document.body.classList.remove('studio-on');
    document.title = t('meta.title');
    window.dispatchEvent(new CustomEvent('lumreels:studio', { detail: { open: false } }));
  }
  async open(id, rev) {
    const same = id === this.id;
    this.id = id; this.rev = rev;
    this.R.hidden = false; document.body.classList.add('studio-on');
    if (!same) { this.zoomSet = false; this.sel = null; this.edl = null; this.player.release(); this.timeline.setStrip(null); this.timeline.setWave(null); this.review.reset(id); }
    try {
      this.job = await getJSON(`/api/edits/${encodeURIComponent(id)}`);
    } catch (e) { this.showWait(t('st.notFound', { e: I.srv(e.message) }), null); return; }
    if (this.id !== id) return;
    this.paintTop();
    if (busyOf(this.job)) { this.watchJob(); return; }
    if (!this.job.links?.out) { this.showWait(this.job.status === 'error' ? t('st.buildErr', { e: I.srv(this.job.error || '') }) : t('ed.mediaEmpty'), null); return; }
    await this.loadView();
  }
  async loadView() {
    const id = this.id; const rev = this.rev;
    let v;
    try { v = await getJSON(`/api/edits/${encodeURIComponent(id)}/manual${rev != null ? `?rev=${rev}` : ''}`); } catch (e) { this.showWait(t('man.loadErr', { e: I.srv(e.message) }), null); return; }
    if (this.id !== id || this.rev !== rev) return;
    this.hideWait();
    this.store.load(id, v);
    if (this.sel && !this.findSel(this.sel)) this.sel = null;
    this.player.setSources({ clean: safeUrl(v.media.clean), base: safeUrl(v.media.base), out: safeUrl(v.media.out), music: null });
    this.gfxKey = null; this.refreshGfx(true);
    if (!this.zoomSet) { this.timeline.openDefault(); this.zoomSet = true; }
    this.loadMedia(v);
    if (!v.readOnly) this.loadEdl();
    this.repaintAll();
    document.title = `${this.job.sourceName || id} · Studio`;
    window.dispatchEvent(new CustomEvent('lumreels:studio', { detail: { open: true, id } }));
  }
  async loadMedia(v) {
    const id = this.id;
    if (v.media.outName) getJSON(`/api/edits/${encodeURIComponent(id)}/strip?out=${encodeURIComponent(v.media.outName)}`).then((s) => { if (this.id === id) this.timeline.setStrip({ ...s, url: safeUrl(s.url) }); }).catch(() => {});
    this.loadWave(true);
  }
  /** Sóng + file nhạc cho nguồn đang chọn (đổi bài → tải sóng mới). */
  async loadWave(force) {
    const v = this.store.view; const src = this.store.doc?.music.source; const id = this.id;
    if (!v || !src || src === 'none') { this.timeline.setWave(null); this.player.setMusic(null); this.waveSrc = src; return; }
    if (!force && src === this.waveSrc) return;
    this.waveSrc = src;
    const q = v.readOnly && v.media.musicFile ? `file=${encodeURIComponent(v.media.musicFile)}` : `src=${encodeURIComponent(src)}`;
    try {
      const w = await getJSON(`/api/edits/${encodeURIComponent(id)}/wave?${q}`);
      if (this.id !== id || this.waveSrc !== src) return;
      this.timeline.setWave(w); this.player.setMusic(safeUrl(w.url));
    } catch { this.timeline.setWave(null); }
  }
  async loadEdl() {
    const url = safeUrl(this.job?.links?.edl); const id = this.id; if (!url) return;
    try { const e = await getJSON(url); if (this.id === id) { this.edl = e; this.review.build(); this.repaintAll(); } } catch { /* không có EDL: không có mục xem lại */ }
  }

  // ---- vẽ ----
  repaintAll() {
    if (!this.store.view) return;
    this.paintTop(); this.paintRail();
    this.timeline.setFocus(['cap', 'zoom', 'gfx', 'music'].includes(this.mode) ? this.mode : 'cap');
    this.timeline.layout();
    this.insp.render();
    this.player.tick();
  }
  paintTop() {
    const j = this.job; const v = this.store.view;
    const name = j?.sourceName || this.id || '';
    this.tName.textContent = name; this.tName.title = name;
    const style = j?.styleName || j?.style || '';
    this.tSub.textContent = [v?.keepAll ? t('st.fromReel') : style, v ? fmtDur(v.duration) : ''].filter(Boolean).join(' · ');
    // nguồn là reel (Sửa tiếp trong Studio): link quay về video đó ở tab Dựng từ mẫu
    const reel = v?.reel || j?.reel;
    this.reelA.hidden = !reel;
    if (reel) { this.reelA.textContent = t('st.reelLink', { title: reel.title || reel.id }); this.reelA.href = `#reel/${encodeURIComponent(reel.id)}`; this.reelA.title = t('st.reelBack'); }
    // phiên bản
    const vs = v?.versions || [];
    this.vers.replaceChildren(...vs.filter((x) => x.out).map((x) => {
      const on = x.n === v.rev;
      const b = el('button', on ? 'on' : '', x.n === 0 ? t('st.r0') : `r${x.n}`, { type: 'button', role: 'radio', 'aria-checked': String(on) });
      b.title = x.n === 0 ? t('st.r0Tip') : (x.manual ? t('man.tag') + ': ' : '') + (x.instruction || '');
      b.addEventListener('click', () => { if (!on) location.hash = x.n === v.latest ? `#/edit/${this.id}` : `#/edit/${this.id}/r${x.n}`; });
      return b;
    }));
    this.vers.hidden = vs.length < 2;
    const n = this.store.view ? this.store.changes : 0;
    const busy = busyOf(j) || !!this.publishing;
    this.bUndo.disabled = !this.store.undo.length || busy; this.bRedo.disabled = !this.store.redo.length || busy;
    const pend = this.review.pending();
    this.bReview.hidden = !v || v.readOnly || !this.review.items().length;
    this.bReview.replaceChildren(icon('warn'), el('span', null, t('st.needReview')), el('span', 'num', String(pend)));
    this.bReview.setAttribute('aria-pressed', String(this.mode === 'review'));
    this.bReset.hidden = !n || busy;
    this.bPub.hidden = !n && !this.publishing;
    this.bPub.disabled = busy || !n;
    this.bPub.replaceChildren(icon('upload'), el('span', null, this.publishing ? t('st.publishing') : t('st.publish', { n })));
    // nhật ký: lần xuất/sửa gần nhất lỗi (reviseError) hoặc job lỗi → nút nổi màu cảnh báo
    const bad = !!j && (j.status === 'error' || !!j.reviseError);
    this.bLog.dataset.logId = this.id || '';
    this.bLog.classList.toggle('bad', bad); this.bLog.classList.toggle('log-btn', bad);
    this.bLog.replaceChildren(el('span', null, t(bad ? 'log.btnErr' : 'log.btn')));
    const out = safeUrl(v?.media?.out || j?.links?.out);
    this.aDl.hidden = !out;
    if (out) { this.aDl.href = out; this.aDl.setAttribute('download', `${(name || 'video').replace(/\.[^.]+$/, '')}${v?.rev ? '-r' + v.rev : ''}.mp4`); }
    this.aDl.classList.toggle('pri', !n); this.aDl.classList.toggle('ghost', !!n);
  }
  paintRail() {
    for (const [k, b] of Object.entries(this.railBtns)) {
      const on = k === this.mode || (k === 'cap' && this.mode === 'review');
      b.classList.toggle('on', on); b.setAttribute('aria-pressed', String(on));
    }
    const n = this.review.pending();
    this.capDot.hidden = !n; this.capDot.textContent = String(n);
  }
  setMode(m, user) {
    this.mode = m;
    if (['cap', 'zoom', 'gfx', 'music'].includes(m)) this.timeline.setFocus(m);
    if (m === 'review') { this.timeline.setFocus('cap'); this.review.goto(this.review.index(), true); }
    this.paintRail(); this.paintTop(); this.insp.render();
    if (user && narrow()) this.openSheet();
  }
  openSheet() { this.insp.root.classList.add('open'); this.scrim.classList.add('on'); }
  closeSheet() { this.insp.root.classList.remove('open'); this.scrim.classList.remove('on'); }

  onStore(what) {
    if (what === 'load') return;
    if (this.sel && !this.findSel(this.sel)) this.sel = null;
    this.timeline.renderBlocks();
    this.insp.render();
    this.player.lastCap = null; this.player.lastGfx = ''; this.player.tick();
    this.paintTop(); this.paintRail();
    this.refreshGfx();
    if (this.store.doc?.music.source !== this.waveSrc) this.loadWave();
    else this.player.syncAudio(false);
  }
  /** Đổi tỉ lệ khung (1 bước Undo). Xuất bản mới: reframe theo mặt, phụ đề/đồ hoạ đặt lại trên khung mới. */
  setRatio(r) {
    if (!this.store.doc || this.store.view?.readOnly) return;
    if (this.store.commit((d) => { d.ratio = r; })) this.toast(t('st.ratioChanged', { r }));
  }
  /** Cảnh đồ hoạ xem trước: server dựng HTML/CSS từ đồ hoạ đang sửa (giờ + ô chữ/số), khung sandbox vẽ theo t. */
  refreshGfx(now) {
    const v = this.store.view; const id = this.id;
    if (!v || v.readOnly) { this.player.setGfxScene(null); return; }
    const rows = (d) => Object.fromEntries(Object.entries(d || {}).map(([k, x]) => [k, Array.isArray(x) ? x.map((r, i) => ({ k: i, ...r })) : x]));
    const list = this.store.doc.gfx.map((g) => ({ id: g.id, at: r2(g.at), until: r2(g.until), data: rows(g.data) }));
    const key = JSON.stringify(list);
    if (key === this.gfxKey) return;
    this.gfxKey = key;
    clearTimeout(this.gfxT);
    const go = async () => {
      if (!list.length) { this.player.setGfxScene(null); return; }
      try {
        const sc = await postJSON(`/api/edits/${encodeURIComponent(id)}/gfx-preview`, { graphics: list });
        if (this.id === id && this.gfxKey === key) this.player.setGfxScene(sc);
      } catch { /* ô đang gõ dở (vd số rỗng): giữ cảnh trước */ }
    };
    if (now) go(); else this.gfxT = setTimeout(go, 160);
  }
  onTime(tt) { this.timeline.setTime(tt); this.insp.onTime(tt); }
  seek(tt) { this.player.seek(tt); }

  // ---- chọn khối ----
  findSel(s) {
    const d = this.store.doc; if (!d || !s) return null;
    if (s.kind === 'cap') return d.lines.find((x) => x.u === s.u);
    if (s.kind === 'zoom') return d.zooms.find((x) => x.u === s.u);
    if (s.kind === 'gfx') return d.gfx.find((x) => x.u === s.u);
    if (s.kind === 'music') return d.music.source !== 'none' ? d.music : null;
    if (s.kind === 'clip') return s.b - s.a >= 1 / 30 ? s : null;
    if (s.kind === 'cut') return (d.cuts || [])[s.i] || null;
    return null;
  }
  select(s, { quiet } = {}) {
    this.sel = s && this.findSel(s) ? s : null;
    if (this.sel) {
      const vid = this.sel.kind === 'clip' || this.sel.kind === 'cut';
      this.vfocus = vid;
      this.mode = vid ? 'video' : this.sel.kind;
      if (this.sel.kind === 'cap') this.insp.capTab = 'lines';
      this.timeline.setFocus(vid ? 'video' : this.sel.kind);
    }
    this.timeline.renderBlocks();
    this.paintRail();
    if (!quiet || this.sel) this.insp.render();
    this.player.tick();
    if (this.sel && narrow() && !quiet) this.openSheet();
  }

  // ---- thao tác ----
  splitAtHead(u) {
    const st = this.store; const tt = this.player.time;
    if (!u && this.vfocus) { this.splitClip(); return; }
    let k = u ? st.doc.lines.findIndex((l) => l.u === u) : st.lineAt(tt);
    if (k < 0 && this.sel?.kind === 'cap') k = st.doc.lines.findIndex((l) => l.u === this.sel.u);
    if (k < 0) { this.toast(t('st.noLineHere')); return; }
    const l = st.doc.lines[k];
    if (!st.splitLine(k, tt >= l.start && tt < l.end ? tt : null)) { this.toast(t('man.cantSplit')); return; }
    this.select({ kind: 'cap', u: st.doc.lines[k + 1].u }, { quiet: true });
    this.insp.render();
  }
  mergeSel() {
    const st = this.store;
    const k = this.sel?.kind === 'cap' ? st.doc.lines.findIndex((l) => l.u === this.sel.u) : st.lineAt(this.player.time);
    if (k < 0 || k + 1 >= st.doc.lines.length) { this.toast(t('st.noMerge')); return; }
    st.mergeLine(k);
  }
  deleteSel() {
    const s = this.sel; if (!s || this.store.view?.readOnly) { this.toast(t('st.selFirst')); return; }
    if (s.kind === 'cap') this.store.commit((d) => { d.lines = d.lines.filter((x) => x.u !== s.u); });
    else if (s.kind === 'zoom') this.store.commit((d) => { d.zooms = d.zooms.filter((x) => x.u !== s.u); });
    else if (s.kind === 'gfx') this.store.commit((d) => { d.gfx = d.gfx.filter((x) => x.u !== s.u); });
    else if (s.kind === 'music') this.store.commit((d) => { d.music.source = 'none'; });
    else if (s.kind === 'clip') { if (this.store.addCut(s.a, s.b)) this.toast(t('st.cutDone', { a: fmtT(s.a), b: fmtT(s.b) })); }
    else if (s.kind === 'cut') this.store.commit((d) => { d.cuts = (d.cuts || []).filter((_, i) => i !== s.i); });
    this.sel = null; this.repaintAll();
  }
  /** S khi đang ở track video: tách clip tại đầu phát (chọn clip rồi Xoá = cắt bỏ). */
  splitClip() {
    const st = this.store; const tt = r2(this.player.time);
    if (tt <= 0.05 || tt >= st.view.duration - 0.05 || st.cutAt(tt)) { this.toast(t('st.noSplitHere')); return; }
    st.commit((d) => { d.vsplits = [...new Set([...(d.vsplits || []), tt])].sort((a, b) => a - b); });
    const c = this.timeline.clipAt(tt + 0.01); if (c) this.select({ kind: 'clip', a: c[0], b: c[1] });
  }
  /** Zoom mới tại đầu phát: đẩy chậm 1,1× dài 1,5 s (ngắn lại nếu sát zoom sau / cuối video). */
  addZoom() {
    const st = this.store; if (st.view?.readOnly) return;
    const tt = r2(this.player.time); const dur = st.view.duration;
    const hit = st.doc.zooms.find((z) => tt >= z.at - 1e-3 && tt < z.at + z.dur);
    if (hit) { this.select({ kind: 'zoom', u: hit.u }); this.toast(t('st.zoomHere')); return; }
    const next = st.doc.zooms.filter((z) => z.at > tt).sort((a, b) => a.at - b.at)[0];
    const room = Math.min(next ? next.at - tt : Infinity, dur - tt - 0.25);
    if (room < 0.3) { this.toast(t('st.zoomNoRoom')); return; }
    const z = { u: `zn${Date.now().toString(36)}`, n: null, at: tt, dur: r2(Math.min(1.5, room)), scale: 1.1, kind: 'push' };
    st.commit((d) => { d.zooms.push(z); d.zooms.sort((a, b) => a.at - b.at); });
    this.select({ kind: 'zoom', u: z.u });
  }
  setGfxTime(u, f, x) {
    const st = this.store; const g = st.doc.gfx.find((y) => y.u === u); if (!g) return;
    let a = f === 'at' ? x : g.at; let b = f === 'until' ? x : g.until;
    const others = st.doc.gfx.filter((y) => y.u !== u);
    const prev = others.filter((y) => y.until <= g.at + 1e-3).reduce((m, y) => Math.max(m, y.until), 0);
    const next = others.filter((y) => y.at >= g.until - 1e-3).reduce((m, y) => Math.min(m, y.at), st.view.duration);
    a = clamp(r2(a), prev, next - 1.5); b = clamp(r2(b), a + 1.5, Math.min(next, a + 14));
    st.commit((d) => { const y = d.gfx.find((q) => q.u === u); if (y) { y.at = a; y.until = b; } });
  }
  async uploadMusic(f) {
    const id = this.id; const msg = this.insp.musicMsg;
    if (msg) msg.textContent = t('man.uploading', { name: f.name, size: (f.size / 1e6).toFixed(1) + ' MB' });
    const fd = new FormData(); fd.append('music', f, f.name);
    try {
      const r = await fetch(`/api/edits/${encodeURIComponent(id)}/music`, { method: 'POST', body: fd });
      const j = await r.json().catch(() => ({}));
      if (!r.ok) throw new Error(j.error || 'HTTP ' + r.status);
      if (this.id !== id) return;
      this.store.view.music.uploads.push({ file: j.file, name: j.name });
      this.store.commit((d) => { d.music.source = `upload:${j.file}`; });
      if (this.insp.musicMsg) this.insp.musicMsg.textContent = t('man.uploadOk', { name: j.name });
    } catch (e) { if (this.insp.musicMsg) this.insp.musicMsg.textContent = t('man.uploadErr', { e: I.srv(e.message) }); }
  }
  musicName(src) {
    const v = this.store.view; if (!src || src === 'none') return t('ed.noMusic');
    if (src === 'keep') src = v?.music.name || '';
    if (src === 'reel') return t('st.reelMusic');
    if (src.startsWith('synth:')) { const s = src.slice(6); return s.charAt(0).toUpperCase() + s.slice(1); }
    if (src.startsWith('upload:')) return v?.music.uploads.find((u) => u.file === src.slice(7))?.name || src.slice(7);
    return src;
  }

  // ---- Xuất bản mới: bản vá → server dựng lại phần cần thiết → r<n+1> ----
  async publish() {
    const st = this.store; const id = this.id;
    const p = st.patch(); if (!Object.keys(p).length || this.publishing) return;
    const bad = st.lineErrors();
    if (bad.size) {
      const u = [...bad.keys()][0];
      this.select({ kind: 'cap', u }); this.toast(t('st.fixFirst', { n: bad.size }), 'bad'); return;
    }
    this.publishing = true; this.paintTop();
    this.player.release(); // Windows: nhả base.mp4 trước khi server ghi lại
    this.setProg(2);
    try {
      this.job = await postJSON(`/api/edits/${encodeURIComponent(id)}/manual`, p);
    } catch (e) {
      this.publishing = false; this.setProg(null); this.paintTop();
      this.toast(I.srv(e.message), 'bad'); this.reloadSources();
      return;
    }
    this.watchJob(true);
  }
  reloadSources() { const v = this.store.view; if (!v) return; this.player.setSources({ clean: safeUrl(v.media.clean), base: safeUrl(v.media.base), out: safeUrl(v.media.out) }); this.loadWave(true); }
  async revise(text) {
    const id = this.id;
    this.player.release();
    try { this.job = await postJSON(`/api/edits/${encodeURIComponent(id)}/revise`, { instruction: text }); }
    catch (e) { this.toast(I.srv(e.message), 'bad'); this.reloadSources(); return; }
    this.publishing = 'revise'; this.paintTop(); this.watchJob(true);
  }
  /** Theo dõi job (dựng / xuất / sửa bằng lời): thanh mảnh dưới thanh trên; xong thì tự chuyển sang bản mới. */
  watchJob(mine) {
    clearTimeout(this.pollT);
    const id = this.id;
    const before = this.store.view?.latest;
    const tick = async () => {
      let v;
      try { v = await getJSON(`/api/edits/${encodeURIComponent(id)}`); } catch { this.pollT = setTimeout(tick, 2500); return; }
      if (this.id !== id) return;
      this.job = v;
      if (busyOf(v)) {
        const steps = v.steps || []; const from = Number.isInteger(v.stepFrom) ? v.stepFrom : 0;
        const i = Math.max(from, v.stepIndex ?? from);
        const pct = clamp(((i - from) + (v.pct || 0) / 100) / Math.max(1, steps.length - from), 0, 1) * 100;
        const line = v.status === 'queued' ? t('ed.waitTurn') : t('ed.stepOf', { i: i + 1, n: steps.length, step: I.srv(steps[i] || ''), p: v.pct || 0 });
        if (mine || this.store.view) { this.setProg(Math.max(3, pct)); this.prog.title = line; this.toast(`${t(this.publishing === 'revise' ? 'ed.revising' : 'st.publishing')} · ${line}`, null, true); }
        else this.showWait(`${t(v.action === 'edit' ? 'ed.st.running' : 'st.publishing')} · ${line}`, pct);
        this.paintTop();
        this.pollT = setTimeout(tick, 1200); return;
      }
      const was = this.publishing; this.publishing = false; this.setProg(null);
      if (v.status === 'error' && !v.links?.out) { this.showWait(t('st.buildErr', { e: I.srv(v.error || '') }), null); this.paintTop(); return; }
      const err = v.status === 'error' ? v.error : v.reviseError;
      if (err && (mine || was)) { this.toast(I.srv(err), 'bad'); this.paintTop(); this.reloadSources(); return; }
      if (mine || was) this.store.clearDraft();
      const latest = (v.revisions || []).length;
      if (location.hash !== `#/edit/${id}`) history.replaceState(null, '', `#/edit/${id}`);
      this.rev = null;
      await this.loadView();
      if ((mine || was) && latest !== before) this.toast(t('st.published', { n: latest }), 'ok');
    };
    tick();
  }
  setProg(p) {
    this.prog.hidden = p == null;
    if (p != null) { this.prog.firstChild.style.transform = `scaleX(${clamp(p, 0, 100) / 100})`; this.prog.setAttribute('aria-valuenow', String(Math.round(p))); }
  }
  showWait(text, pct) {
    this.wait.hidden = false; this.waitT.textContent = text;
    this.waitBar.hidden = pct == null;
    if (pct != null) this.waitBar.firstChild.style.transform = `scaleX(${clamp(pct, 0, 100) / 100})`;
  }
  hideWait() { this.wait.hidden = true; }
  toast(text, kind, sticky) {
    clearTimeout(this.toastT);
    this.toastEl.hidden = false; this.toastEl.textContent = text; this.toastEl.className = 'st-toast' + (kind ? ' ' + kind : '');
    if (!sticky) this.toastT = setTimeout(() => { this.toastEl.hidden = true; }, kind === 'bad' ? 7000 : 3200);
  }

  // ---- phím tắt ----
  onKey(e) {
    if (!this.id || this.R.hidden) return;
    const tg = e.target; const typing = tg.closest?.('input, textarea, select, [contenteditable="true"]');
    const mod = e.ctrlKey || e.metaKey;
    if (mod && (e.key === 'z' || e.key === 'Z' || e.key === 'y')) {
      if (typing) return; // ô nhập tự Undo chữ của nó
      e.preventDefault();
      if (e.key === 'y' || e.shiftKey) this.store.doRedo(); else this.store.doUndo();
      return;
    }
    if (typing || mod || e.altKey) { if (e.key === 'Escape' && typing) tg.blur(); return; }
    if (e.key === ' ' || e.code === 'Space') { e.preventDefault(); this.player.toggle(); return; }
    if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
      if (tg.closest?.('[role=radiogroup], [role=tablist]')) return;
      e.preventDefault();
      const d = (e.key === 'ArrowLeft' ? -1 : 1) * (e.shiftKey ? 1 : 1 / 30);
      this.player.step(d); this.timeline.scrollToTime(this.player.time); return;
    }
    if (e.key === 's' || e.key === 'S') { e.preventDefault(); this.splitAtHead(); return; }
    if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault(); this.deleteSel(); return; }
    if (e.key === 'Escape') { if (this.sel) { this.select(null); } else this.closeSheet(); }
  }

  // ---- "Cần xem lại": chữ AI sửa + số nghe không chắc; đi lần lượt, đầu phát nhảy tới đúng chỗ ----
  makeReview() {
    const S = this; let list = []; let idx = 0; let id = null; let res = {};
    const key = () => `lumreels.studio.review.${id}`;
    const toOut = (src) => {
      const e = S.edl; if (!e || !Number.isFinite(src)) return null;
      const h = e.hook; const hd = h ? h.end - h.start : 0;
      let acc = hd;
      for (const k of e.keep) { if (src < k.start - 1e-6) return r2(acc); if (src <= k.end + 1e-6) return r2(acc + src - k.start); acc += k.end - k.start; }
      if (h && src >= h.start && src <= h.end) return r2(src - h.start);
      return null;
    };
    const R = {
      reset(nid) { id = nid; list = []; idx = 0; res = ls.get(key(), {}) || {}; },
      build() {
        const j = S.job || {}; const e = S.edl; if (!e) { list = []; return; }
        const words = new Map((e.captions?.words || []).map((w) => [w.i, w]));
        const fx = [...(j.fixes || [])].sort((a, b) => a.word - b.word);
        const out = [];
        for (let i = 0; i < fx.length; i++) {
          const f = fx[i]; let heard = f.heard || '';
          // "vờ" + "ga" → "VGA": chữ sau bị gộp (text rỗng) nối vào chữ trước
          while (fx[i + 1] && fx[i + 1].word === fx[i].word + 1 && !fx[i + 1].text && f.text) { heard += ' ' + (fx[i + 1].heard || ''); i++; }
          const w = words.get(f.word);
          out.push({ key: `fix:${f.word}`, kind: 'fix', at: toOut(w ? w.start : null), heard: heard.trim(), text: f.text || '', why: '' });
        }
        for (const f of j.checks?.figures || []) out.push({ key: `fig:${f.at}:${f.text}`, kind: 'fig', at: toOut(f.at), heard: f.said || f.heard || '', relisten: f.heard || '', text: f.text || '', why: f.why || '', gtype: f.type || null, where: f.where || null, value: f.value });
        list = out.filter((x) => x.at != null).sort((a, b) => a.at - b.at);
        idx = Math.max(0, list.findIndex((x) => !res[x.key]));
      },
      items: () => list,
      pending: () => list.filter((x) => !res[x.key]).length,
      index: () => idx,
      current: () => list[idx] || null,
      status: (it) => res[it.key] || null,
      lineOf(it) { const L = S.store.doc?.lines || []; return L.find((l) => it.at >= l.start - 0.05 && it.at < l.end) || L.find((l) => it.at < l.end) || null; },
      inLine(l) { return list.filter((it) => !res[it.key] && it.at >= l.start - 0.05 && it.at < l.end); },
      flagged(u) { const l = S.store.doc?.lines.find((x) => x.u === u); return !!l && R.inLine(l).length > 0; },
      goto(i, noRender) {
        if (!list.length) return;
        idx = clamp(i, 0, list.length - 1); const it = list[idx];
        S.player.pause(); S.seek(it.at); S.timeline.scrollToTime(it.at);
        const l = R.lineOf(it); if (l) { S.sel = { kind: 'cap', u: l.u }; S.timeline.renderBlocks(); }
        if (!noRender) S.insp.render();
      },
      go(d) { R.goto(idx + d); },
      resolve(it, how) {
        res[it.key] = how; ls.set(key(), res);
        const next = list.findIndex((x, i) => i > idx && !res[x.key]);
        const any = next >= 0 ? next : list.findIndex((x) => !res[x.key]);
        if (any >= 0) R.goto(any, true);
        S.paintTop(); S.paintRail(); S.timeline.renderBlocks(); S.insp.render();
      },
      edit(it) {
        const l = R.lineOf(it); if (!l) return;
        res[it.key] = 'edit'; ls.set(key(), res);
        S.mode = 'cap'; S.insp.capTab = 'lines'; S.insp.wantFocus = l.u;
        S.seek(it.at); S.select({ kind: 'cap', u: l.u });
        S.paintTop(); S.paintRail();
      },
      /** Số trên đồ hoạ: ô đồ hoạ tương ứng {g, path, cur} (cùng loại, đang hiện quanh lúc đó) hoặc null. */
      figTarget(it) {
        if (it.kind !== 'fig' || !it.gtype || !it.where) return null;
        const gs = (S.store.doc?.gfx || []).filter((g) => g.type === it.gtype && it.at >= g.at - 0.6 && it.at <= g.until + 0.6)
          .sort((a, b) => Math.abs(a.at - it.at) - Math.abs(b.at - it.at));
        const w = String(it.where); let m;
        const pathOf = (g) => {
          if (w === 'value' || w === 'old') return [w];
          if ((m = /^(mục|điểm) (\d+)$/u.exec(w))) return [m[1] === 'mục' ? 'items' : 'points', +m[2], 'value'];
          if ((m = /^dòng (\d+)(?: ([ab]))?$/u.exec(w))) return ['rows', +m[1], m[2] || 'value'];
          if ((m = /^ý (\d+)$/u.exec(w))) return ['items', +m[1], 'text'];
          return null;
        };
        for (const g of gs) {
          const pth = pathOf(g); if (!pth) continue;
          let o = g.data; for (const k of pth) { if (o == null) break; o = o[k]; }
          if (typeof o === 'string' || typeof o === 'number') return { g, path: pth, cur: o };
        }
        return null;
      },
      /** Số nghe được (nghe lại riêng trước, rồi lời chép): "9 rưỡi" → 9,5. */
      heardNums(it) {
        const out = [];
        for (const src of [it.relisten, it.heard]) {
          const s0 = String(src || '').replace(/(\d+)\s+rư[ỡở]i/giu, (_, n) => `${n},5`);
          for (const x of s0.match(/\d+(?:[.,]\d+)?/g) || []) out.push(x);
          if (out.length) break;
        }
        return out;
      },
      /** Giá trị trả lại cho ô đồ hoạ: số nghe được đầu tiên khác số đang in. */
      figRevertValue(it, tg) {
        const nums = R.heardNums(it); const num = (x) => Number(String(x).replace(',', '.'));
        if (typeof tg.cur === 'number') { const x = nums.map(num).find((v) => Number.isFinite(v) && v !== tg.cur); return x ?? null; }
        // ô chữ ("22–23"): thay lần lượt từng số trong ô bằng số nghe được cùng vị trí (cửa sổ bắt đầu ở số trùng số đầu ô)
        const curNums = String(tg.cur).match(/\d+(?:[.,]\d+)?/g) || [];
        if (!curNums.length || !nums.length) return null;
        let i0 = nums.indexOf(curNums[0]); if (i0 < 0 || i0 + curNums.length > nums.length) i0 = Math.max(0, nums.length - curNums.length);
        let k = 0;
        const v = String(tg.cur).replace(/\d+(?:[.,]\d+)?/g, (x) => nums[i0 + k++] ?? x);
        return v === String(tg.cur) ? null : v;
      },
      canRevert(it) {
        if (it.kind === 'fig') { const tg = R.figTarget(it); return !!tg && R.figRevertValue(it, tg) != null; }
        if (!it.text || !it.heard) return false;
        const l = R.lineOf(it); return !!l && plain(l.text).toLowerCase().includes(it.text.toLowerCase());
      },
      revert(it) {
        if (it.kind === 'fig') {
          const tg = R.figTarget(it); if (!tg) return;
          const v = R.figRevertValue(it, tg); if (v == null) return;
          S.store.commit((d) => {
            const g = d.gfx.find((x) => x.u === tg.g.u); if (!g) return;
            let o = g.data; for (let k = 0; k < tg.path.length - 1; k++) o = o[tg.path[k]];
            o[tg.path[tg.path.length - 1]] = v;
          });
          S.select({ kind: 'gfx', u: tg.g.u }, { quiet: true });
          R.resolve(it, 'revert');
          return;
        }
        const l = R.lineOf(it); if (!l || !R.canRevert(it)) return;
        S.store.commit((d) => {
          const x = d.lines.find((y) => y.u === l.u); if (!x) return;
          const ws = tokens(x.text); const tw = tokens(it.text).map((w) => w.w.toLowerCase());
          for (let i = 0; i + tw.length <= ws.length; i++) {
            if (tw.every((w, k) => ws[i + k].w.toLowerCase().replace(/[^\p{L}\p{N}]/gu, '') === w.replace(/[^\p{L}\p{N}]/gu, ''))) {
              ws.splice(i, tw.length, ...tokens(it.heard).map((w) => ({ w: w.w, hi: ws[i].hi })));
              break;
            }
          }
          x.text = untokens(ws);
        });
        R.resolve(it, 'revert');
      },
    };
    return R;
  }
}

let studio = null;
function boot() { studio = new Studio(); window.LumStudio = studio; }
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();