const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');

function resizeCanvas() {
    const rect = canvas.parentElement.getBoundingClientRect();
    canvas.width = rect.width;
    canvas.height = rect.height;
}

window.addEventListener('load', resizeCanvas);
window.addEventListener('resize', resizeCanvas);

const polygons = [];
let currentPolygon = [];
const tolerance = 8;
let isDrawing = false;
let isDragging = false;
let draggedPointIndex = null;
let draggedPolygonIndex = null;

canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', endDrawing);
canvas.addEventListener('contextmenu', deletePolygon);

function startDrawing(e) {
    if (e.button !== 0) return; // Solo continuar si es el botón izquierdo

    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    let foundPoint = false;

    for (let p = 0; p < polygons.length; p++) {
        for (let i = 0; i < polygons[p].length; i++) {
            if (isNearPoint(x, y, polygons[p][i])) {
                isDragging = true;
                draggedPointIndex = i;
                draggedPolygonIndex = p;
                foundPoint = true;
                break;
            }
        }
        if (foundPoint) break;
    }

    if (!foundPoint) {
        if (currentPolygon.length === 0) {
            currentPolygon.push({ x, y });
            isDrawing = true;
        } else if (currentPolygon.length > 0 && isNearFirstPoint(x, y, currentPolygon) && currentPolygon.length >= 3) {
            closePolygon();
        } else {
            currentPolygon.push({ x, y });
            isDrawing = true;
        }
    }
    redrawAll();
}

function draw(e) {
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    if (isDragging && draggedPointIndex !== null && draggedPolygonIndex !== null) {
        polygons[draggedPolygonIndex][draggedPointIndex].x = x;
        polygons[draggedPolygonIndex][draggedPointIndex].y = y;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        redrawAll();
        calculateArea(polygons[draggedPolygonIndex], draggedPolygonIndex);
    } else if (isDrawing && currentPolygon.length > 0) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        redrawAll();
        ctx.strokeStyle = 'black';
        ctx.beginPath();
        ctx.moveTo(currentPolygon[currentPolygon.length - 1].x, currentPolygon[currentPolygon.length - 1].y);
        ctx.lineTo(x, y);
        ctx.stroke();
        for (let i = 0; i < currentPolygon.length; i++) {
            drawPoint(currentPolygon[i].x, currentPolygon[i].y);
        }
        drawPoint(x, y);
    }
}

function endDrawing() {
    isDrawing = false;
    if (isDragging) {
        isDragging = false;
        calculateArea(polygons[draggedPolygonIndex], draggedPolygonIndex);
        draggedPointIndex = null;
        draggedPolygonIndex = null;
    }
}

function deletePolygon(e) {
    e.preventDefault();

    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    for (let p = 0; p < polygons.length; p++) {
        if (isPointInPolygon({ x, y }, polygons[p])) {
            polygons.splice(p, 1);
            redrawAll();
            break;
        }
    }
}

function isNearFirstPoint(x, y, polygon) {
    if (polygon.length < 1) return false;
    const firstPoint = polygon[0];
    return Math.hypot(x - firstPoint.x, y - firstPoint.y) < tolerance;
}

function isNearPoint(x, y, point) {
    return Math.hypot(x - point.x, y - point.y) < tolerance;
}

function isPointInPolygon(point, polygon) {
    let inside = false;
    for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
        const xi = polygon[i].x, yi = polygon[i].y;
        const xj = polygon[j].x, yj = polygon[j].y;
        const intersect = ((yi > point.y) !== (yj > point.y)) &&
            (point.x < ((xj - xi) * (point.y - yi) / (yj - yi) + xi));
        if (intersect) inside = !inside;
    }
    return inside;
}

function drawPoint(x, y) {
    ctx.fillStyle = 'red';
    ctx.strokeStyle = 'black';
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.arc(x, y, 5, 0, 2 * Math.PI);
    ctx.fill();
    ctx.stroke();
}

function drawPolygon(polygon) {
    ctx.fillStyle = 'rgba(0, 0, 255, 0.3)';
    ctx.strokeStyle = 'black';
    ctx.beginPath();
    ctx.moveTo(polygon[0].x, polygon[0].y);
    for (let i = 1; i < polygon.length; i++) {
        ctx.lineTo(polygon[i].x, polygon[i].y);
    }
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
    for (let i = 0; i < polygon.length; i++) {
        drawPoint(polygon[i].x, polygon[i].y);
    }
}

function closePolygon() {
    if (currentPolygon.length > 2) {
        polygons.push(currentPolygon);
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        redrawAll();
        calculateArea(currentPolygon, polygons.length - 1);
        currentPolygon = [];
    }
}

function redrawAll() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for (let p = 0; p < polygons.length; p++) {
        drawPolygon(polygons[p]);
    }
    if (currentPolygon.length > 0) {
        ctx.strokeStyle = 'black';
        ctx.beginPath();
        ctx.moveTo(currentPolygon[0].x, currentPolygon[0].y);
        for (let i = 1; i < currentPolygon.length; i++) {
            ctx.lineTo(currentPolygon[i].x, currentPolygon[i].y);
        }
        ctx.stroke();
        for (let i = 0; i < currentPolygon.length; i++) {
            drawPoint(currentPolygon[i].x, currentPolygon[i].y);
        }
    }
}

function calculateArea(polygon, index) {
    let area = 0;
    for (let i = 0; i < polygon.length; i++) {
        const j = (i + 1) % polygon.length;
        area += polygon[i].x * polygon[j].y;
        area -= polygon[i].y * polygon[j].x;
    }
    area = Math.abs(area) / 2;
    console.log(`Área del polígono ${index + 1}: ${area}`);
    console.log(`Coordenadas del polígono ${index + 1}:`, polygon);
}