import gifenc from 'gifenc';
import { svgPathProperties } from 'svg-path-properties';
import { compositeGIF } from '../expansion/gif.js';
import { text, num, choice, color, assert, parseJSON, numeric, canvas, png, json, file, source, pixels, fit, rgb, svgDoc, svgResults } from './common.js';
const { GIFEncoder, quantize, applyPalette } = gifenc;
const background = () => color('background', '合成背景色', '#ffffff');
const frameCount = () => num('frames', '帧数', 12, 2, 40);
const duration = () => num('duration', '总时长(ms)', 1200, 100, 10000, 10);
function opaque(data, background) { const [r, g, b] = rgb(background), result = new Uint8ClampedArray(data); for (let i = 0; i < result.length; i += 4) { const a = result[i + 3] / 255; result[i] = result[i] * a + r * (1 - a); result[i + 1] = result[i + 1] * a + g * (1 - a); result[i + 2] = result[i + 2] * a + b * (1 - a); result[i + 3] = 255; } return result; }
async function encodeFrames(frames, background, repeat = 0) {
  assert(frames.length && frames.length <= 100 && frames.reduce((n, f) => n + f.data.width * f.data.height, 0) <= 24e6, '动画最多100帧、累计24MP。'); const encoder = GIFEncoder();
  for (const frame of frames) { const data = opaque(frame.data.data, background), palette = quantize(data, 256), index = applyPalette(data, palette); encoder.writeFrame(index, frame.data.width, frame.data.height, { palette, delay: frame.delay, repeat, dispose: 1 }); await new Promise((resolve) => setTimeout(resolve, 0)); }
  encoder.finish(); return file(new Blob([encoder.bytes()], { type: 'image/gif' }), 'animation.gif');
}
export const gif_editor = /*#__PURE__*/ (() => ({ fields: [num('start', '起始帧(含)', 1, 1, 100), num('end', '结束帧(0表示最后)', 0, 0, 100), num('speed', '播放速度倍数', 1, .25, 4, .25), choice('direction', '顺序', [['forward', '原顺序'], ['reverse', '倒序']]), num('repeat', '循环次数(0无限;−1一次)', 0, -1, 100), background()], async run({ files, values: v }) {
  const decoded = await compositeGIF(files[0]), end = v.end || decoded.frames.length; assert(v.start <= end && end <= decoded.frames.length, '所选帧区间超出输入。'); let frames = decoded.frames.slice(v.start - 1, end).map((f) => ({ data: f.data, delay: Math.max(20, Math.round(f.delay / v.speed / 10) * 10) })); if (v.direction === 'reverse') frames.reverse();
  return [await encodeFrames(frames, v.background, v.repeat), json({ inputFrames: decoded.frames.length, outputFrames: frames.length, delays: frames.map((f) => f.delay), durationMs: frames.reduce((n, f) => n + f.delay, 0), repeat: v.repeat }, 'edit-report.json')];
} }))();
export const gif_sprite = /*#__PURE__*/ (() => ({ fields: [num('columns', '图集列数', 4, 1, 20)], async run({ files, values: v }) {
  const { metadata: m, frames } = await compositeGIF(files[0]), columns = Math.min(v.columns, frames.length), rows = Math.ceil(frames.length / columns); assert(columns * m.width <= 4096 && rows * m.height <= 4096 && columns * m.width * rows * m.height <= 16e6, '图集超过4096px或16MP,请减少GIF尺寸或帧数。');
  const node = canvas(columns * m.width, rows * m.height), ctx = node.getContext('2d'), report = frames.map((f, i) => { const x = i % columns * m.width, y = Math.floor(i / columns) * m.height; ctx.putImageData(f.data, x, y); return { name: `frame-${i + 1}`, x, y, width: m.width, height: m.height, delay: f.delay }; });
  return [await png(node, 'gif-atlas.png'), json({ width: node.width, height: node.height, frames: report, loopCount: m.loopCount }, 'gif-atlas.json')];
} }))();
export const gif_compare = /*#__PURE__*/ (() => ({ fields: [num('threshold', '通道差阈值', 0, 0, 255), background()], async run({ files, values: v }) {
  assert(files.length === 2, '请选择两份GIF。'); const a = await compositeGIF(files[0]), b = await compositeGIF(files[1]); assert(a.metadata.width === b.metadata.width && a.metadata.height === b.metadata.height, '两份GIF尺寸必须一致。'); const w = a.metadata.width, h = a.metadata.height;
  const boundaries = (frames) => { let t = 0; return [0, ...frames.map((f) => t += f.delay)]; }, ta = boundaries(a.frames), tb = boundaries(b.frames), total = Math.max(ta.at(-1), tb.at(-1)), times = [...new Set([...ta, ...tb])].filter((t) => t < total).sort((a, b) => a - b); assert(times.length <= 100 && times.length * w * h <= 24e6, '对齐后帧数或累计像素超限。');
  const pick = (animation, boundaries, t) => animation.frames[Math.max(0, Math.min(animation.frames.length - 1, boundaries.findLastIndex((n) => n <= t)))], frames = [], stats = [];
  for (const [i, t] of times.entries()) { const da = opaque(pick(a, ta, t).data.data, v.background), db = opaque(pick(b, tb, t).data.data, v.background), out = new ImageData(w, h); let changed = 0, sum = 0;
    for (let p = 0; p < da.length; p += 4) { const differences = [0, 1, 2].map((c) => Math.abs(da[p + c] - db[p + c])); const different = Math.max(...differences) > v.threshold; if (different) changed++; sum += differences.reduce((s, n) => s + n, 0); out.data.set(different ? [255, 60, 80, 255] : [245, 248, 246, 255], p); }
    const delay = (times[i + 1] ?? total) - t; frames.push({ data: out, delay }); stats.push({ timeMs: t, durationMs: delay, changedPixels: changed, ratio: changed / (w * h), meanChannelError: sum / (w * h * 3) }); }
  return [await encodeFrames(frames, '#ffffff', -1), json({ width: w, height: h, durationA: ta.at(-1), durationB: tb.at(-1), note: '各取一次播放;较短动画结束后保持末帧,不比较循环扩展。', intervals: stats }, 'gif-difference.json')];
} }))();
export const animation_crossfade = /*#__PURE__*/ (() => ({ fields: [frameCount(), duration(), background()], async run({ images, values: v }) {
  assert(images.length === 2 && images[0].width === images[1].width && images[0].height === images[1].height, '需两张同尺寸图片。'); const a = pixels(source(images)), b = pixels(source([images[1]])); assert(a.width * a.height * v.frames <= 24e6, '累计动画像素超过24MP。');
  const da = opaque(a.data, v.background), db = opaque(b.data, v.background), frames = []; const delay = Math.max(20, Math.round(v.duration / v.frames / 10) * 10);
  for (let f = 0; f < v.frames; f++) { const data = new ImageData(a.width, a.height), t = f / (v.frames - 1); for (let i = 0; i < data.data.length; i++) data.data[i] = da[i] * (1 - t) + db[i] * t; frames.push({ data, delay }); }
  return [await encodeFrames(frames, v.background), json({ frames: v.frames, requestedDurationMs: v.duration, actualDurationMs: delay * v.frames, startWeight: 0, endWeight: 1 }, 'crossfade.json')];
} }))();
export const animation_path = /*#__PURE__*/ (() => ({ fields: [text('path', 'SVG轨迹(512×384画布)', 'M80 280 Q256 40 432 280', true), num('size', '图像最长边(px)', 64, 8, 160), frameCount(), duration(), background()], async run({ images, values: v }) {
  source(images); assert(v.path.length <= 8000 && /^[MmZzLlHhVvCcSsQqTtAa\s\d.,eE+-]+$/.test(v.path), '路径字符无效。'); let path; try { path = new svgPathProperties(v.path); } catch { throw new Error('SVG轨迹语法无效。'); } const length = path.getTotalLength(); assert(length > 0 && length <= 10000, '轨迹长度无效。');
  const frames = [], positions = [], node = canvas(512, 384), ctx = node.getContext('2d'), delay = Math.max(20, Math.round(v.duration / v.frames / 10) * 10);
  for (let i = 0; i < v.frames; i++) { const p = path.getPointAtLength(i / (v.frames - 1) * length); assert(p.x >= v.size / 2 && p.x <= 512 - v.size / 2 && p.y >= v.size / 2 && p.y <= 384 - v.size / 2, '轨迹上的图片超出画布,请调整路径或缩小图像。'); ctx.fillStyle = v.background; ctx.fillRect(0, 0, 512, 384); fit(ctx, images[0], p.x - v.size / 2, p.y - v.size / 2, v.size, v.size); frames.push({ data: ctx.getImageData(0, 0, 512, 384), delay }); positions.push(p); }
  return [await encodeFrames(frames, v.background), json({ path: v.path, positions, frameDelayMs: delay, actualDurationMs: delay * v.frames }, 'motion-path.json')];
} }))();
export const gif_flipbook = /*#__PURE__*/ (() => ({ fields: [num('scale', '每像素对应PDF点数', 2, .5, 10, .5)], async run({ files, values: v }) {
  const { PDFDocument, StandardFonts } = await import('pdf-lib'), { pdfFile } = await import('../expansion/pdf.js'), { metadata: m, frames } = await compositeGIF(files[0]), doc = await PDFDocument.create(), font = await doc.embedFont(StandardFonts.Helvetica); assert(m.width * v.scale <= 4000 && m.height * v.scale <= 4000, 'PDF页面超过4000pt,请降低缩放。'); let time = 0;
  const node = canvas(m.width, m.height), ctx = node.getContext('2d');
  for (const [i, f] of frames.entries()) { ctx.putImageData(f.data, 0, 0); const pngFile = await png(node), embedded = await doc.embedPng(await pngFile.blob.arrayBuffer()), page = doc.addPage([Math.max(240, m.width * v.scale + 40), m.height * v.scale + 70]); page.drawImage(embedded, { x: 20, y: 40, width: m.width * v.scale, height: m.height * v.scale }); page.drawText(`Frame ${i + 1} | ${time} ms | ${f.delay} ms`, { x: 20, y: 18, size: 10, font }); time += f.delay; }
  return [await pdfFile(doc, 'flipbook.pdf'), json(m, 'flipbook-timing.json')];
} }))();
export const svg_animation = /*#__PURE__*/ (() => ({ fields: [choice('motion', '运动方式', [['rotate', '旋转'], ['translate', '水平往返'], ['scale', '缩放往返']]), num('duration', '周期(秒)', 2, .2, 20, .1), num('repeat', '重复次数(0无限)', 0, 0, 100), color('fill', '图形颜色', '#167d68')], async run({ values: v }) {
  const values = { rotate: '0;360', translate: '-100 0;100 0;-100 0', scale: '.5;1;.5' }[v.motion], body = `<g transform="translate(256 192)"><g><rect x="-60" y="-40" width="120" height="80" rx="12" fill="${v.fill}"/><circle cx="25" cy="-10" r="12" fill="white"/><animateTransform attributeName="transform" type="${v.motion}" values="${values}" dur="${v.duration}s" repeatCount="${v.repeat || 'indefinite'}"/></g></g>`;
  return [...await svgResults(svgDoc(body, 512, 384, 'SVG动画'), 'animated', false), json({ motion: v.motion, durationSeconds: v.duration, repeat: v.repeat, note: '使用SVG声明式动画;预览和播放需浏览器支持SMIL。' }, 'animation.json')];
} }))();
export const lottie_inspect = /*#__PURE__*/ (() => ({ fields: [], async run({ files }) {
  const data = parseJSON(await files[0].text()); assert(data && typeof data.v === 'string' && Array.isArray(data.layers), '不是有效Lottie文档:缺少版本或layers。');
  const width = numeric(data.w), height = numeric(data.h), rate = numeric(data.fr), from = numeric(data.ip), to = numeric(data.op); assert(width > 0 && height > 0 && width <= 16000 && height <= 16000 && rate > 0 && rate <= 240 && to > from, 'Lottie画布、帧率或时间区间无效。');
  const assets = (data.assets || []).map((a) => ({ id: a.id, path: a.p, directory: a.u, embedded: a.e === 1 || /^data:/.test(a.p || ''), layers: a.layers?.length || 0, remoteReference: /^https?:|^\/\//i.test((a.u || '') + (a.p || '')) }));
  const layers = data.layers.map((l) => ({ index: l.ind, name: l.nm, type: l.ty, parent: l.parent, asset: l.refId, in: l.ip, out: l.op, hidden: Boolean(l.hd) }));
  return [json({ version: data.v, name: data.nm, width, height, frameRate: rate, firstFrame: from, lastFrameExclusive: to, durationSeconds: (to - from) / rate, layers, assets, note: '只检查结构,不渲染动画、不加载资源、不执行表达式。' }, 'lottie-report.json')];
} }))();