const canvas = document.getElementById('captchaCanvas');
    const ctx = canvas.getContext('2d');
    const captchaInput = document.getElementById('captchaInput');
    const submitBtn = document.getElementById('submitBtn');

    let generatedCaptcha = '';

    function generateCaptcha() {
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let captchaText = '';
        for (let i = 0; i < 6; i++) { // Generate 6-character CAPTCHA
            captchaText += characters.charAt(Math.floor(Math.random() * characters.length));
        }
        generatedCaptcha = captchaText;
        drawCaptcha();
    }

    function drawCaptcha() {
        ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas

        // Draw background lines/shapes for complexity
        ctx.strokeStyle = '#ccc';
        ctx.lineWidth = 1;
        for (let i = 0; i < 5; i++) {
            ctx.beginPath();
            ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
            ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
            ctx.stroke();
        }

        ctx.font = '30px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';

        for (let i = 0; i < generatedCaptcha.length; i++) {
            ctx.save(); // Save current canvas state

            const char = generatedCaptcha[i];
            const x = (canvas.width / (generatedCaptcha.length + 1)) * (i + 1);
            const y = canvas.height / 2;

            // Apply random rotations and color
            ctx.translate(x, y);
            ctx.rotate((Math.random() - 0.5) * 0.5); // Random rotation
            ctx.fillStyle = rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255});
            ctx.fillText(char, 0, 0);

            ctx.restore(); // Restore previous canvas state
        }
    }

    submitBtn.addEventListener('click', () => {
        if (captchaInput.value === generatedCaptcha) {
            alert('CAPTCHA correct!');
        } else {
            alert('CAPTCHA incorrect. Please try again.');
            generateCaptcha(); // Regenerate CAPTCHA on incorrect attempt
        }
        captchaInput.value = ''; // Clear input field
    });

    // Initial CAPTCHA generation
    generateCaptcha();