document.addEventListener("DOMContentLoaded",()=>{const e=new fabric.Canvas("editor-canvas");window.__polygonEditorCanvas=e;let s=!1;const o=[],i=document.getElementById("editor-canvas").dataset.image;i&&fabric.Image.fromURL(i,t=>{t.scaleToWidth(e.getWidth()),e.setBackgroundImage(t,e.renderAll.bind(e))},{crossOrigin:"anonymous"});const d=document.getElementById("svg-output").value.trim(),c=(d.includes('points="')?d.match(/points="([^"]+)"/)[1]:d).split(" ").map(t=>{const[n,a]=t.split(",").map(Number);return{x:n,y:a}});if(c.length>2&&!isNaN(c[0].x)){const t=new fabric.Polygon(c,{fill:"rgba(0, 128, 255, 0.3)",stroke:"blue",strokeWidth:2,selectable:!0});e.add(t),e.setActiveObject(t),e.renderAll()}e.on("mouse:down",t=>{if(!s)return;const n=e.getPointer(t.e);o.push({x:n.x,y:n.y});const a=new fabric.Circle({radius:3,fill:"red",left:n.x,top:n.y,selectable:!1});e.add(a)}),document.getElementById("generate-svg").addEventListener("click",t=>{if(t.preventDefault(),o.length>2){const n=new fabric.Polygon(o,{fill:"rgba(0, 0, 255, 0.3)",stroke:"blue",strokeWidth:2,selectable:!0});e.add(n),e.renderAll();const a=o.map(l=>`${Math.round(l.x)},${Math.round(l.y)}`).join(" ");document.getElementById("svg-output").value=`points="${a}"`}else document.getElementById("svg-output").value="Agrega al menos 3 puntos."});const r=document.getElementById("reset-canvas");r&&r.addEventListener("click",()=>{e.getObjects().forEach(t=>{t!==e.backgroundImage&&e.remove(t)}),o.length=0,document.getElementById("svg-output").value="",e.discardActiveObject(),e.renderAll()}),document.addEventListener("keydown",t=>{if(t.key==="d"&&(s=!s,alert("Modo dibujo: "+(s?"ON":"OFF"))),t.key==="Delete"||t.key==="Backspace"){const n=e.getActiveObject();n&&(e.remove(n),e.discardActiveObject(),e.renderAll())}})});
