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.5 KB
Raw Blame
// Gói mẫu .lumpack: hộp "Nhập gói" (chọn file → xem trước → Cài) và trang "Gói của tôi" (xem, gỡ, xuất).
// API: packs/http.mjs. L9: MỌI chữ lấy từ gói (tên, tác giả, liên hệ, mô tả, guidance) chỉ đi vào textContent;
// không innerHTML, không href/src/style lấy từ gói (ảnh do server ghép từ id/slug đã kiểm).
// Báo cho app.js / edit-panel.js bằng sự kiện window 'lumreels:packs' {detail:{show?, removed?}}.
(() => {
  const I = window.I18N;
  const t = (k, v) => I.t(k, v);
  const $ = (s, r = document) => r.querySelector(s);
  function h(tag, props = {}, ...kids) {
    const el = document.createElement(tag);
    if (props.class) el.className = props.class;
    if (props.text != null) el.textContent = props.text;
    for (const [k, v] of Object.entries(props.attrs || {})) if (v != null && v !== false) el.setAttribute(k, v === true ? '' : String(v));
    for (const [k, v] of Object.entries(props.data || {})) el.dataset[k] = String(v);
    for (const [k, v] of Object.entries(props.on || {})) el.addEventListener(k, v);
    for (const c of kids.flat()) if (c != null && c !== false) el.append(c instanceof Node ? c : document.createTextNode(String(c)));
    return el;
  }
  const btn = (cls, text, on, attrs = {}) => h('button', { class: cls, text, on: { click: on }, attrs: { type: 'button', ...attrs } });
  const fmtKB = (b) => `${Math.max(1, Math.round(b / 1024))} KB`;
  const KINDS = ['template', 'edit-style'];
  const kindLabel = (k) => t('kind.' + (KINDS.includes(k) ? k : 'template'));
  const PROV = ['original', 'own-video', 'style-study'];
  const notify = (detail = {}) => window.dispatchEvent(new CustomEvent('lumreels:packs', { detail }));

  /** Chữ guidance có tô vàng các từ cần đọc kỹ (mark), dựng bằng nút chữ — không bao giờ phân tích như HTML. */
  function markedText(text, words) {
    const pre = h('pre', { class: 'pk-text' });
    const list = (words || []).filter(Boolean).map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
    if (!list.length) { pre.textContent = text; return pre; }
    let re;
    try { re = new RegExp(`(^|[^\\p{L}\\p{N}])(${list.join('|')})(?=$|[^\\p{L}\\p{N}])`, 'giu'); } catch { pre.textContent = text; return pre; }
    let last = 0; let m;
    while ((m = re.exec(text))) {
      const start = m.index + m[1].length;
      if (start > last) pre.append(document.createTextNode(text.slice(last, start)));
      pre.append(h('mark', { text: m[2] }));
      last = start + m[2].length;
      if (m[0].length === 0) re.lastIndex++;
    }
    if (last < text.length) pre.append(document.createTextNode(text.slice(last)));
    return pre;
  }
  function metaRow(label, value) {
    if (value == null || value === '') return null;
    return h('div', { class: 'pk-meta-row' }, h('dt', { text: label }), h('dd', { text: value }));
  }
  function thumbEl(src) {
    return src ? h('img', { class: 'pk-thumb', attrs: { src, alt: '', loading: 'lazy', decoding: 'async', width: 72, height: 128 } }) : h('span', { class: 'pk-thumb ph', attrs: { 'aria-hidden': 'true' } });
  }

  // ================================================================================================================
  // Hộp "Nhập gói"
  // ================================================================================================================
  const imp = { dlg: null, body: null, view: null, file: null, busy: false, replace: false, done: null };
  function importDialog() {
    if (imp.dlg) return imp.dlg;
    const title = h('h2', { class: 'pk-h', text: t('pk.title'), attrs: { id: 'pkTitle' } });
    imp.body = h('div', { class: 'pk-body' });
    imp.dlg = h('dialog', { class: 'pk-dlg', attrs: { id: 'packDlg', 'aria-labelledby': 'pkTitle' } },
      h('div', { class: 'pk-head' }, title, btn('x', '×', () => closeImport(), { 'aria-label': t('pk.close'), 'data-i18n-aria': 'pk.close' })),
      imp.body);
    imp.dlg.addEventListener('cancel', (e) => { if (imp.busy) e.preventDefault(); });
    imp.dlg.addEventListener('close', () => { imp.view = null; imp.file = null; imp.done = null; });
    document.body.append(imp.dlg);
    return imp.dlg;
  }
  function openImport() {
    importDialog();
    imp.view = null; imp.done = null; imp.replace = false;
    renderImport('pick');
    if (!imp.dlg.open) imp.dlg.showModal();
  }
  function closeImport() { if (!imp.busy && imp.dlg?.open) imp.dlg.close(); }

  let impState = 'pick'; let impErr = null;
  function renderImport(state = impState, err = impErr) {
    impState = state; impErr = err;
    if (!imp.body) return;
    $('#pkTitle').textContent = t('pk.title');
    const b = imp.body;
    if (state === 'pick') return b.replaceChildren(pickView(err));
    if (state === 'reading') return b.replaceChildren(h('div', { class: 'pk-load', text: t('pk.reading'), attrs: { role: 'status' } }));
    if (state === 'done') return b.replaceChildren(doneView());
    b.replaceChildren(previewView());
  }

  function pickView(err) {
    const input = h('input', { attrs: { type: 'file', accept: '.lumpack,application/json', id: 'pkFile', hidden: true } });
    input.addEventListener('change', () => { if (input.files[0]) inspect(input.files[0]); });
    const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    icon.setAttribute('viewBox', '0 0 24 24'); icon.setAttribute('aria-hidden', 'true');
    const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', 'M12 16V4m0 0-4 4m4-4 4 4M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3'); icon.append(path);
    const drop = h('div', { class: 'pk-drop', attrs: { role: 'button', tabindex: 0, 'aria-describedby': 'pkDropHint' } },
      icon, h('span', { class: 'big', text: t('pk.dropBig') }), h('span', { class: 'small', text: t('pk.dropSmall'), attrs: { id: 'pkDropHint' } }));
    drop.addEventListener('click', () => input.click());
    drop.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); input.click(); } });
    drop.addEventListener('dragover', (e) => { e.preventDefault(); drop.classList.add('over'); });
    drop.addEventListener('dragleave', () => drop.classList.remove('over'));
    drop.addEventListener('drop', (e) => { e.preventDefault(); drop.classList.remove('over'); const f = e.dataTransfer?.files?.[0]; if (f) inspect(f); });
    const kids = [drop, input, h('p', { class: 'pk-note', text: t('pk.restricted') })];
    if (err) kids.unshift(h('div', { class: 'pk-err', text: err, attrs: { role: 'alert' } }));
    return h('div', {}, kids);
  }

  async function inspect(file) {
    imp.file = file;
    if (file.size > 12 * 1024 * 1024) return renderImport('pick', t('pk.err.not-pack') + ' ' + t('pk.err.tooBig'));
    renderImport('reading');
    const fd = new FormData();
    fd.append('file', file, 'pack.lumpack');
    try {
      const r = await fetch('/api/packs/inspect', { method: 'POST', body: fd });
      const j = await r.json().catch(() => ({}));
      if (!r.ok) return renderImport('pick', j.code ? t('pk.err.' + j.code) : (j.error || t('err.status', { s: r.status })));
      imp.view = j; imp.replace = false;
      renderImport('preview');
      $('.pk-dlg .pk-body')?.scrollTo?.(0, 0);
    } catch { renderImport('pick', t('pk.err.net')); }
  }

  function statusBox(v) {
    if (!v.ok) {
      const box = h('div', { class: 'pk-err', attrs: { role: 'alert' } },
        h('strong', { text: t('pk.err.' + (v.code || 'rejected')) }), h('div', { text: t('pk.err.first', { e: v.errors[0] }) }));
      if (v.errors.length > 1) {
        box.append(h('details', {}, h('summary', { text: t('pk.err.more', { n: v.errors.length }) }), h('ul', {}, v.errors.map((e) => h('li', { text: e })))));
      }
      return box;
    }
    const st = v.install?.state;
    if (st && st !== 'new') {
      const box = h('div', { class: 'pk-warn' + (st === 'upgrade' ? '' : ' bad'), attrs: { role: 'status' } }, t('pk.st.' + st, { v: v.install.installedVersion, id: v.pack.id }));
      if (st === 'upgrade') {
        const cb = h('input', { attrs: { type: 'checkbox', id: 'pkReplace' } });
        cb.checked = imp.replace;
        cb.addEventListener('change', () => { imp.replace = cb.checked; renderImport('preview'); });
        box.append(h('label', { class: 'pk-check', attrs: { for: 'pkReplace' } }, cb, ' ', t('pk.replace', { v: v.pack.version })));
      }
      return box;
    }
    return null;
  }

  function previewView() {
    const v = imp.view;
    const p = v.pack || {};
    const name = (I.lang === 'en' && p.nameEn) || p.name || t('pk.noName');
    const head = h('div', { class: 'pk-sum' },
      h('div', { class: 'pk-name' }, h('span', { class: 'src src-pack', text: t('src.pack') }), h('span', { class: 'n', text: name }), p.version ? h('span', { class: 'v', text: 'v' + p.version }) : null),
      p.description ? h('p', { class: 'pk-desc', text: p.description }) : null,
      h('dl', { class: 'pk-meta' },
        metaRow(t('pk.author'), p.author?.name), metaRow(t('pk.contact'), p.author?.contact), metaRow(t('pk.license'), p.license),
        metaRow(t('pk.provenance'), PROV.includes(p.provenance) ? t('prov.' + p.provenance) : p.provenance), metaRow(t('pk.id'), p.id),
        metaRow(t('pk.engine'), p.engineMin ? '≥ ' + p.engineMin : null), metaRow(t('pk.items'), String(v.items.length)),
        metaRow(t('pk.sha'), v.fileSha256 ? v.fileSha256.slice(0, 16) + '…' : null)));
    const kids = [head, statusBox(v), h('p', { class: 'pk-note lock', text: t('pk.restricted') })];
    const warnItems = v.items.filter((x) => x.warnings?.length).length;
    if (warnItems) kids.push(h('div', { class: 'pk-warn', text: t('pk.warnHead', { n: warnItems }) }));
    const list = h('ul', { class: 'pk-items', attrs: { 'aria-label': t('pk.items') } }, v.items.map((it) => {
      const warn = it.warnings?.length ? h('span', { class: 'pk-wtag', text: t('pk.warnItem') }) : null;
      const det = h('details', { class: 'pk-item-text' }, h('summary', { text: t('pk.showText') }), markedText(it.text, v.warnWords));
      if (it.warnings?.length) det.open = v.items.length <= 3;
      return h('li', { class: 'pk-item' },
        thumbEl(it.thumb),
        h('div', { class: 'pk-item-main' },
          h('div', { class: 'pk-item-h' }, h('span', { class: 'k', text: kindLabel(it.kind) }), h('span', { class: 't', text: it.name }), warn),
          h('div', { class: 'pk-item-ref', text: p.id ? `${p.id}/${it.slug}` : it.slug }),
          it.blurb ? h('div', { class: 'pk-item-b', text: it.blurb }) : null,
          it.warnings?.length ? h('div', { class: 'pk-item-w', text: it.warnings.join(' · ') }) : null,
          det));
    }));
    kids.push(list);
    const can = v.canInstall && (v.install.state !== 'upgrade' || imp.replace);
    const err = h('p', { class: 'err', attrs: { id: 'pkInstallErr', role: 'alert' } });
    const go = btn('pk-go', t(imp.busy ? 'pk.installing' : 'pk.install'), () => install(go, err), can && !imp.busy ? {} : { disabled: true });
    kids.push(h('div', { class: 'pk-actions' }, btn('pk-btn', t('pk.cancel'), () => closeImport(), imp.busy ? { disabled: true } : {}),
      btn('pk-btn', t('pk.other'), () => renderImport('pick', null), imp.busy ? { disabled: true } : {}), go), err);
    return h('div', {}, kids);
  }

  async function install(go, errEl) {
    if (imp.busy || !imp.view) return;
    imp.busy = true; go.disabled = true; go.textContent = t('pk.installing');
    try {
      const r = await fetch('/api/packs/install', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ fileSha256: imp.view.fileSha256, replace: imp.replace }) });
      const j = await r.json().catch(() => ({}));
      if (!r.ok) {
        const v = imp.view.install?.installedVersion || '';
        const msg = j.code === 'expired' ? t('pk.err.expired') : ['installed', 'conflict', 'older', 'upgrade'].includes(j.code) ? t('pk.st.' + j.code, { v, id: imp.view.pack?.id })
          : ['not-pack', 'engine', 'rejected'].includes(j.code) ? t('pk.err.' + j.code) : (j.error || t('err.status', { s: r.status }));
        throw new Error(msg);
      }
      imp.done = j;
      imp.busy = false;
      notify({});
      renderImport('done');
    } catch (e) {
      imp.busy = false;
      renderImport('preview');
      const el = $('#pkInstallErr'); if (el) el.textContent = e.message === 'Failed to fetch' ? t('pk.err.net') : e.message;
    }
  }

  function doneView() {
    const m = imp.done || {};
    const local = String(m.id || '').startsWith('local.');
    return h('div', { class: 'pk-done', attrs: { role: 'status' } },
      h('div', { class: 'pk-done-ic', attrs: { 'aria-hidden': 'true' }, text: '✓' }),
      h('p', { class: 'pk-done-t', text: t('pk.done', { name: m.name || m.id, n: m.itemCount || 0 }) }),
      h('div', { class: 'pk-actions' },
        btn('pk-btn', t('pk.close'), () => closeImport()),
        btn('pk-go', t('pk.showGrid'), () => { closeImport(); showTplTab(); notify({ show: local ? 'local' : 'pack' }); })));
  }
  function showTplTab() { document.querySelector('.tab[data-tab="tpl"]')?.click(); }

  // ================================================================================================================
  // Trang "Gói của tôi"
  // ================================================================================================================
  const mine = { dlg: null, body: null, data: null, state: 'loading', open: new Set(), details: new Map(), confirm: null, exporting: false, exp: null, msg: null };
  function mineDialog() {
    if (mine.dlg) return mine.dlg;
    mine.body = h('div', { class: 'pk-body' });
    mine.dlg = h('dialog', { class: 'pk-dlg', attrs: { id: 'packsDlg', 'aria-labelledby': 'mpTitle' } },
      h('div', { class: 'pk-head' }, h('h2', { class: 'pk-h', text: t('mp.title'), attrs: { id: 'mpTitle' } }),
        btn('x', '×', () => mine.dlg.close(), { 'aria-label': t('pk.close'), 'data-i18n-aria': 'pk.close' })),
      mine.body);
    document.body.append(mine.dlg);
    return mine.dlg;
  }
  async function openMine() {
    mineDialog();
    mine.confirm = null; mine.exp = null; mine.msg = null;
    if (!mine.dlg.open) mine.dlg.showModal();
    await loadMine();
  }
  async function loadMine() {
    mine.state = 'loading'; renderMine();
    try {
      const r = await fetch('/api/packs');
      if (!r.ok) throw new Error();
      mine.data = await r.json();
      mine.state = 'ok';
    } catch { mine.state = 'error'; }
    renderMine();
  }
  function renderMine() {
    if (!mine.body) return;
    $('#mpTitle').textContent = t('mp.title');
    const kids = [];
    if (mine.msg) kids.push(h('div', { class: 'pk-ok', text: mine.msg, attrs: { role: 'status' } }));
    kids.push(h('div', { class: 'mp-top' }, btn('pk-btn', t('pack.importBtn'), () => { mine.dlg.close(); openImport(); }),
      btn('pk-btn' + (mine.exp ? ' on' : ''), t('mp.export'), () => { mine.exp = mine.exp ? null : { picked: new Set() }; renderMine(); }, { 'aria-expanded': String(!!mine.exp) })));
    if (mine.exp) kids.push(exportView());
    if (mine.state === 'loading') kids.push(h('div', { class: 'pk-load', text: t('mp.loading') }));
    else if (mine.state === 'error') kids.push(h('div', { class: 'pk-err', text: t('mp.loadErr') }), btn('pk-btn', t('mp.retry'), loadMine));
    else if (!mine.data.packs.length) kids.push(h('div', { class: 'mp-empty' }, h('p', { text: t('mp.empty') }), btn('pk-go', t('pack.importBtn'), () => { mine.dlg.close(); openImport(); })));
    else kids.push(h('ul', { class: 'mp-list' }, mine.data.packs.map(packCard)));
    mine.body.replaceChildren(...kids);
  }
  function packCard(p) {
    const local = p.source === 'local';
    const name = (I.lang === 'en' && p.nameEn) || p.name;
    const open = mine.open.has(p.id);
    const head = h('div', { class: 'mp-h' },
      h('span', { class: 'src src-' + (local ? 'local' : 'pack'), text: t(local ? 'src.local' : 'src.pack') }),
      p.verified ? h('span', { class: 'src src-ok', text: t('mp.verified') }) : null,
      h('span', { class: 'n', text: name }), h('span', { class: 'v', text: 'v' + p.version }));
    const sub = h('div', { class: 'mp-sub', text: [p.id, p.author?.name, p.license, t('mp.items', { n: p.itemCount })].filter(Boolean).join(' · ') });
    const acts = h('div', { class: 'mp-acts' },
      btn('pk-btn', t(open ? 'mp.hide' : 'mp.view'), () => toggleView(p.id), { 'aria-expanded': String(open) }),
      local ? null : btn('pk-btn danger', t('mp.remove'), () => { mine.confirm = { type: 'pack', id: p.id, name }; renderMine(); }));
    const card = h('li', { class: 'mp-card' }, head, sub, acts);
    if (mine.confirm?.type === 'pack' && mine.confirm.id === p.id) card.append(confirmBox(t('mp.removeQ', { name }), t('mp.removeYes'), () => removePack(p.id, name)));
    if (open) {
      if (p.description) card.append(h('p', { class: 'pk-desc', text: p.description }));
      if (p.author?.contact) card.append(h('p', { class: 'mp-sub', text: t('pk.contact') + ': ' + p.author.contact }));
      const det = mine.details.get(p.id);
      card.append(h('ul', { class: 'pk-items' }, p.items.map((it) => {
        const full = det?.items?.find((x) => x.kind === it.kind && x.slug === it.slug);
        const li = h('li', { class: 'pk-item' }, thumbEl(it.thumb), h('div', { class: 'pk-item-main' },
          h('div', { class: 'pk-item-h' }, h('span', { class: 'k', text: kindLabel(it.kind) }), h('span', { class: 't', text: it.name })),
          h('div', { class: 'pk-item-ref', text: it.ref }),
          full ? h('details', { class: 'pk-item-text' }, h('summary', { text: t('pk.showText') }), markedText(full.text, det.warnWords)) : null,
          local ? btn('pk-btn danger sm', t('mp.delItem'), () => { mine.confirm = { type: 'item', id: p.id, kind: it.kind, slug: it.slug, name: it.name }; renderMine(); }) : null));
        if (mine.confirm?.type === 'item' && mine.confirm.id === p.id && mine.confirm.slug === it.slug && mine.confirm.kind === it.kind) {
          li.append(confirmBox(t('mp.delItemQ', { name: it.name }), t('mp.delItem'), () => removeItem(p.id, it.kind, it.slug, it.name)));
        }
        return li;
      })));
    }
    return card;
  }
  function confirmBox(q, yes, fn) {
    const err = h('p', { class: 'err', attrs: { role: 'alert' } });
    return h('div', { class: 'mp-confirm', attrs: { role: 'group' } }, h('p', { text: q }),
      h('div', { class: 'pk-actions' }, btn('pk-btn', t('pk.cancel'), () => { mine.confirm = null; renderMine(); }),
        btn('pk-go danger', yes, async (e) => { e.target.disabled = true; try { await fn(); } catch (x) { err.textContent = x.message; e.target.disabled = false; } })), err);
  }
  async function toggleView(id) {
    if (mine.open.has(id)) { mine.open.delete(id); renderMine(); return; }
    mine.open.add(id); renderMine();
    if (!mine.details.has(id)) {
      try { const r = await fetch('/api/packs/' + encodeURIComponent(id)); if (r.ok) { mine.details.set(id, await r.json()); renderMine(); } } catch { /* bỏ qua: vẫn có danh sách mục */ }
    }
  }
  async function del(url) {
    const r = await fetch(url, { method: 'DELETE' });
    const j = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(j.error || t('err.status', { s: r.status }));
    return j;
  }
  async function removePack(id, name) {
    await del('/api/packs/' + encodeURIComponent(id));
    mine.confirm = null; mine.open.delete(id); mine.details.delete(id);
    mine.msg = t('mp.removed', { name });
    notify({ removed: id });
    await loadMine();
  }
  async function removeItem(id, kind, slug, name) {
    await del(`/api/packs/${encodeURIComponent(id)}/items/${encodeURIComponent(kind)}/${encodeURIComponent(slug)}`);
    mine.confirm = null; mine.details.delete(id);
    mine.msg = t('mp.deleted', { name });
    notify({ removed: `${id}/${slug}` });
    await loadMine();
  }

  // ---- Xuất gói (chỉ mục "Của tôi") ----
  const slugify = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/gi, 'd').toLowerCase()
    .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 24).replace(/-+$/, '');
  const ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*\.[a-z0-9]+(?:-[a-z0-9]+)*$/;
  function exportView() {
    const ex = mine.exp;
    const packs = (mine.data?.packs || []).filter((p) => p.source === 'local');
    const items = packs.flatMap((p) => p.items);
    const box = h('form', { class: 'mp-export', attrs: { novalidate: true, 'aria-labelledby': 'exTitle' } });
    box.append(h('h3', { class: 'pk-h3', text: t('ex.title'), attrs: { id: 'exTitle' } }));
    if (mine.state === 'ok' && !items.length) { box.append(h('p', { class: 'mp-empty-t', text: t('ex.none') })); return box; }
    const fs = h('fieldset', { class: 'ex-items' }, h('legend', { text: t('ex.pick') }));
    for (const it of items) {
      const key = `${it.kind === 'template' ? 'template' : 'style'}:${it.ref}`;
      const cb = h('input', { attrs: { type: 'checkbox', value: key } });
      cb.checked = ex.picked.has(key);
      cb.addEventListener('change', () => { if (cb.checked) ex.picked.add(key); else ex.picked.delete(key); });
      fs.append(h('label', { class: 'pk-check' }, cb, ' ', h('span', { text: `${kindLabel(it.kind)}: ${it.name}` })));
    }
    const field = (id, label, input, hint) => h('div', { class: 'ex-f' }, h('label', { class: 'field', text: label, attrs: { for: id } }), input, hint ? h('div', { class: 'hint', text: hint }) : null);
    const inp = (id, val, extra = {}) => { const i = h('input', { class: 'ed-in', attrs: { id, type: 'text', autocomplete: 'off', spellcheck: 'false', ...extra } }); i.value = val || ''; return i; };
    const nameI = inp('exName', ex.name, { maxlength: 60 });
    const authorI = inp('exAuthor', ex.author, { maxlength: 60 });
    const idI = inp('exId', ex.id, { maxlength: 49, inputmode: 'url', pattern: ID_RE.source });
    const contactI = inp('exContact', ex.contact, { maxlength: 100 });
    const verI = inp('exVer', ex.version || '1.0.0', { maxlength: 14, inputmode: 'decimal' });
    const lic = h('select', { attrs: { id: 'exLic' } }, (mine.data?.licenses || ['CC-BY-4.0']).map((l) => { const o = h('option', { text: l, attrs: { value: l } }); if (l === (ex.license || 'CC-BY-4.0')) o.selected = true; return o; }));
    const autoId = () => { if (!ex.idTouched) { const a = slugify(authorI.value); const n = slugify(nameI.value); idI.value = a.length >= 2 && n.length >= 2 ? `${a}.${n}` : ''; } };
    nameI.addEventListener('input', () => { ex.name = nameI.value; autoId(); ex.id = idI.value; });
    authorI.addEventListener('input', () => { ex.author = authorI.value; autoId(); ex.id = idI.value; });
    idI.addEventListener('input', () => { ex.idTouched = true; ex.id = idI.value; });
    contactI.addEventListener('input', () => { ex.contact = contactI.value; });
    verI.addEventListener('input', () => { ex.version = verI.value; });
    lic.addEventListener('change', () => { ex.license = lic.value; });
    const err = h('p', { class: 'err', attrs: { role: 'alert', id: 'exErr' } });
    const go = h('button', { class: 'pk-go', text: t(mine.exporting ? 'ex.busy' : 'ex.go'), attrs: { type: 'submit' } });
    box.append(fs,
      h('div', { class: 'ex-grid' },
        field('exName', t('ex.name'), nameI), field('exAuthor', t('ex.author'), authorI),
        field('exId', t('ex.id'), idI, t('ex.idHint')), field('exContact', t('ex.contact'), contactI),
        field('exLic', t('ex.license'), lic), field('exVer', t('ex.version'), verI)),
      h('div', { class: 'pk-actions' }, go), err);
    box.addEventListener('submit', async (e) => {
      e.preventDefault();
      err.textContent = '';
      if (!ex.picked.size) { err.textContent = t('ex.err.items'); return; }
      if (!nameI.value.trim()) { err.textContent = t('ex.err.name'); nameI.focus(); return; }
      if (!authorI.value.trim()) { err.textContent = t('ex.err.author'); authorI.focus(); return; }
      if (!ID_RE.test(idI.value)) { err.textContent = t('ex.err.id'); idI.focus(); return; }
      if (!/^\d{1,4}\.\d{1,4}\.\d{1,4}$/.test(verI.value)) { err.textContent = t('ex.err.ver'); verI.focus(); return; }
      mine.exporting = true; go.disabled = true; go.textContent = t('ex.busy');
      try {
        const r = await fetch('/api/packs/export', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ id: idI.value, name: nameI.value.trim(), author: authorI.value.trim(), contact: contactI.value.trim() || undefined, license: lic.value, version: verI.value, items: [...ex.picked] }),
        });
        if (!r.ok) { const j = await r.json().catch(() => ({})); throw new Error(j.code === 'reserved' ? t('ex.err.reserved') : (j.error || t('err.status', { s: r.status }))); }
        const blob = await r.blob();
        const file = `${idI.value}-${verI.value}.lumpack`;
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a'); a.href = url; a.download = file; document.body.append(a); a.click(); a.remove();
        setTimeout(() => URL.revokeObjectURL(url), 30000);
        mine.msg = t('ex.ok', { file, kb: fmtKB(blob.size) });
        mine.exp = null;
      } catch (x) { err.textContent = x.message === 'Failed to fetch' ? t('pk.err.net') : x.message; }
      finally { mine.exporting = false; }
      if (!mine.exp) renderMine(); else { go.disabled = false; go.textContent = t('ex.go'); }
    });
    return box;
  }

  // ---- nút mở ----
  document.addEventListener('click', (e) => {
    if (e.target.closest?.('[data-pack-import]')) { e.preventDefault(); openImport(); }
    else if (e.target.closest?.('[data-packs-open]')) { e.preventDefault(); openMine(); }
  });
  window.addEventListener('lumreels:lang', () => {
    if (imp.dlg?.open) renderImport();
    if (mine.dlg?.open) renderMine();
    for (const d of [imp.dlg, mine.dlg]) if (d) I.apply(d);
  });
  window.LumPacks = { openImport, openMine };
})();