import QRCode from 'qrcode';
import { field, input, select, number, value, result, encode } from '../../src/io.js';
export default {
  controls: field('文本或网址', '<textarea name="text" maxlength="1200" required>https://lansejingying.com/</textarea>') + field('尺寸(px)', input('size', 512, 128, 2048)) + field('纠错等级', select('level', [['M', 'M · 15%'], ['L', 'L · 7%'], ['Q', 'Q · 25%'], ['H', 'H · 30%']])) + field('前景色', '<input name="dark" type="color" value="#172c25">') + field('背景色', '<input name="light" type="color" value="#ffffff">'),
  async run({ form }) {
    if (!value(form, 'text').trim()) throw new Error('请输入文本或网址。');
    const dark = value(form, 'dark'); const light = value(form, 'light');
    const luminance = (hex) => { const rgb = hex.slice(1).match(/../g).map((v) => { const n = parseInt(v, 16) / 255; return n <= 0.04045 ? n / 12.92 : ((n + 0.055) / 1.055) ** 2.4; }); return rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722; };
    if ((luminance(light) + 0.05) / (luminance(dark) + 0.05) < 4.5) throw new Error('前景色应比背景色深,且对比度至少为 4.5。');
    const size = number(form, 'size'); const node = document.createElement('canvas');
    await QRCode.toCanvas(node, value(form, 'text'), { width: size, margin: 4, errorCorrectionLevel: value(form, 'level'), color: { dark, light } });
    if (node.width > size) throw new Error('内容过多,请增加尺寸或缩短文本。');
    return [result(await encode(node), 'qr-code.png', `${node.width} × ${node.height}`)];
  },
};