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.
// "Tạo mẫu từ video" (THIET-KE gói mẫu §4.1, §5.4): hộp tải video tham khảo → xác nhận quyền → theo dõi tiến độ
// → xem nháp (bản dựng thử cạnh video gốc, bảng số, điểm lệch, guidance sửa tay) → Lưu thành mẫu "Của tôi" hoặc Bỏ.
// Tự chứa: tự nạp learn-panel.css, tự gắn nút "Tạo mẫu" cạnh ô tìm mẫu. Chữ qua window.I18N (khoá lp.*).
// Mọi chuỗi từ server/người dùng/AI chỉ đi vào textContent (L9), không vào innerHTML.
// API: /api/drafts (packs/drafts-http.mjs).
(() => {
const t = (k, v) => window.I18N.t(k, v);
const srv = (s) => window.I18N.srv(s);
const css = document.createElement('link');
css.rel = 'stylesheet'; css.href = '/learn-panel.css';
document.head.appendChild(css);
const IC = {
spark: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5 18 18M6 18l2.5-2.5M15.5 8.5 18 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',
up: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 16V4m0 0-4 4m4-4 4 4M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',
check: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m5 12 5 5 9-10" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
x: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>',
back: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M15 5 8 12l7 7" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
};
const STEP_KEYS = ['measuring', 'writing', 'testing', 'comparing', 'revising'];
/** Tạo phần tử: h('div.cls', {attr}, ...con). Chuỗi con → textNode (không bao giờ là HTML). */
function h(tag, attrs = {}, ...kids) {
const [name, ...cls] = tag.split('.');
const el = document.createElement(name);
if (cls.length) el.className = cls.join(' ');
for (const [k, v] of Object.entries(attrs || {})) {
if (v === undefined || v === null || v === false) continue;
if (k === 'on') for (const [ev, fn] of Object.entries(v)) el.addEventListener(ev, fn);
else if (k === 'html') el.innerHTML = v; // chỉ dùng cho icon tĩnh trong file này
else if (k in el && typeof v !== 'string') el[k] = v;
else el.setAttribute(k, v === true ? '' : v);
}
for (const c of kids.flat()) if (c !== null && c !== undefined && c !== false) el.append(c instanceof Node ? c : document.createTextNode(String(c)));
return el;
}
const fmtS = (ms) => { const s = Math.max(0, Math.round(ms / 1000)); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; };
const usd = (n) => `$${(Number(n) || 0).toFixed(2)}`;
const slugify = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[đĐ]/g, 'd').toLowerCase()
.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').replace(/^[^a-z]+/, '').slice(0, 32).replace(/-+$/, '');
// ---------- trạng thái ----------
let info = { drafts: [], limits: { maxBytes: 200 * 1024 * 1024, minS: 4, maxS: 180, segS: 8, ext: ['.mp4', '.mov', '.webm', '.m4v'], consent: '' }, engine: 'claude' };
let view = 'list'; // list | form | draft
let cur = null; // nháp đang xem (draftView từ server)
let pollTimer = null;
const F = { file: null, url: '', dur: null, from: 0, name: '', note: '', category: '', consent: false, skipTest: false, err: '', sending: false, pct: 0 };
const E = { text: null, dirty: false, lint: null, saving: false, name: '', slug: '', slugTouched: false, err: '', busy: false };
// ---------- nút mở + hộp ----------
const openBtn = h('button.lp-open', { type: 'button', on: { click: () => open() } });
const dlg = h('dialog.lp', { 'aria-labelledby': 'lpTitle' });
const live = h('div.sr', { role: 'status', 'aria-live': 'polite' });
document.body.append(dlg);
function mountButton() {
const f = document.querySelector('#tplTab .filters');
if (f && !openBtn.isConnected) f.insertBefore(openBtn, f.querySelector('.chips'));
}
function paintButton() { openBtn.innerHTML = IC.spark; openBtn.append(h('span', {}, t('lp.open'))); openBtn.setAttribute('aria-haspopup', 'dialog'); }
dlg.addEventListener('cancel', (e) => { if (F.sending) e.preventDefault(); });
dlg.addEventListener('close', () => { clearTimeout(pollTimer); });
async function open(id) {
if (!dlg.open) dlg.showModal();
await loadList();
if (id) return openDraft(id);
const running = info.drafts.find((d) => !['ready', 'error', 'saved', 'discarded'].includes(d.status));
if (running) return openDraft(running.id);
view = info.drafts.some((d) => ['ready', 'error'].includes(d.status)) ? 'list' : 'form';
render();
}
async function loadList() {
try { const r = await fetch('/api/drafts'); if (r.ok) info = await r.json(); } catch { /* giữ dữ liệu cũ */ }
}
async function openDraft(id) {
try {
const r = await fetch(`/api/drafts/${encodeURIComponent(id)}`);
if (!r.ok) throw new Error((await r.json()).error);
const d = await r.json();
if (!cur || cur.id !== d.id) { E.text = null; E.dirty = false; E.lint = null; E.err = ''; E.slugTouched = false; E.name = d.name || ''; E.slug = ''; }
cur = d;
if (!E.dirty) E.text = d.guidance;
if (!E.name && d.guidance) E.name = (/^title:\s*(.+)$/m.exec(d.guidance) || [])[1]?.trim() || '';
if (!E.slugTouched) E.slug = slugify(E.name);
view = 'draft';
} catch (e) { F.err = srv(e.message) || t('lp.loadErr'); view = 'list'; }
render();
schedulePoll();
}
function schedulePoll() {
clearTimeout(pollTimer);
if (dlg.open && view === 'draft' && cur && !['ready', 'error', 'saved', 'discarded'].includes(cur.status)) {
pollTimer = setTimeout(() => { if (dlg.open && view === 'draft') openDraft(cur.id); }, 2500);
}
}
// ---------- vẽ ----------
function head(title, backTo) {
return h('div.lp-head', {},
backTo ? h('button.lp-icon', { type: 'button', 'aria-label': t('lp.back'), html: IC.back, on: { click: backTo } }) : null,
h('h2', { id: 'lpTitle' }, title),
h('button.lp-icon', { type: 'button', 'aria-label': t('lp.close'), html: IC.x, disabled: F.sending, on: { click: () => dlg.close() } }));
}
function render() {
const focusId = document.activeElement?.id;
dlg.replaceChildren(live, ...(view === 'form' ? formView() : view === 'draft' && cur ? draftView() : listView()).filter(Boolean));
if (focusId && dlg.querySelector('#' + CSS.escape(focusId))) dlg.querySelector('#' + CSS.escape(focusId)).focus({ preventScroll: true });
}
function statusLabel(d) {
if (d.status === 'ready') return t(d.tested === false ? 'lp.st.readyNoTest' : 'lp.st.ready');
return t('lp.st.' + d.status);
}
function listView() {
const items = info.drafts.filter((d) => d.status !== 'saved');
return [
head(t('lp.title')),
h('p.lp-lead', {}, t('lp.lead')),
F.err ? h('p.lp-err', { role: 'alert' }, F.err) : null,
items.length ? h('ul.lp-list', {}, items.map((d) => h('li', {},
h('button.lp-row', { type: 'button', on: { click: () => { F.err = ''; openDraft(d.id); } } },
h('span.lp-row-t', {}, d.name || d.video?.filename || d.id),
h('span.lp-chip.' + (d.status === 'ready' ? 'ok' : d.status === 'error' ? 'bad' : 'run'), {}, statusLabel(d)),
h('span.lp-row-m', {}, `${fmtS(d.totals?.ms || 0)} · ${usd(d.totals?.costUSD)}`))))) : h('p.lp-empty', {}, t('lp.noDrafts')),
h('div.lp-actions', {}, h('button.lp-primary', { type: 'button', on: { click: () => { F.err = ''; view = 'form'; render(); } } }, t('lp.new'))),
];
}
// ---- form tải video ----
function pickFile(file) {
F.err = '';
if (F.url) URL.revokeObjectURL(F.url);
F.file = null; F.url = ''; F.dur = null; F.from = 0;
if (!file) return render();
const ext = (file.name.match(/\.[^.]+$/) || [''])[0].toLowerCase();
if (!info.limits.ext.includes(ext)) { F.err = t('lp.err.ext'); return render(); }
if (file.size > info.limits.maxBytes) { F.err = t('lp.err.big'); return render(); }
F.file = file; F.url = URL.createObjectURL(file);
if (!F.name) F.name = '';
render();
}
function formView() {
const L = info.limits;
const segEnd = F.dur ? Math.min(F.dur, F.from + L.segS) : null;
const video = F.url ? h('video.lp-vid', { src: F.url, muted: true, playsInline: true, preload: 'metadata', controls: true, 'aria-label': t('lp.refVideo'),
on: {
loadedmetadata: (e) => {
const d = e.target.duration;
if (!Number.isFinite(d)) return;
if (F.dur !== d) {
F.dur = d;
F.err = d < L.minS ? t('lp.err.short', { min: L.minS }) : d > L.maxS + 0.5 ? t('lp.err.long') : '';
render();
}
},
timeupdate: (e) => { if (segEnd && e.target.currentTime > segEnd) e.target.currentTime = F.from; },
} }) : null;
if (video && F.dur) video.currentTime = F.from;
const maxFrom = F.dur ? Math.max(0, Math.floor((F.dur - Math.min(L.segS, F.dur)) * 2) / 2) : 0;
const canGo = !!F.file && F.consent && !F.sending && F.dur && F.dur >= L.minS && F.dur <= L.maxS + 0.5;
return [
head(t('lp.title'), info.drafts.some((d) => d.status !== 'saved') ? () => { view = 'list'; render(); } : null),
h('p.lp-lead', {}, t('lp.lead')),
h('div.lp-form', {},
h('div.lp-col', {},
F.file ? h('div.lp-picked', {}, video,
h('div.lp-file', {}, h('span', {}, F.file.name), h('span.lp-dim', {}, `${(F.file.size / 1048576).toFixed(1)} MB${F.dur ? ` · ${F.dur.toFixed(1)} s` : ''}`),
h('button.lp-link', { type: 'button', disabled: F.sending, on: { click: () => { pickFile(null); } } }, t('lp.change'))))
: h('label.lp-drop', { for: 'lpFile', tabindex: '0', role: 'button', 'aria-describedby': 'lpDropHint',
on: {
keydown: (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); dlg.querySelector('#lpFile').click(); } },
dragover: (e) => { e.preventDefault(); e.currentTarget.classList.add('on'); },
dragleave: (e) => e.currentTarget.classList.remove('on'),
drop: (e) => { e.preventDefault(); pickFile(e.dataTransfer.files[0]); },
} },
h('span.lp-drop-ic', { html: IC.up }), h('span.lp-big', {}, t('lp.drop')), h('span.lp-dim', { id: 'lpDropHint' }, t('lp.dropHint'))),
h('input', { type: 'file', id: 'lpFile', accept: 'video/mp4,video/quicktime,video/webm,.mp4,.mov,.webm,.m4v', hidden: true, on: { change: (e) => pickFile(e.target.files[0]) } }),
F.file && F.dur && F.dur > L.segS ? h('div.lp-field', {},
h('label', { for: 'lpFrom' }, t('lp.from')),
h('div.lp-range', {},
h('input', { type: 'range', id: 'lpFrom', min: '0', max: String(maxFrom), step: '0.5', value: String(F.from), disabled: F.sending,
on: { input: (e) => { F.from = Number(e.target.value); const v = dlg.querySelector('.lp-vid'); if (v) v.currentTime = F.from; dlg.querySelector('#lpFromOut').textContent = t('lp.seg', { a: F.from.toFixed(1), b: (F.from + L.segS).toFixed(1) }); } } }),
h('output', { id: 'lpFromOut', for: 'lpFrom' }, t('lp.seg', { a: F.from.toFixed(1), b: segEnd.toFixed(1) }))),
h('p.lp-hint', {}, t('lp.fromHint'))) : null),
h('div.lp-col', {},
h('div.lp-field', {}, h('label', { for: 'lpName' }, t('lp.name'), h('span.lp-opt', {}, t('lp.optional'))),
h('input.lp-in', { id: 'lpName', type: 'text', maxlength: '40', value: F.name, placeholder: t('lp.namePh'), autocomplete: 'off', disabled: F.sending, on: { input: (e) => { F.name = e.target.value; } } })),
h('div.lp-field', {}, h('label', { for: 'lpCat' }, t('lp.cat')),
h('select.lp-in', { id: 'lpCat', disabled: F.sending, on: { change: (e) => { F.category = e.target.value; } } },
['', 'faceless', 'ads', 'multi-style', 'viet-nam'].map((c) => h('option', { value: c, selected: F.category === c }, c ? t('cat.' + c) : t('lp.catAuto'))))),
h('div.lp-field', {}, h('label', { for: 'lpNote' }, t('lp.note'), h('span.lp-opt', {}, t('lp.optional'))),
h('textarea.lp-in', { id: 'lpNote', rows: '2', maxlength: '300', placeholder: t('lp.notePh'), disabled: F.sending, on: { input: (e) => { F.note = e.target.value; } } }, F.note)),
h('div.lp-rules', {}, h('strong', {}, t('lp.rulesH')), h('ul', {}, h('li', {}, t('lp.rule1')), h('li', {}, t('lp.rule2')), h('li', {}, t('lp.rule3')))),
h('label.lp-check.lp-consent', { for: 'lpConsent' },
h('input', { type: 'checkbox', id: 'lpConsent', checked: F.consent, disabled: F.sending, required: true, on: { change: (e) => { F.consent = e.target.checked; render(); } } }),
h('span', {}, t('lp.consent'))),
h('label.lp-check', { for: 'lpSkip' },
h('input', { type: 'checkbox', id: 'lpSkip', checked: F.skipTest, disabled: F.sending, on: { change: (e) => { F.skipTest = e.target.checked; render(); } } }),
h('span', {}, t('lp.skipTest'))),
h('p.lp-hint', {}, t(F.skipTest ? 'lp.estNoTest' : 'lp.est')),
F.err ? h('p.lp-err', { role: 'alert' }, F.err) : null,
F.sending ? h('div.lp-bar', { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', 'aria-valuenow': String(F.pct), 'aria-label': t('lp.uploading') }, h('i', { style: `width:${F.pct}%` })) : null,
h('div.lp-actions', {},
h('button.lp-primary', { type: 'button', disabled: !canGo, on: { click: submit } }, F.sending ? t('lp.uploadingPct', { p: F.pct }) : t('lp.go')),
!F.consent && F.file ? h('span.lp-dim', {}, t('lp.needConsent')) : null))),
];
}
function submit() {
if (!F.file || !F.consent || F.sending) return;
const fd = new FormData();
fd.append('kind', 'template');
fd.append('consent', '1');
fd.append('from', String(F.from));
if (F.name.trim()) fd.append('name', F.name.trim());
if (F.note.trim()) fd.append('note', F.note.trim());
if (F.category) fd.append('category', F.category);
if (F.skipTest) fd.append('skipTest', '1');
fd.append('video', F.file, F.file.name); // file gửi sau cùng: server kiểm consent/kind trước khi nhận file
F.sending = true; F.pct = 0; F.err = ''; render();
const x = new XMLHttpRequest();
x.open('POST', '/api/drafts');
x.upload.onprogress = (e) => { if (e.lengthComputable) { F.pct = Math.round((e.loaded / e.total) * 100); const b = dlg.querySelector('.lp-bar i'); if (b) b.style.width = F.pct + '%'; const btn = dlg.querySelector('.lp-primary'); if (btn) btn.textContent = t('lp.uploadingPct', { p: F.pct }); } };
x.onload = () => {
F.sending = false;
let j = {};
try { j = JSON.parse(x.responseText); } catch { /* bỏ qua */ }
if (x.status !== 202) { F.err = srv(j.error) || t('lp.err.upload'); return render(); }
if (F.url) URL.revokeObjectURL(F.url);
Object.assign(F, { file: null, url: '', dur: null, from: 0, name: '', note: '', category: '', consent: false, skipTest: false });
live.textContent = t('lp.started');
openDraft(j.id);
};
x.onerror = () => { F.sending = false; F.err = t('lp.err.upload'); render(); };
x.send(fd);
}
// ---- nháp: tiến độ / xem / lưu ----
function stepsBox(d) {
const order = d.stepOrder || STEP_KEYS;
const idx = order.indexOf(d.status);
const runningNow = idx >= 0;
const est = order.reduce((a, k) => a + (d.stepEstS?.[k] || 0), 0) * 1000;
const doneMs = order.reduce((a, k) => a + (d.steps?.[k]?.ms || 0), 0);
const curMs = runningNow && d.stepStartedAt ? Date.now() - new Date(d.stepStartedAt).getTime() : 0;
const pct = d.status === 'ready' ? 100 : Math.min(97, Math.round(((doneMs + Math.min(curMs, (d.stepEstS?.[d.status] || 60) * 1000)) / est) * 100));
return h('div.lp-steps-wrap', {},
runningNow ? h('div.lp-bar', { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', 'aria-valuenow': String(pct), 'aria-label': t('lp.progress') }, h('i', { style: `width:${pct}%` })) : null,
h('ol.lp-steps', { 'aria-label': t('lp.progress') }, order.map((k, i) => {
const s = d.steps?.[k];
const state = s && (!runningNow || i < idx) ? 'done' : i === idx ? 'now' : 'todo';
return h('li.' + state, {},
h('span.lp-dot', { 'aria-hidden': 'true', html: state === 'done' ? IC.check : '' }),
h('span.lp-step-t', {}, t('lp.step.' + k)),
h('span.lp-step-m', {}, state === 'done' ? `${fmtS(s.ms)}${s.costUSD ? ' · ' + usd(s.costUSD) : ''}` : state === 'now' ? t('lp.stepNow', { e: fmtS(curMs), est: fmtS((d.stepEstS?.[k] || 0) * 1000) }) : t('lp.stepEst', { est: fmtS((d.stepEstS?.[k] || 0) * 1000) })),
state === 'done' && s.note ? h('span.lp-step-n', {}, srv(s.note)) : null);
})),
runningNow ? h('p.lp-hint', {}, t('lp.canClose')) : null);
}
function compareTable(c) {
return h('table.lp-table', {},
h('caption', {}, t('lp.cmpH', { n: c.offCount, total: c.rows.length })),
h('thead', {}, h('tr', {}, h('th', { scope: 'col' }, t('lp.cmpMetric')), h('th', { scope: 'col' }, t('lp.cmpRef')), h('th', { scope: 'col' }, t('lp.cmpTest')), h('th', { scope: 'col' }, t('lp.cmpDev')))),
h('tbody', {}, c.rows.map((r) => h('tr.' + (r.off ? 'off' : 'ok'), {},
h('th', { scope: 'row' }, t('lp.m.' + r.key)),
h('td', {}, r.key === 'palette' ? swatches(r.ref) : r.ref ?? '–'),
h('td', {}, r.key === 'palette' ? swatches(r.test) : r.test ?? '–'),
h('td', {}, r.dev == null ? '–' : h('span', {}, `${Math.round(r.dev * 100)}%`, h('span.lp-tag', {}, t(r.off ? 'lp.off' : 'lp.near'))))))));
}
function swatches(s) {
const cols = String(s || '').split(' ').filter((x) => /^#[0-9A-F]{6}$/i.test(x));
return h('span.lp-sw', {}, cols.map((c) => h('i', { style: `background:${c}`, title: c })), h('span.sr', {}, cols.join(' ')));
}
function draftView() {
const d = cur;
const busy = !['ready', 'error', 'saved', 'discarded'].includes(d.status);
const out = [head(d.savedName || d.name || t('lp.draftH'), () => { view = 'list'; loadList().then(render); })];
out.push(h('div.lp-meta', {},
h('span.lp-chip.' + (d.status === 'ready' || d.status === 'saved' ? 'ok' : d.status === 'error' ? 'bad' : 'run'), {}, statusLabel(d)),
h('span.lp-dim', {}, t('lp.totals', { t: fmtS(d.totals?.ms || 0), c: usd(d.totals?.costUSD) })),
d.video ? h('span.lp-dim', {}, t('lp.fromFile', { f: d.video.filename, a: d.segment.from, b: +(d.segment.from + d.segment.dur).toFixed(1) })) : null));
if (d.status === 'saved') {
out.push(h('div.lp-done', {},
h('span.lp-done-ic', { html: IC.check, 'aria-hidden': 'true' }),
h('div', {}, h('strong', {}, t('lp.savedH')), h('p', {}, t('lp.savedP', { ref: d.savedAs }))),
h('button.lp-primary', { type: 'button', on: { click: () => { const ref = d.savedAs; dlg.close(); window.dispatchEvent(new CustomEvent('lumreels:templates', { detail: { pick: ref } })); } } }, t('lp.useNow'))));
return out;
}
out.push(stepsBox(d));
if (d.status === 'error') out.push(h('p.lp-err', { role: 'alert' }, srv(d.error) || t('lp.err.run')));
if (busy) return out;
// ---- xem nháp ----
out.push(h('div.lp-media', {},
h('figure', {}, h('figcaption', {}, t('lp.refVideo')),
d.links.ref ? h('video', { src: d.links.ref + `#t=${d.segment.from},${d.segment.from + d.segment.dur}`, controls: true, muted: true, playsInline: true, preload: 'metadata', loop: true }) : h('div.lp-ph', {}, t('lp.noRef'))),
h('figure', {}, h('figcaption', {}, t('lp.testVideo')),
d.links.test && d.tested !== false ? h('video', { src: d.links.test, controls: true, playsInline: true, preload: 'metadata', poster: d.links.thumb || undefined }) : h('div.lp-ph', {}, t('lp.notTested')))));
if (d.links.sheet || d.links.testSheet) {
out.push(h('details.lp-sheets', {}, h('summary', {}, t('lp.sheets')),
h('div.lp-media', {},
d.links.sheet ? h('figure', {}, h('figcaption', {}, t('lp.refSheet')), h('img', { src: d.links.sheet, alt: t('lp.refSheetAlt'), loading: 'lazy' })) : null,
d.links.testSheet ? h('figure', {}, h('figcaption', {}, t('lp.testSheet')), h('img', { src: d.links.testSheet, alt: t('lp.testSheetAlt'), loading: 'lazy' })) : null)));
}
if (d.compare) out.push(compareTable(d.compare));
if (d.review?.diffs?.length) out.push(h('div.lp-diffs', {}, h('h3', {}, t(d.revised ? 'lp.diffsFixed' : 'lp.diffsH')), h('ul', {}, d.review.diffs.map((x) => h('li', {}, x)))));
if (d.review?.selfCheck?.length) {
const ok = d.review.selfCheck.filter((x) => x.ok).length;
out.push(h('details.lp-self', {}, h('summary', {}, t('lp.selfH', { ok, n: d.review.selfCheck.length })),
h('ul', {}, d.review.selfCheck.map((x) => h('li.' + (x.ok ? 'ok' : 'bad'), {}, h('span', { 'aria-hidden': 'true' }, x.ok ? '✓ ' : '✗ '), h('span.sr', {}, t(x.ok ? 'lp.yes' : 'lp.no') + ': '), x.q)))));
}
// guidance sửa tay
const lint = E.lint || d.lint || { errors: [], warnings: [] };
out.push(h('div.lp-field.lp-guide', {},
h('label', { for: 'lpGuide' }, t('lp.guideH'), h('span.lp-opt', {}, t('lp.guideHint'))),
h('textarea.lp-in.lp-mono', { id: 'lpGuide', rows: '14', spellcheck: false, disabled: E.busy, on: { input: (e) => { E.text = e.target.value; if (!E.dirty) { E.dirty = true; render(); } } } }, E.text || ''),
lint.errors?.length ? h('ul.lp-errs', { role: 'alert' }, lint.errors.map((x) => h('li', {}, srv(x)))) : null,
lint.warnings?.length ? h('ul.lp-warns', {}, lint.warnings.map((x) => h('li', {}, srv(x)))) : null,
h('div.lp-actions', {},
h('button.lp-ghost', { type: 'button', disabled: !E.dirty || E.busy, on: { click: saveText } }, t('lp.saveText')),
E.dirty ? h('span.lp-dim', {}, t('lp.unsaved')) : null)));
// lưu thành mẫu
const canSave = d.status === 'ready' && !E.dirty && !E.busy && !(lint.errors?.length) && E.name.trim() && /^[a-z][a-z0-9-]{1,31}$/.test(E.slug);
out.push(h('div.lp-save', {},
h('h3', {}, t('lp.saveH')),
h('div.lp-save-row', {},
h('div.lp-field', {}, h('label', { for: 'lpSaveName' }, t('lp.saveName')),
h('input.lp-in', { id: 'lpSaveName', type: 'text', maxlength: '40', value: E.name, autocomplete: 'off', on: { input: (e) => { E.name = e.target.value; if (!E.slugTouched) { E.slug = slugify(E.name); const s = dlg.querySelector('#lpSlug'); if (s) s.value = E.slug; } syncSave(); } } })),
h('div.lp-field', {}, h('label', { for: 'lpSlug' }, t('lp.slug')),
h('input.lp-in.lp-mono', { id: 'lpSlug', type: 'text', maxlength: '32', value: E.slug, autocomplete: 'off', spellcheck: false, 'aria-describedby': 'lpSlugHint', on: { input: (e) => { E.slug = e.target.value.trim(); E.slugTouched = true; syncSave(); } } }),
h('p.lp-hint', { id: 'lpSlugHint' }, t('lp.slugHint')))),
d.status === 'error' ? h('p.lp-hint', {}, t('lp.errNoSave')) : null,
E.err ? h('p.lp-err', { role: 'alert' }, E.err) : null,
h('div.lp-actions', {},
h('button.lp-primary', { type: 'button', id: 'lpSaveBtn', disabled: !canSave, on: { click: save } }, t('lp.save')),
h('button.lp-ghost', { type: 'button', disabled: E.busy || E.dirty, on: { click: retest } }, t('lp.retest')),
h('button.lp-danger', { type: 'button', disabled: E.busy, on: { click: discard } }, t('lp.discard'))),
h('p.lp-hint', {}, t('lp.saveNote'))));
return out;
}
function syncSave() {
const b = dlg.querySelector('#lpSaveBtn');
const lint = E.lint || cur?.lint || { errors: [] };
if (b) b.disabled = !(cur?.status === 'ready' && !E.dirty && !E.busy && !(lint.errors?.length) && E.name.trim() && /^[a-z][a-z0-9-]{1,31}$/.test(E.slug));
}
async function call(method, url, body) {
const r = await fetch(url, { method, headers: body ? { 'Content-Type': 'application/json' } : {}, body: body ? JSON.stringify(body) : undefined });
const j = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(j.error || r.statusText);
return j;
}
async function saveText() {
E.busy = true; E.err = ''; render();
try {
const j = await call('PUT', `/api/drafts/${cur.id}/text`, { text: E.text });
E.lint = { errors: [...j.errors, ...j.seen.map((s) => t('lp.seenHit', { s }))], warnings: j.warnings };
E.dirty = false; cur = { ...cur, ...j.draft }; E.text = j.draft.guidance;
live.textContent = t(E.lint.errors.length ? 'lp.textBad' : 'lp.textOk');
} catch (e) { E.err = srv(e.message); }
E.busy = false; render();
}
async function save() {
E.busy = true; E.err = ''; render();
try {
const j = await call('POST', `/api/drafts/${cur.id}/save`, { slug: E.slug, name: E.name.trim() });
cur = { ...cur, ...j.draft };
live.textContent = t('lp.savedH');
window.dispatchEvent(new CustomEvent('lumreels:templates', { detail: {} }));
} catch (e) { E.err = srv(e.message); }
E.busy = false; render();
}
async function retest() {
E.busy = true; E.err = ''; render();
try { await call('POST', `/api/drafts/${cur.id}/retest`); E.busy = false; return openDraft(cur.id); } catch (e) { E.err = srv(e.message); }
E.busy = false; render();
}
async function discard() {
if (!confirm(t('lp.discardAsk'))) return;
E.busy = true; render();
try { await call('DELETE', `/api/drafts/${cur.id}`); cur = null; await loadList(); view = info.drafts.some((d) => d.status !== 'saved') ? 'list' : 'form'; live.textContent = t('lp.discarded'); } catch (e) { E.err = srv(e.message); }
E.busy = false; render();
}
// ---------- khởi động ----------
paintButton();
mountButton();
window.addEventListener('lumreels:lang', () => { paintButton(); if (dlg.open) render(); });
window.LumLearn = { open };
})();