import { quantize, applyPalette } from 'gifenc';
import { num, color, choice, canvas, source, pixels, png, zip, json, rgb, luminance, fit, requireCount } from './common.js';

const n = num; const c = color; const s = choice;
const fields = {
  'image-orient': [n('angle', '顺时针角度', 90, -360, 360), s('flip', '镜像', [['none', '无'], ['x', '水平'], ['y', '垂直']])],
  'image-border': [n('size', '边框宽度(px)', 16, 1, 400), c('color', '边框颜色', '#167d68'), s('position', '位置', [['outside', '外部'], ['inside', '内部']])],
  'image-round': [n('radius', '圆角半径(px)', 40, 0, 2000)],
  'image-shadow': [n('blur', '模糊(px)', 20, 0, 100), n('x', '水平偏移(px)', 12, -200, 200), n('y', '垂直偏移(px)', 12, -200, 200), c('color', '阴影颜色', '#23332c'), n('opacity', '阴影不透明度', 0.5, 0, 1, 0.05)],
  'canvas-extend': [n('top', '上(px)', 40, 0, 2000), n('right', '右(px)', 40, 0, 2000), n('bottom', '下(px)', 40, 0, 2000), n('left', '左(px)', 40, 0, 2000), c('color', '背景色', '#ffffff')],
  'alpha-trim': [n('threshold', '透明度阈值', 0, 0, 254), n('padding', '保留边距(px)', 0, 0, 400)],
  'chroma-key': [c('target', '背景颜色', '#ffffff'), n('tolerance', '颜色容差', 30, 0, 442), n('feather', '羽化范围', 20, 1, 200)],
  'flatten-alpha': [c('color', '背景颜色', '#ffffff')],
  'image-redact': [n('x', '左侧(%)', 20, 0, 99), n('y', '顶部(%)', 20, 0, 99), n('w', '宽度(%)', 40, 1, 100), n('h', '高度(%)', 30, 1, 100), s('mode', '方式', [['solid', '实色遮挡'], ['pixel', '马赛克']]), n('block', '马赛克块(px)', 12, 2, 100), c('color', '遮挡颜色', '#202020')],
  'pixel-art-scale': [n('scale', '整数倍率', 3, 2, 8)],
  'photo-adjust': [n('brightness', '亮度(%)', 110, 0, 200), n('contrast', '对比度(%)', 110, 0, 200), n('saturation', '饱和度(%)', 100, 0, 200), n('hue', '色相旋转(度)', 0, -180, 180)],
  'duotone': [c('dark', '阴影色', '#193c55'), c('light', '高光色', '#ffd678')],
  'image-dither': [n('threshold', '黑白阈值', 128, 0, 255), n('strength', '抖动强度', 1, 0, 2, 0.1)],
  'image-quantize': [n('colors', '颜色数量', 16, 2, 64)],
  'color-replace': [c('target', '目标颜色', '#ffffff'), c('replacement', '替换颜色', '#167d68'), n('tolerance', '颜色容差', 40, 0, 442)],
  'image-blend': [s('mode', '混合模式', [['multiply', '正片叠底'], ['screen', '滤色'], ['overlay', '叠加'], ['difference', '差值'], ['source-over', '普通']]), n('opacity', '第二张不透明度', 0.6, 0, 1, 0.05)],
  'alpha-mask': [s('mode', '蒙版来源', [['luma', '亮度'], ['alpha', '透明度']]), s('invert', '反转', [['no', '否'], ['yes', '是']])],
  'channel-extract': [],
  'normal-map': [n('strength', '凹凸强度', 2, 0.1, 20, 0.1), s('invert', 'Y 方向', [['no', 'OpenGL'], ['yes', 'DirectX']])],
  'mirror-tile': [],
  'image-split': [n('rows', '行数', 2, 1, 8), n('cols', '列数', 3, 1, 8)],
  'image-stitch': [s('direction', '拼接方向', [['vertical', '纵向'], ['horizontal', '横向']]), n('size', '统一短边(px)', 512, 32, 2048), n('gap', '间隔(px)', 8, 0, 200), c('color', '背景色', '#ffffff')],
  'image-stamp': [s('mode', '水印排布', [['single', '单枚居中'], ['tile', '平铺']]), n('size', '水印宽度(%)', 25, 1, 100), n('opacity', '不透明度', 0.5, 0.05, 1, 0.05), n('gap', '平铺间距(px)', 32, 1, 400)],
  'social-crops': [n('x', '水平焦点(%)', 50, 0, 100), n('y', '垂直焦点(%)', 50, 0, 100), n('size', '输出宽度(px)', 1080, 64, 2048)],
};

