import {createShape,moveShape,hitTest,toSvg,defs,shapeMarkup} from './model.mjs';
const $=id=>document.getElementById(id),canvas=$('canvas');let shapes=[],tool='select',selected=null,seq=1,drag=null;
const number=id=>Number($(id).value);
function status(s){$('status').textContent=s}
function render(){canvas.innerHTML=defs+shapes.map(s=>shapeMarkup(s)+(s.id===selected?``:'' )).join('');$('count').textContent=shapes.length;$('scene').textContent=JSON.stringify(shapes,null,2);$('objects').replaceChildren(...shapes.map(s=>{const b=document.createElement('button');b.textContent=`${s.id}. ${s.type}${s.type==='text'?' — '+s.text:''}`;b.setAttribute('aria-pressed',s.id===selected);b.onclick=()=>select(s.id);return b}));}
function select(id){selected=id;const s=shapes.find(s=>s.id===id);if(s){$('x').value=s.x;$('y').value=s.y;$('w').value=s.w??s.x2??240;$('h').value=s.h??s.y2??140;if(s.type==='text')$('text').value=s.text;}render();status(s?`Selected ${s.type} #${id}. Edit its values or use arrow keys on the canvas.`:'No object selected.');}
for(const b of document.querySelectorAll('[data-tool]'))b.onclick=()=>{tool=b.dataset.tool;document.querySelectorAll('[data-tool]').forEach(v=>v.setAttribute('aria-pressed',v===b));status(`${b.textContent} tool active.`)};
function add(start,end){const s=createShape(tool,start,end,$('text').value,seq);if(s){shapes.push(s);seq++;select(s.id);status(`Added ${s.type} #${s.id}. ${shapes.length} objects on the canvas.`)}else status('No object added. Choose a drawing tool and use non-empty dimensions or text.');}
$('add').onclick=()=>{const start={x:number('x'),y:number('y')};add(start,tool==='rectangle'?{x:start.x+number('w'),y:start.y+number('h')}:{x:number('w'),y:number('h')})};
$('apply').onclick=()=>{const old=shapes.find(s=>s.id===selected);if(!old)return status('Select an object first.');const start={x:number('x'),y:number('y')};const s=createShape(old.type,start,old.type==='rectangle'?{x:start.x+number('w'),y:start.y+number('h')}:{x:number('w'),y:number('h')},$('text').value,old.id);if(!s)return status('Change rejected: empty text or dimensions.');shapes=shapes.map(v=>v.id===s.id?s:v);render();status(`Updated ${s.type} #${s.id}.`)};
function remove(){if(selected===null)return;const id=selected;shapes=shapes.filter(s=>s.id!==id);selected=null;render();status(`Deleted object #${id}. ${shapes.length} objects remain.`)}$('delete').onclick=remove;
function point(e){const r=canvas.getBoundingClientRect();return{x:Math.round((e.clientX-r.left)*960/r.width),y:Math.round((e.clientY-r.top)*540/r.height)}}
canvas.onpointerdown=e=>{const p=point(e);canvas.focus();canvas.setPointerCapture(e.pointerId);if(tool==='select'){select(hitTest(shapes,p));drag={start:p,base:shapes.map(s=>({...s})),moving:true}}else if(tool==='text')add(p,null);else drag={start:p,moving:false}};
canvas.onpointermove=e=>{if(drag?.moving&&selected!==null){const p=point(e);shapes=moveShape(drag.base,selected,p.x-drag.start.x,p.y-drag.start.y);render()}};
canvas.onpointerup=e=>{if(drag){if(!drag.moving)add(drag.start,point(e));else if(selected!==null)select(selected);drag=null}};canvas.onpointercancel=()=>{if(drag?.moving)shapes=drag.base;drag=null;render()};
canvas.onkeydown=e=>{const d={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]}[e.key];if(d&&selected!==null){e.preventDefault();const k=e.shiftKey?10:1;shapes=moveShape(shapes,selected,d[0]*k,d[1]*k);select(selected)}if(e.key==='Delete'||e.key==='Backspace'){e.preventDefault();remove()}};
$('export').onclick=async()=>{const svg=toSvg(shapes),u=URL.createObjectURL(new Blob([svg],{type:'image/svg+xml'}));try{const img=new Image();img.src=u;await img.decode();const c=document.createElement('canvas');c.width=960;c.height=540;const ctx=c.getContext('2d');ctx.drawImage(img,0,0);const blob=await new Promise(r=>c.toBlob(r,'image/png'));const png=URL.createObjectURL(blob);const prev=$('export-image').dataset.objectUrl;if(prev)URL.revokeObjectURL(prev);$('export-image').src=png;$('export-image').dataset.objectUrl=png;await $('export-image').decode();const copy=document.createElement('canvas');copy.width=960;copy.height=540;copy.getContext('2d').drawImage($('export-image'),0,0);const a=ctx.getImageData(0,0,960,540).data,b=copy.getContext('2d').getImageData(0,0,960,540).data;let changed=0;for(let i=0;i