<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Color Therapy Enhanced</title>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            overflow: hidden;
            font-family: Arial, sans-serif;
        }
        #message {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 24px;
            text-align: center;
            z-index: 2;
            white-space: nowrap;
            animation: breathe 5s ease-in-out infinite, glow 2s ease-in-out infinite;
        }
        @keyframes breathe {
            0%, 100% { transform: scale(1) translate(-50%, -50%); }
            50% { transform: scale(1.1) translate(-50%, -50%); }
        }
        @keyframes glow {
            0%, 100% { text-shadow: 0 0 10px rgba(255, 255, 255, 0.5); }
            50% { text-shadow: 0 0 20px rgba(255, 255, 255, 1); }
        }
        .popup {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            z-index: 1000;
        }
        .popup button {
            margin: 10px;
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .popup button:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
    <div id="message"></div>
    <div class="popup" id="exitPopup">
        <p>¿Estás seguro de que quieres salir?</p>
        <button id="confirmExit">Sí</button>
        <button id="cancelExit">No</button>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <script>
        const scene = new THREE.Scene();
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        const renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);

        // Background colors and messages setup
        const backgroundColors = [
            '#4f412c', '#9da85e', '#101347', '#a05bcf', '#574e42'
        ];
        let backgroundColorIndex = 0;
        const messages = [
            "Find inner peace and harmony...",
            "Let go of all worries and stress...",
            "Embrace the calm and tranquility...",
            "Feel the energy flow through you..."
        ];
        let messageIndex = 0;

        // Particle system setup
        const geometry = new THREE.BufferGeometry();
        const vertices = [];
        const colors = [];
        for (let i = 0; i < 10000; i++) {
            vertices.push(
                THREE.MathUtils.randFloatSpread(2000),
                THREE.MathUtils.randFloatSpread(2000),
                THREE.MathUtils.randFloatSpread(2000)
            );
            colors.push(Math.random(), Math.random(), Math.random());
        }
        geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
        geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));

        const particleMaterial = new THREE.PointsMaterial({
            size: 2,
            vertexColors: true,
            blending: THREE.AdditiveBlending,
            transparent: true
        });
        const particles = new THREE.Points(geometry, particleMaterial);
        scene.add(particles);

        // Ships setup with enhanced trails
        const ships = [];
        const shipTrails = [];
        const maxTrailLength = 50;

        for (let i = 0; i < 10; i++) {
            const shipGeometry = new THREE.IcosahedronGeometry(20, 0);
            const shipMaterial = new THREE.MeshBasicMaterial({
                color: new THREE.Color().setHSL(Math.random(), 1, 0.5),
                wireframe: true
            });
            const ship = new THREE.Mesh(shipGeometry, shipMaterial);
            ship.position.set(
                THREE.MathUtils.randFloatSpread(1000),
                THREE.MathUtils.randFloatSpread(1000),
                THREE.MathUtils.randFloatSpread(1000)
            );
            ship.velocity = new THREE.Vector3(
                Math.random() * 2 - 1,
                Math.random() * 2 - 1,
                Math.random() * 2 - 1
            ).normalize().multiplyScalar(2);
            
            ships.push(ship);
            shipTrails.push([]);
            scene.add(ship);
        }

        // Trail system
        function createTrailPoint(position, color) {
            const trailGeometry = new THREE.SphereGeometry(2, 8, 8);
            const trailMaterial = new THREE.MeshBasicMaterial({
                color: color,
                transparent: true,
                opacity: 0.8
            });
            const trailPoint = new THREE.Mesh(trailGeometry, trailMaterial);
            trailPoint.position.copy(position);
            return trailPoint;
        }

        // Popup handling
        let isPopupVisible = false;
        document.addEventListener('keydown', showExitPopup);
        document.addEventListener('click', (event) => {
            if (!isPopupVisible || 
                (event.target.id === 'cancelExit' || event.target.id === 'confirmExit')) {
                if (event.target.id === 'cancelExit') {
                    hideExitPopup();
                } else if (event.target.id === 'confirmExit') {
                    window.close();
                } else if (!isPopupVisible) {
                    showExitPopup();
                }
            }
        });

        function showExitPopup() {
            if (!isPopupVisible) {
                isPopupVisible = true;
                document.getElementById('exitPopup').style.display = 'block';
            }
        }

        function hideExitPopup() {
            isPopupVisible = false;
            document.getElementById('exitPopup').style.display = 'none';
        }

        // Animation loop
        camera.position.z = 1000;
        let time = 0;

        function animate() {
            requestAnimationFrame(animate);
            time += 0.01;

            // Update particles
            const positions = geometry.attributes.position.array;
            const colors = geometry.attributes.color.array;
            
            for (let i = 0; i < positions.length; i += 3) {
                const x = positions[i];
                const y = positions[i + 1];
                const z = positions[i + 2];

                // Add wave effect to particles
                positions[i + 1] = y + Math.sin(time + x * 0.01) * 0.5;

                // Update colors based on position
                colors[i] = Math.sin(time + x * 0.01) * 0.5 + 0.5;
                colors[i + 1] = Math.cos(time + y * 0.01) * 0.5 + 0.5;
                colors[i + 2] = Math.sin(time + z * 0.01) * 0.5 + 0.5;
            }

            geometry.attributes.position.needsUpdate = true;
            geometry.attributes.color.needsUpdate = true;

            // Update ships and trails
            ships.forEach((ship, index) => {
                // Update ship position
                ship.position.add(ship.velocity);
                ship.rotation.x += 0.01;
                ship.rotation.y += 0.01;

                // Bounce off boundaries
                ['x', 'y', 'z'].forEach(axis => {
                    if (Math.abs(ship.position[axis]) > 1000) {
                        ship.velocity[axis] *= -1;
                    }
                });

                // Create new trail point
                const trailPoint = createTrailPoint(
                    ship.position.clone(),
                    new THREE.Color().setHSL((time + index * 0.1) % 1, 1, 0.5)
                );
                shipTrails[index].push(trailPoint);
                scene.add(trailPoint);

                // Remove old trail points
                if (shipTrails[index].length > maxTrailLength) {
                    const oldPoint = shipTrails[index].shift();
                    scene.remove(oldPoint);
                    oldPoint.geometry.dispose();
                    oldPoint.material.dispose();
                }

                // Fade trail points
                shipTrails[index].forEach((point, i) => {
                    point.material.opacity = i / maxTrailLength;
                });
            });

            particles.rotation.x += 0.0003;
            particles.rotation.y += 0.0005;

            renderer.render(scene, camera);
        }

        // Handle window resize
        window.addEventListener('resize', () => {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(window.innerWidth, window.innerHeight);
        });

        // Start animation
        animate();

        // Message update function
        async function changeMessage() {
            const messageElement = document.getElementById('message');
            const nextMessage = messages[messageIndex];
            messageIndex = (messageIndex + 1) % messages.length;

            messageElement.innerHTML = '';
            messageElement.style.color = `hsl(${Math.random() * 360}, 100%, 70%)`;

            for (let i = 0; i < nextMessage.length; i++) {
                const charSpan = document.createElement('span');
                charSpan.classList.add('char');
                charSpan.innerText = nextMessage[i] === ' ' ? '\u00A0' : nextMessage[i];
                messageElement.appendChild(charSpan);
                await new Promise(resolve => setTimeout(resolve, 70));
            }
        }

        // Initialize message and set interval
        changeMessage();
        setInterval(changeMessage, 10000);
    </script>
</body>
</html>