export function getImplementation(id) {
  return { fields: fields[id], async run({ images, values: v }) {
    let out = source(images); const w = out.width; const h = out.height; let ctx = out.getContext('2d');
    if (id === 'image-orient') {
      const a = v.angle * Math.PI / 180; const cs = Math.abs(Math.cos(a)); const sn = Math.abs(Math.sin(a));
      out = canvas(Math.max(1, Math.ceil(w * cs + h * sn - 1e-9)), Math.max(1, Math.ceil(w * sn + h * cs - 1e-9))); ctx = out.getContext('2d');
      ctx.translate(out.width / 2, out.height / 2); ctx.rotate(a); ctx.scale(v.flip === 'x' ? -1 : 1, v.flip === 'y' ? -1 : 1); ctx.drawImage(images[0].image, -w / 2, -h / 2);
    } else if (id === 'image-border') {
      if (v.position === 'outside') { out = canvas(w + v.size * 2, h + v.size * 2, v.color); const border = out.getContext('2d'); border.clearRect(v.size, v.size, w, h); border.drawImage(images[0].image, v.size, v.size); }
      else { ctx.fillStyle = v.color; ctx.fillRect(0, 0, w, Math.min(h, v.size)); ctx.fillRect(0, h - v.size, w, v.size); ctx.fillRect(0, 0, Math.min(w, v.size), h); ctx.fillRect(w - v.size, 0, v.size, h); }
    } else if (id === 'image-round') {
      out = canvas(w, h); ctx = out.getContext('2d'); ctx.beginPath(); ctx.roundRect(0, 0, w, h, Math.min(v.radius, w / 2, h / 2)); ctx.clip(); ctx.drawImage(images[0].image, 0, 0);
    } else if (id === 'image-shadow') {
      const pad = Math.ceil(v.blur * 3 + Math.max(Math.abs(v.x), Math.abs(v.y)) + 1);
      out = canvas(w + pad * 2, h + pad * 2); ctx = out.getContext('2d'); ctx.shadowColor = `rgba(${rgb(v.color).join(',')},${v.opacity})`; ctx.shadowBlur = v.blur; ctx.shadowOffsetX = v.x; ctx.shadowOffsetY = v.y; ctx.drawImage(images[0].image, pad, pad);
    } else if (id === 'canvas-extend') {
      out = canvas(w + v.left + v.right, h + v.top + v.bottom, v.color); out.getContext('2d').drawImage(images[0].image, v.left, v.top);
    } else if (id === 'alpha-trim') {
      const d = pixels(out).data; let x0 = w, y0 = h, x1 = -1, y1 = -1;
      for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (d[(y * w + x) * 4 + 3] > v.threshold) { x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, y); y1 = Math.max(y1, y); }
      if (x1 < 0) throw new Error('图片在当前阈值下完全透明。');
      out = canvas(x1 - x0 + 1 + 2 * v.padding, y1 - y0 + 1 + 2 * v.padding); out.getContext('2d').drawImage(images[0].image, x0, y0, x1 - x0 + 1, y1 - y0 + 1, v.padding, v.padding, x1 - x0 + 1, y1 - y0 + 1);
    } else if (id === 'flatten-alpha') {
      out = canvas(w, h, v.color); out.getContext('2d').drawImage(images[0].image, 0, 0);
    } else if (id === 'image-redact') {
      const x = Math.floor(w * v.x / 100), y = Math.floor(h * v.y / 100), rw = Math.min(w - x, Math.max(1, Math.round(w * v.w / 100))), rh = Math.min(h - y, Math.max(1, Math.round(h * v.h / 100)));
      if (v.mode === 'solid') { ctx.fillStyle = v.color; ctx.fillRect(x, y, rw, rh); }
      else { const small = canvas(Math.max(1, Math.ceil(rw / v.block)), Math.max(1, Math.ceil(rh / v.block))); small.getContext('2d').drawImage(out, x, y, rw, rh, 0, 0, small.width, small.height); ctx.imageSmoothingEnabled = false; ctx.clearRect(x, y, rw, rh); ctx.drawImage(small, x, y, rw, rh); }
    } else if (id === 'pixel-art-scale') {
      out = canvas(w * v.scale, h * v.scale); ctx = out.getContext('2d'); ctx.imageSmoothingEnabled = false; ctx.drawImage(images[0].image, 0, 0, out.width, out.height);
    } else if (id === 'photo-adjust') {
      out = canvas(w, h); ctx = out.getContext('2d'); ctx.filter = `brightness(${v.brightness}%) contrast(${v.contrast}%) saturate(${v.saturation}%) hue-rotate(${v.hue}deg)`; ctx.drawImage(images[0].image, 0, 0);
    } else if (['duotone', 'image-dither', 'color-replace', 'chroma-key', 'image-quantize'].includes(id)) {
      const data = pixels(out); const d = data.data; const dark = rgb(v.dark || '#000000'), light = rgb(v.light || '#ffffff'), target = rgb(v.target || '#ffffff'), replacement = rgb(v.replacement || '#000000');
      let palette, indices;
      if (id === 'image-quantize') { palette = quantize(d, v.colors); indices = applyPalette(d, palette); }
      const bayer = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
      for (let i = 0; i < d.length; i += 4) {
        const l = luminance(d[i], d[i + 1], d[i + 2]) / 255;
        if (id === 'duotone') for (let k = 0; k < 3; k++) d[i + k] = dark[k] + (light[k] - dark[k]) * l;
        else if (id === 'image-dither') { const p = i / 4; const threshold = v.threshold + (bayer[(Math.floor(p / w) % 4) * 4 + p % w % 4] / 16 - 0.5) * 255 * v.strength; d[i] = d[i + 1] = d[i + 2] = l * 255 >= threshold ? 255 : 0; }
        else if (id === 'image-quantize') { const p = palette[indices[i / 4]]; d[i] = p[0]; d[i + 1] = p[1]; d[i + 2] = p[2]; }
        else { const dist = Math.hypot(d[i] - target[0], d[i + 1] - target[1], d[i + 2] - target[2]); if (id === 'chroma-key') d[i + 3] *= Math.min(1, Math.max(0, (dist - v.tolerance) / v.feather)); else if (dist <= v.tolerance) for (let k = 0; k < 3; k++) d[i + k] = replacement[k]; }
      }
      ctx.putImageData(data, 0, 0);
    } else return runComposites(id, images, v, out);
    return [await png(out)];
  } };
}

