document.addEventListener('DOMContentLoaded', () => {
    const canvas = new fabric.Canvas('editor-canvas');
    window.__polygonEditorCanvas = canvas;

    let drawingMode = false;
    const points = [];

    const canvasEl = document.getElementById('editor-canvas');
    const imageUrl = canvasEl.dataset.image;

    // ✅ Cargar imagen de fondo
    if (imageUrl) {
        fabric.Image.fromURL(imageUrl, (img) => {
            img.scaleToWidth(canvas.getWidth());
            canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
        }, { crossOrigin: 'anonymous' });
    }

    // ✅ Cargar polígono desde textarea (svg_points)
    const rawPoints = document.getElementById('svg-output').value.trim();
    const pointsString = rawPoints.includes('points="')
        ? rawPoints.match(/points="([^"]+)"/)[1]
        : rawPoints;

    const loadedPoints = pointsString.split(' ').map(coord => {
        const [x, y] = coord.split(',').map(Number);
        return { x, y };
    });

    if (loadedPoints.length > 2 && !isNaN(loadedPoints[0].x)) {
        const polygon = new fabric.Polygon(loadedPoints, {
            fill: 'rgba(0, 128, 255, 0.3)',
            stroke: 'blue',
            strokeWidth: 2,
            selectable: true
        });
        canvas.add(polygon);
        canvas.setActiveObject(polygon);
        canvas.renderAll();
    }

    // 🖱 Dibujo con mouse
    canvas.on('mouse:down', (opt) => {
        if (!drawingMode) return;

        const pointer = canvas.getPointer(opt.e);
        points.push({ x: pointer.x, y: pointer.y });

        const circle = new fabric.Circle({
            radius: 3,
            fill: 'red',
            left: pointer.x,
            top: pointer.y,
            selectable: false
        });

        canvas.add(circle);
    });

    // 💾 Generar SVG
    document.getElementById('generate-svg').addEventListener('click', (e) => {
        e.preventDefault();

        if (points.length > 2) {
            const polygon = new fabric.Polygon(points, {
                fill: 'rgba(0, 0, 255, 0.3)',
                stroke: 'blue',
                strokeWidth: 2,
                selectable: true
            });

            canvas.add(polygon);
            canvas.renderAll();

            const formattedPoints = points.map(p => `${Math.round(p.x)},${Math.round(p.y)}`).join(' ');
            document.getElementById('svg-output').value = `points="${formattedPoints}"`;
        } else {
            document.getElementById('svg-output').value = 'Agrega al menos 3 puntos.';
        }
    });

    // 🔄 Reset canvas
    const resetBtn = document.getElementById('reset-canvas');
    if (resetBtn) {
        resetBtn.addEventListener('click', () => {
            canvas.getObjects().forEach(obj => {
                if (obj !== canvas.backgroundImage) {
                    canvas.remove(obj);
                }
            });

            points.length = 0;
            document.getElementById('svg-output').value = '';
            canvas.discardActiveObject();
            canvas.renderAll();
        });
    }

    // 🧩 Teclado: D para dibujar, Supr para borrar
    document.addEventListener('keydown', (e) => {
        if (e.key === 'd') {
            drawingMode = !drawingMode;
            alert('Modo dibujo: ' + (drawingMode ? 'ON' : 'OFF'));
        }

        if (e.key === 'Delete' || e.key === 'Backspace') {
            const active = canvas.getActiveObject();
            if (active) {
                canvas.remove(active);
                canvas.discardActiveObject();
                canvas.renderAll();
            }
        }
    });
});
