const canvas=document.querySelector('.crop-canvas'),ctx=canvas.getContext('2d'),file=document.querySelector('.crop-file'),zoom=document.querySelector('.crop-zoom'),px=document.querySelector('.crop-x'),py=document.querySelector('.crop-y'),status=document.querySelector('.crop-status'),save=document.querySelector('.crop-save');let image;function draw(){if(!image||!ctx)return;const size=Math.min(image.naturalWidth,image.naturalHeight)/Number(zoom.value),x=(image.naturalWidth-size)*px.value/100,y=(image.naturalHeight-size)*py.value/100;ctx.clearRect(0,0,360,360);ctx.drawImage(image,x,y,size,size,0,0,360,360)}file.onchange=()=>{const f=file.files[0];if(!f)return;save.disabled=true;if(!['image/png','image/jpeg','image/webp'].includes(f.type)||f.size>10485760){status.textContent='Wybierz JPG, PNG lub WebP do 10 MB.';return}const url=URL.createObjectURL(f),img=new Image();img.onload=()=>{URL.revokeObjectURL(url);if(img.naturalWidth*img.naturalHeight>40000000){status.textContent='Obraz ma ponad 40 megapikseli.';return}image=img;zoom.value=1;draw();save.disabled=!ctx;status.textContent='Ustaw kadr i pobierz plik.'};img.onerror=()=>{URL.revokeObjectURL(url);status.textContent='Nie można odczytać obrazu.'};img.src=url};[zoom,px,py].forEach(i=>i.oninput=draw);save.onclick=()=>canvas.toBlob(blob=>{if(!blob)return;const url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='kadr.png';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)},'image/png');