async function runComposites(id, images, v, out) {
  const w = out.width, h = out.height; const ctx = out.getContext('2d');
  if (['image-blend', 'alpha-mask', 'image-stamp'].includes(id)) requireCount(images, 2);
  if (id === 'image-blend') { ctx.globalCompositeOperation = v.mode; ctx.globalAlpha = v.opacity; fit(ctx, images[1], 0, 0, w, h, true); }
  else if (id === 'alpha-mask') {
    const mask = canvas(w, h); fit(mask.getContext('2d'), images[1], 0, 0, w, h, true); const m = pixels(mask).data, data = pixels(out), d = data.data;
    for (let i = 0; i < d.length; i += 4) { let alpha = v.mode === 'alpha' ? m[i + 3] : luminance(m[i], m[i + 1], m[i + 2]) * m[i + 3] / 255; if (v.invert === 'yes') alpha = 255 - alpha; d[i + 3] *= alpha / 255; } ctx.putImageData(data, 0, 0);
  } else if (id === 'channel-extract') {
    const original = pixels(out); const result = [];
    for (let k = 0; k < 4; k++) { const node = canvas(w, h); const d = node.getContext('2d').createImageData(w, h); for (let i = 0; i < d.data.length; i += 4) { d.data[i] = d.data[i + 1] = d.data[i + 2] = original.data[i + k]; d.data[i + 3] = 255; } node.getContext('2d').putImageData(d, 0, 0); result.push(await png(node, `${['red', 'green', 'blue', 'alpha'][k]}.png`)); } return result;
  } else if (id === 'normal-map') {
    const data = pixels(out), d = data.data; const heights = new Float32Array(w * h); for (let i = 0; i < heights.length; i++) heights[i] = luminance(d[i * 4], d[i * 4 + 1], d[i * 4 + 2]) / 255;
    const at = (x, y) => heights[Math.max(0, Math.min(h - 1, y)) * w + Math.max(0, Math.min(w - 1, x))];
    for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const dx = (at(x - 1, y) - at(x + 1, y)) * v.strength, dy = (at(x, y - 1) - at(x, y + 1)) * v.strength * (v.invert === 'yes' ? -1 : 1), len = Math.hypot(dx, dy, 1), i = (y * w + x) * 4; d[i] = (dx / len + 1) * 127.5; d[i + 1] = (dy / len + 1) * 127.5; d[i + 2] = (1 / len + 1) * 127.5; d[i + 3] = 255; } ctx.putImageData(data, 0, 0);
  } else if (id === 'mirror-tile') {
    out = canvas(w * 2, h * 2); const c = out.getContext('2d'); for (let y = 0; y < 2; y++) for (let x = 0; x < 2; x++) { c.save(); c.translate(x ? w * 2 : 0, y ? h * 2 : 0); c.scale(x ? -1 : 1, y ? -1 : 1); c.drawImage(images[0].image, 0, 0); c.restore(); }
  } else if (id === 'image-split') {
    if (v.cols > w || v.rows > h) throw new Error('行列数不能超过图片像素尺寸。'); const entries = [], tiles = [];
    for (let y = 0; y < v.rows; y++) for (let x = 0; x < v.cols; x++) { const x0 = Math.floor(x * w / v.cols), y0 = Math.floor(y * h / v.rows), tw = Math.floor((x + 1) * w / v.cols) - x0, th = Math.floor((y + 1) * h / v.rows) - y0; const tile = canvas(tw, th); tile.getContext('2d').drawImage(out, x0, y0, tw, th, 0, 0, tw, th); const name = `tile-${y + 1}-${x + 1}.png`; entries.push(await png(tile, name)); tiles.push({ name, x: x0, y: y0, width: tw, height: th }); } entries.push(json({ width: w, height: h, tiles }, 'index.json')); return [await zip(entries, 'tiles.zip')];
  } else if (id === 'image-stitch') {
    if (images.length < 2) throw new Error('请至少选择两张图片。'); const vertical = v.direction === 'vertical', sizes = images.map((im) => Math.max(1, Math.round(v.size * (vertical ? im.height / im.width : im.width / im.height)))), total = sizes.reduce((a, b) => a + b, 0) + v.gap * (images.length - 1); out = canvas(vertical ? v.size : total, vertical ? total : v.size, v.color); let offset = 0;
    images.forEach((im, i) => { out.getContext('2d').drawImage(im.image, vertical ? 0 : offset, vertical ? offset : 0, vertical ? v.size : sizes[i], vertical ? sizes[i] : v.size); offset += sizes[i] + v.gap; });
  } else if (id === 'image-stamp') {
    const sw = Math.max(1, Math.round(w * v.size / 100)), sh = Math.max(1, Math.round(sw * images[1].height / images[1].width)); if (sh > 16000) throw new Error('水印过高,请减小尺寸。'); ctx.globalAlpha = v.opacity;
    if (v.mode === 'single') ctx.drawImage(images[1].image, (w - sw) / 2, (h - sh) / 2, sw, sh);
    else { if (Math.ceil(w / (sw + v.gap)) * Math.ceil(h / (sh + v.gap)) > 10000) throw new Error('水印平铺超过 10000 枚,请增大间距或尺寸。'); for (let y = 0; y < h; y += sh + v.gap) for (let x = 0; x < w; x += sw + v.gap) ctx.drawImage(images[1].image, x, y, sw, sh); }
  } else if (id === 'social-crops') {
    const result = []; for (const [a, b] of [[1, 1], [4, 3], [16, 9], [3, 4], [9, 16]]) { const node = canvas(v.size, Math.round(v.size * b / a)); fit(node.getContext('2d'), images[0], 0, 0, node.width, node.height, true, v.x / 100, v.y / 100); result.push(await png(node, `cover-${a}x${b}.png`)); } return result;
  } else throw new Error('未知图片工具。');
  return [await png(out)];
}