const $ = (x) => document.getElementById(x);

const input = $("input");
const canvas = $("canvas");
const preview = $("preview");
const background = $("background");

const ctx = canvas.getContext("2d");
const lineHeight = 22;

let height = 0;
let line = 0;

input.addEventListener("input", () => {
    const lines = input.value.split("\n");
    height = lines.length;
    canvas.width = 512;
    ctx.font =
        '16px "gg sans", "Noto Sans", "Helvetica Neue", Helvetica, Arial, sans-serif';
    ctx.textBaseline = "hanging";
    line = 0;
    lines.forEach(renderText);
    canvas.height = 22 * height;
    ctx.fillStyle = background.value;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "#EFEFF0";
    ctx.font =
        '16px "gg sans", "Noto Sans", "Helvetica Neue", Helvetica, Arial, sans-serif';
    ctx.textBaseline = "hanging";
    line = 0;
    lines.forEach(renderText);
    preview.src = canvas.toDataURL();
    canvas.toBlob((blob) => {
        const item = new ClipboardItem({ "image/png": blob });
        navigator.clipboard.write([item]);
    });
});

input.addEventListener("keydown", (e) => {
    if (e.key == "c" && e.ctrlKey) {
        e.preventDefault();
    }
});

function renderText(item, i) {
    line++;
    if (ctx.measureText(item).width > canvas.width) {
        let rn = ctx.measureText(item).width;
        let goal = canvas.width;
        let len = item.length;
        while (rn > goal) {
            len--;
            rn = ctx.measureText(item.slice(0, len)).width;
        }
        ctx.fillText(
            item.slice(0, len),
            0,
            (line - 1) * lineHeight + 2,
            canvas.width,
        );
        renderText(item.slice(len), line);
        height++;
    } else {
        ctx.fillText(item, 0, (line - 1) * lineHeight + 2, canvas.width);
    }
}
