let canvas, ctx;
let drawing = false;
let startX, startY;
let mode = 'draw';

document.addEventListener('DOMContentLoaded', () => {
    canvas = document.getElementById("whiteboardCanvas");
    ctx = canvas.getContext("2d");

    let modeSelector = document.getElementById("boardMode");
    let colorPicker = document.getElementById("colorPicker");
    let thicknessPicker = document.getElementById("thicknessPicker");

    canvas.addEventListener("mousedown", function(e) {
        const rect = canvas.getBoundingClientRect();
        startX = e.clientX - rect.left;
        startY = e.clientY - rect.top;

        if (mode === 'text') {
            let text = prompt("Enter your text:");
            if (text) {
                ctx.fillStyle = colorPicker.value;
                ctx.font = `${thicknessPicker.value * 5}px Arial`;
                ctx.fillText(text, startX, startY);
            }
            return;
        }

        drawing = true;
        if (mode === 'draw') {
            ctx.beginPath();
            ctx.moveTo(startX, startY);
        }
    });

    canvas.addEventListener("mousemove", function(e) {
        if (!drawing) return;
        const rect = canvas.getBoundingClientRect();
        const currentX = e.clientX - rect.left;
        const currentY = e.clientY - rect.top;

        ctx.strokeStyle = colorPicker.value;
        ctx.lineWidth = thicknessPicker.value;

        if (mode === 'draw') {
            ctx.lineTo(currentX, currentY);
            ctx.stroke();
        }
    });

    canvas.addEventListener("mouseup", function(e) {
        drawing = false;
        const rect = canvas.getBoundingClientRect();
        const endX = e.clientX - rect.left;
        const endY = e.clientY - rect.top;

        ctx.strokeStyle = colorPicker.value;
        ctx.lineWidth = thicknessPicker.value;

        if (mode === 'line') {
            ctx.beginPath();
            ctx.moveTo(startX, startY);
            ctx.lineTo(endX, endY);
            ctx.stroke();
        }

        if (mode === 'rectangle') {
            ctx.strokeRect(startX, startY, endX - startX, endY - startY);
        }

        if (mode === 'circle') {
            ctx.beginPath();
            const radius = Math.sqrt(Math.pow(endX - startX, 2) + Math.pow(endY - startY, 2));
            ctx.arc(startX, startY, radius, 0, 2 * Math.PI);
            ctx.stroke();
        }
    });

    modeSelector.addEventListener("change", () => {
        mode = modeSelector.value;
    });
});

function clearCanvas() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}
