(() => {
    const canvas=document.getElementById('signature-pad');
    const output=document.getElementById('signature-data');
    const clear=document.getElementById('signature-clear');

    if(!canvas || !output){
        return;
    }

    const ctx=canvas.getContext('2d');
    ctx.lineWidth=2.2;
    ctx.lineCap='round';

    let drawing=false;

    const point=event => {
        const rect=canvas.getBoundingClientRect();
        const source=event.touches ? event.touches[0] : event;
        return {
            x:(source.clientX-rect.left)*(canvas.width/rect.width),
            y:(source.clientY-rect.top)*(canvas.height/rect.height)
        };
    };

    const start=event => {
        drawing=true;
        const p=point(event);
        ctx.beginPath();
        ctx.moveTo(p.x,p.y);
        event.preventDefault();
    };

    const move=event => {
        if(!drawing){
            return;
        }
        const p=point(event);
        ctx.lineTo(p.x,p.y);
        ctx.stroke();
        output.value=canvas.toDataURL('image/png');
        event.preventDefault();
    };

    const end=() => {
        drawing=false;
        output.value=canvas.toDataURL('image/png');
    };

    canvas.addEventListener('mousedown',start);
    canvas.addEventListener('mousemove',move);
    window.addEventListener('mouseup',end);
    canvas.addEventListener('touchstart',start,{passive:false});
    canvas.addEventListener('touchmove',move,{passive:false});
    canvas.addEventListener('touchend',end);

    clear?.addEventListener('click',() => {
        ctx.clearRect(0,0,canvas.width,canvas.height);
        output.value='';
    });
})();
