import { GIFEncoder, quantize, applyPalette } from 'gifenc';
import { num, text, choice, color, canvas, source, fit, png, json, plain, file, zip, pixels, dimensions } from './common.js';

const grid = () => [num('cols', '列数', 4, 1, 16), num('rows', '行数', 4, 1, 16)];
const fields = {
  'favicon-maker': [color('background', '背景色', '#ffffff')], 'app-icon-pack': [color('background', '背景色', '#ffffff')],
  'sprite-sheet': [num('cols', '列数', 4, 1, 8), num('size', '单元边长(px)', 128, 16, 1024), num('gap', '单元间距(px)', 2, 0, 64)],
  'sprite-slicer': grid(), 'images-pdf': [choice('paper', '页面', [['a4', 'A4'], ['image', '原始像素尺寸']])],
  'gif-extract': [], 'gif-inspect': [], 'sprite-animation': [...grid(), num('delay', '每帧延时(ms)', 150, 20, 5000, 10)],
  'image-data-url': [choice('mode', '操作', [['encode', '图片编码'], ['decode', 'Data URL 还原']]), { ...text('data', 'Data URL(解码时填写)', 'data:image/png;base64,', true), maxLength: 2_000_000 }],
  'image-pack': [text('prefix', '文件名前缀', 'image')],
};
async function ico(entries) {
  const arrays = await Promise.all(entries.map((e) => e.blob.arrayBuffer())); const header = new Uint8Array(6 + entries.length * 16), view = new DataView(header.buffer); view.setUint16(2, 1, true); view.setUint16(4, entries.length, true); let offset = header.length;
  arrays.forEach((buffer, i) => { const p = 6 + i * 16; header[p] = header[p + 1] = entries[i].size === 256 ? 0 : entries[i].size; view.setUint16(p + 4, 1, true); view.setUint16(p + 6, 32, true); view.setUint32(p + 8, buffer.byteLength, true); view.setUint32(p + 12, offset, true); offset += buffer.byteLength; });
  return file(new Blob([header, ...arrays], { type: 'image/x-icon' }), 'favicon.ico');
}
export function getImplementation(id) {
  return { fields: fields[id], async run({ values: v, images, files }) {
    if (id === 'gif-extract' || id === 'gif-inspect') { const { inspectGIF } = await import('./gif.js'); return inspectGIF(files[0], id === 'gif-extract'); }
    if (id === 'image-data-url') {
      if (v.mode === 'encode') { if (!files[0]) throw new Error('请先选择图片。'); const data = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(files[0]); }); return [plain(data, 'image-data-url.txt')]; }
      const match = v.data.trim().match(/^data:(image\/(?:png|jpeg|webp|gif|bmp|avif));base64,([A-Za-z0-9+/]+={0,2})$/); if (!match || match[2].length % 4 !== 0) throw new Error('只接受有效的 PNG / JPEG / WebP / GIF / BMP / AVIF Base64 Data URL。');
      let bytes; try { bytes = Uint8Array.from(atob(match[2]), (c) => c.charCodeAt(0)); } catch { throw new Error('Base64 编码无效。'); } const blob = new Blob([bytes], { type: match[1] }), url = URL.createObjectURL(blob), image = new Image();
      try { image.src = url; await image.decode(); dimensions(image.naturalWidth, image.naturalHeight); } catch { throw new Error('Data URL 不是有效图片或尺寸超限。'); } finally { URL.revokeObjectURL(url); }
      return [file(blob, `decoded.${match[1].split('/')[1]}`)];
    }
    if (id === 'image-pack') {
      if (!/^[a-zA-Z0-9_-]{1,40}$/.test(v.prefix)) throw new Error('文件名前缀只允许 1–40 个英文字母、数字、下划线或短横线。'); const entries = [], manifest = [];
      for (let i = 0; i < files.length; i++) { const f = files[i], name = `${v.prefix}-${String(i + 1).padStart(3, '0')}.${f.type === 'image/jpeg' ? 'jpg' : f.type.split('/')[1]}`, hash = [...new Uint8Array(await crypto.subtle.digest('SHA-256', await f.arrayBuffer()))].map((b) => b.toString(16).padStart(2, '0')).join(''); entries.push(file(f, name)); manifest.push({ original: f.name, name, bytes: f.size, sha256: hash }); } entries.push(json(manifest, 'manifest.json')); return [await zip(entries, 'images.zip')];
    }
    if (id === 'images-pdf') {
      const { PDFDocument } = await import('pdf-lib'); const { pdfFile } = await import('./pdf.js'); const doc = await PDFDocument.create();
      for (const image of images) { const node = source([image]), embedded = await doc.embedPng(await (await png(node)).blob.arrayBuffer()), w = v.paper === 'a4' ? 595.276 : image.width, h = v.paper === 'a4' ? 841.89 : image.height, margin = v.paper === 'a4' ? 18 : 0, scale = Math.min((w - margin * 2) / image.width, (h - margin * 2) / image.height); doc.addPage([w, h]).drawImage(embedded, { x: (w - image.width * scale) / 2, y: (h - image.height * scale) / 2, width: image.width * scale, height: image.height * scale }); } return [await pdfFile(doc, 'images.pdf')];
    }
    const original = source(images), w = original.width, h = original.height;
    if (id === 'favicon-maker' || id === 'app-icon-pack') {
      const sizes = id === 'favicon-maker' ? [16, 32, 48, 180, 192, 256, 512] : [48, 72, 96, 144, 192, 512, 180, 1024], entries = [];
      for (const size of sizes) { const node = canvas(size, size, v.background); fit(node.getContext('2d'), images[0], 0, 0, size, size); entries.push({ ...await png(node, `icon-${size}.png`), size }); }
      if (id === 'favicon-maker') { entries.push(await ico(entries.filter((e) => [16, 32, 48, 256].includes(e.size)))); entries.push(plain('<link rel="icon" href="./favicon.ico">\n<link rel="apple-touch-icon" href="./icon-180.png">\n<link rel="manifest" href="./manifest.webmanifest">\n', 'head.html', 'text/plain')); }
      entries.push(json({ name: 'Application', short_name: 'App', display: 'standalone', icons: [192, 512].map((size) => ({ src: `icon-${size}.png`, sizes: `${size}x${size}`, type: 'image/png' })) }, 'manifest.webmanifest')); return [await zip(entries, 'icons.zip')];
    }
    if (id === 'sprite-sheet') {
      const rows = Math.ceil(images.length / v.cols), node = canvas(v.cols * v.size + (v.cols - 1) * v.gap, rows * v.size + (rows - 1) * v.gap), ctx = node.getContext('2d'), frames = [];
      images.forEach((im, i) => { const x = i % v.cols * (v.size + v.gap), y = Math.floor(i / v.cols) * (v.size + v.gap); fit(ctx, im, x, y, v.size, v.size); frames.push({ source: im.file.name, x, y, width: v.size, height: v.size }); }); return [await png(node, 'sprites.png'), json({ width: node.width, height: node.height, frames }, 'sprites.json')];
    }
    if (w % v.cols || h % v.rows) throw new Error('图片宽高必须能被列数和行数整除。');
    const fw = w / v.cols, fh = h / v.rows, count = v.cols * v.rows; if (count > 100 || fw * fh * count > 16_000_000) throw new Error('最多 100 帧,累计帧像素不超过 16 MP。');
    const entries = [], gif = id === 'sprite-animation' ? GIFEncoder() : null;
    for (let i = 0; i < count; i++) {
      const frame = canvas(fw, fh, gif ? '#ffffff' : undefined); frame.getContext('2d').drawImage(original, i % v.cols * fw, Math.floor(i / v.cols) * fh, fw, fh, 0, 0, fw, fh);
      if (gif) { const rgba = pixels(frame).data, palette = quantize(rgba, 256), indexed = applyPalette(rgba, palette); gif.writeFrame(indexed, fw, fh, { palette, delay: v.delay, repeat: 0 }); }
      else entries.push(await png(frame, `frame-${String(i + 1).padStart(3, '0')}.png`));
    }
    if (gif) { gif.finish(); return [file(new Blob([gif.bytes()], { type: 'image/gif' }), 'animation.gif', '白色背景 · 无限循环')]; }
    entries.push(json({ frameWidth: fw, frameHeight: fh, columns: v.cols, rows: v.rows, order: 'row-major' }, 'frames.json')); return [await zip(entries, 'sprites.zip')];
  } };
}