const initThreeBackground = () => {
    // Get the canvas element
    const canvas = document.getElementById('bg-canvas');
    if (!canvas) return;
    
    // Create scene, camera, and renderer
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    const renderer = new THREE.WebGLRenderer({ canvas, alpha: true, antialias: true });
    
    // Set renderer size and pixel ratio
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
    
    // Create space background with subtle gradient
    scene.background = new THREE.Color(0x000510); // Very dark blue for space
    
    // Create a group to hold all star systems
    const galaxyGroup = new THREE.Group();
    scene.add(galaxyGroup);
    
    // Number of star systems
    const starSystemCount = 500; // Reduced count for performance
    
    // Create multiple star systems
    for (let i = 0; i < starSystemCount; i++) {
        // Create a group for this star system
        const starSystem = new THREE.Group();
        
        // Random position within a sphere
        const radius = 4 + Math.random() * 20;
        const theta = Math.random() * Math.PI * 2;
        const phi = Math.acos((Math.random() * 2) - 1);
        
        const x = radius * Math.sin(phi) * Math.cos(theta);
        const y = radius * Math.sin(phi) * Math.sin(theta);
        const z = radius * Math.cos(phi);
        
        starSystem.position.set(x, y, z);
        
        // Random rotation
        starSystem.rotation.x = Math.random() * Math.PI * 2;
        starSystem.rotation.y = Math.random() * Math.PI * 2;
        starSystem.rotation.z = Math.random() * Math.PI * 2;
        
        // Random scale - smaller systems further out
        const distanceFromCenter = Math.sqrt(x*x + y*y + z*z);
        const scaleFactor = 0.05 + (1 - distanceFromCenter/25) * 0.3;
        starSystem.scale.set(scaleFactor, scaleFactor, scaleFactor);
        
        // Store random rotation speeds
        starSystem.userData = {
            rotationSpeedX: (Math.random() - 0.5) * 0.01,
            rotationSpeedY: (Math.random() - 0.5) * 0.01,
            rotationSpeedZ: (Math.random() - 0.5) * 0.01,
            pulseSpeed: 0.5 + Math.random() * 2,
            pulseOffset: Math.random() * Math.PI * 2,
            jetScale: 0.5 + Math.random() * 0.5
        };
        
        // Create central star
        const starGeometry = new THREE.SphereGeometry(1, 16, 16);
        
        // Random star color
        const colorType = Math.random();
        let starColor;
        
        if (colorType < 0.6) { // Blue-white (most common)
            starColor = new THREE.Color(0x8EBBFF);
        } else if (colorType < 0.8) { // Yellow-white
            starColor = new THREE.Color(0xFFF4D6);
        } else if (colorType < 0.95) { // Red stars
            starColor = new THREE.Color(0xFF9E80);
        } else { // Blue giants (rare)
            starColor = new THREE.Color(0x4F7DFF);
        }
        
        const starMaterial = new THREE.MeshBasicMaterial({
            color: starColor,
            transparent: true,
            opacity: 0.8
        });
        
        const star = new THREE.Mesh(starGeometry, starMaterial);
        starSystem.add(star);
        
        // Add glow to star
        const glowGeometry = new THREE.SphereGeometry(1.5, 16, 16);
        const glowMaterial = new THREE.ShaderMaterial({
            uniforms: {
                color: { value: starColor }
            },
            vertexShader: `
                varying vec3 vNormal;
                varying vec3 vViewPosition;
                
                void main() {
                    vNormal = normalize(normalMatrix * normal);
                    vec4 viewPosition = modelViewMatrix * vec4(position, 1.0);
                    vViewPosition = viewPosition.xyz;
                    gl_Position = projectionMatrix * viewPosition;
                }
            `,
            fragmentShader: `
                uniform vec3 color;
                varying vec3 vNormal;
                varying vec3 vViewPosition;
                
                void main() {
                    float intensity = pow(0.7 - dot(vNormal, normalize(vViewPosition)), 4.0);
                    gl_FragColor = vec4(color, 1.0) * intensity;
                }
            `,
            side: THREE.BackSide,
            blending: THREE.AdditiveBlending,
            transparent: true
        });
        
        const glowMesh = new THREE.Mesh(glowGeometry, glowMaterial);
        starSystem.add(glowMesh);
        
        // Add star light
        const starLight = new THREE.PointLight(starColor, 1, 10);
        starLight.position.set(0, 0, 0);
        starSystem.add(starLight);
        
        // Create jets for this star system using instances for performance
        const jetParticlesCount = 1000; // Reduced count for performance
        
        // Create geometry for both north and south jets
        const jetGeometry = new THREE.BufferGeometry();
        const jetPositions = new Float32Array(jetParticlesCount * 2 * 3); // Double for north and south
        const jetColors = new Float32Array(jetParticlesCount * 2 * 3);
        const jetSizes = new Float32Array(jetParticlesCount * 2);
        
        // Set up jets (north and south)
        for (let j = 0; j < jetParticlesCount; j++) {
            const j3 = j * 3;
            const j3South = (j + jetParticlesCount) * 3;
            
            // Distance from center (increases away from center)
            const distFromCenter = Math.pow(Math.random(), 2) * 5; // More concentrated
            
            // Angular dispersion (wider at ends, narrower in middle)
            const maxAngle = 0.2 + 0.3 * Math.abs(Math.tan(distFromCenter * 0.25));
            const randomAngle = Math.random() * 2 * Math.PI;
            const randomRadius = Math.random() * maxAngle * distFromCenter;
            
            // North Jet (positive y)
            const nx = Math.sin(randomAngle) * randomRadius;
            const ny = distFromCenter; // Distance along y-axis
            const nz = Math.cos(randomAngle) * randomRadius;
            
            // South Jet (negative y)
            const sx = Math.sin(randomAngle) * randomRadius;
            const sy = -distFromCenter; // Negative y for south jet
            const sz = Math.cos(randomAngle) * randomRadius;
            
            // Set positions
            jetPositions[j3] = nx;
            jetPositions[j3 + 1] = ny;
            jetPositions[j3 + 2] = nz;
            
            jetPositions[j3South] = sx;
            jetPositions[j3South + 1] = sy;
            jetPositions[j3South + 2] = sz;
            
            // Colors - brightness based on distance
            const brightness = 0.5 + 0.5 * (1 - distFromCenter / 5);
            
            // Extract color components from the star color
            const r = starColor.r;
            const g = starColor.g;
            const b = starColor.b;
            
            // North jet - slightly more blue/cyan
            jetColors[j3] = r * brightness * 0.7; // R
            jetColors[j3 + 1] = g * brightness * 0.8; // G
            jetColors[j3 + 2] = b * brightness; // B
            
            // South jet - slightly more red/magenta
            jetColors[j3South] = r * brightness; // R
            jetColors[j3South + 1] = g * brightness * 0.7; // G
            jetColors[j3South + 2] = b * brightness * 0.8; // B
            
            // Sizes - larger at center, smaller at edges
            const particleSize = (0.2 + Math.random() * 0.1) * (1 - 0.7 * distFromCenter / 5);
            jetSizes[j] = particleSize;
            jetSizes[j + jetParticlesCount] = particleSize;
        }
        
        // Set attributes
        jetGeometry.setAttribute('position', new THREE.BufferAttribute(jetPositions, 3));
        jetGeometry.setAttribute('color', new THREE.BufferAttribute(jetColors, 3));
        jetGeometry.setAttribute('size', new THREE.BufferAttribute(jetSizes, 1));
        
        // Create material for jets
        const jetMaterial = new THREE.PointsMaterial({
            size: 0.1,
            sizeAttenuation: true,
            vertexColors: true,
            transparent: true,
            opacity: 0.8,
            blending: THREE.AdditiveBlending
        });
        
        // Create mesh for jets
        const jets = new THREE.Points(jetGeometry, jetMaterial);
        starSystem.add(jets);
        
        // Add this star system to the galaxy
        galaxyGroup.add(starSystem);
    }
    
    // Create space dust (smaller particles) in the background
    const dustCount = 5000;
    const dustGeometry = new THREE.BufferGeometry();
    const dustPositions = new Float32Array(dustCount * 3);
    const dustColors = new Float32Array(dustCount * 3);
    const dustSizes = new Float32Array(dustCount);
    
    for (let i = 0; i < dustCount; i++) {
        const i3 = i * 3;
        
        // Create dust in a larger sphere
        const radius = 5 + Math.random() * 30;
        const theta = Math.random() * Math.PI * 2;
        const phi = Math.acos((Math.random() * 2) - 1);
        
        dustPositions[i3] = radius * Math.sin(phi) * Math.cos(theta);
        dustPositions[i3 + 1] = radius * Math.sin(phi) * Math.sin(theta);
        dustPositions[i3 + 2] = radius * Math.cos(phi);
        
        // Subtle blue-grey colors for dust
        const intensity = Math.random() * 0.5 + 0.2;
        dustColors[i3] = intensity * 0.5;
        dustColors[i3 + 1] = intensity * 0.7;
        dustColors[i3 + 2] = intensity * 0.9;
        
        // Small sizes for dust
        dustSizes[i] = Math.random() * 0.05 + 0.01;
    }
    
    dustGeometry.setAttribute('position', new THREE.BufferAttribute(dustPositions, 3));
    dustGeometry.setAttribute('color', new THREE.BufferAttribute(dustColors, 3));
    dustGeometry.setAttribute('size', new THREE.BufferAttribute(dustSizes, 1));
    
    const dustMaterial = new THREE.PointsMaterial({
        size: 0.02,
        sizeAttenuation: true,
        vertexColors: true,
        transparent: true,
        opacity: 0.6,
        blending: THREE.AdditiveBlending
    });
    
    const dust = new THREE.Points(dustGeometry, dustMaterial);
    scene.add(dust);
    
    // Create rain effect across the entire page
    const rainCount = 1000;
    const rainGeometry = new THREE.BufferGeometry();
    const rainPositions = new Float32Array(rainCount * 3);
    const rainVelocities = new Float32Array(rainCount);
    const rainSizes = new Float32Array(rainCount);
    
    // Get page dimensions for rain positioning
    const pageWidth = window.innerWidth;
    const pageHeight = window.innerHeight;
    const pageDepth = 20; // How deep the 3D space should be
    
    // Calculate scaling factors to convert from pixel space to Three.js space
    const cameraZ = 10;
    const vFov = (camera.fov * Math.PI) / 180;
    const heightAtDepth = 2 * Math.tan(vFov / 2) * cameraZ;
    const widthAtDepth = heightAtDepth * camera.aspect;
    
    // Scale factors to convert from screen pixels to Three.js units
    const scaleX = widthAtDepth / window.innerWidth;
    const scaleY = heightAtDepth / window.innerHeight;
    
    // Initialize rain drops
    for (let i = 0; i < rainCount; i++) {
        const i3 = i * 3;
        
        // Position randomly across page width and height
        const x = (Math.random() * pageWidth - pageWidth / 2) * scaleX;
        const y = (Math.random() * pageHeight * 2 - pageHeight / 2) * scaleY; // Some above, some below
        const z = Math.random() * pageDepth - pageDepth / 2; // Distribute across depth
        
        rainPositions[i3] = x;
        rainPositions[i3 + 1] = y;
        rainPositions[i3 + 2] = z;
        
        // Random falling speeds - deeper particles fall slower (parallax effect)
        const depthFactor = 1 - (z + pageDepth/2) / pageDepth; // 0 to 1, deeper = smaller
        rainVelocities[i] = (Math.random() * 0.03 + 0.01) * (0.5 + depthFactor);
        
        // Raindrop sizes - closer droplets are larger
        rainSizes[i] = (Math.random() * 0.02 + 0.01) * (0.5 + depthFactor);
    }
    
    rainGeometry.setAttribute('position', new THREE.BufferAttribute(rainPositions, 3));
    rainGeometry.setAttribute('size', new THREE.BufferAttribute(rainSizes, 1));
    
    // Create raindrop texture
    function createRainTexture() {
        const canvas = document.createElement('canvas');
        canvas.width = 32;
        canvas.height = 32;
        
        const context = canvas.getContext('2d');
        
        // Create elongated raindrop shape
        const gradient = context.createLinearGradient(16, 0, 16, 32);
        gradient.addColorStop(0, 'rgba(190, 215, 255, 0.0)');
        gradient.addColorStop(0.2, 'rgba(190, 215, 255, 0.5)');
        gradient.addColorStop(0.9, 'rgba(190, 215, 255, 0.7)');
        gradient.addColorStop(1, 'rgba(190, 215, 255, 0.0)');
        
        context.fillStyle = gradient;
        
        // Draw an elongated raindrop
        context.beginPath();
        context.moveTo(16, 2);
        context.lineTo(18, 10);
        context.lineTo(16, 30);
        context.lineTo(14, 10);
        context.closePath();
        context.fill();
        
        const texture = new THREE.Texture(canvas);
        texture.needsUpdate = true;
        return texture;
    }
    
    // Rain material with custom shader
    const rainMaterial = new THREE.ShaderMaterial({
        uniforms: {
            pointTexture: { value: createRainTexture() }
        },
        vertexShader: `
            attribute float size;
            void main() {
                vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
                gl_PointSize = size * (300.0 / -mvPosition.z);
                gl_Position = projectionMatrix * mvPosition;
            }
        `,
        fragmentShader: `
            uniform sampler2D pointTexture;
            void main() {
                vec4 texColor = texture2D(pointTexture, gl_PointCoord);
                gl_FragColor = texColor;
            }
        `,
        transparent: true,
        depthWrite: false,
        blending: THREE.AdditiveBlending
    });
    
    // Create rain mesh
    const rain = new THREE.Points(rainGeometry, rainMaterial);
    scene.add(rain);
    
    // Add subtle ambient light
    const ambientLight = new THREE.AmbientLight(0x111133, 0.3);
    scene.add(ambientLight);
    
    // Add subtle directional light 
    const directionalLight = new THREE.DirectionalLight(0x2233AA, 0.4);
    directionalLight.position.set(1, 0.5, 0.5);
    scene.add(directionalLight);
    
    // Add faint rim light from the opposite direction
    const rimLight = new THREE.DirectionalLight(0x2255DD, 0.2);
    rimLight.position.set(-1, -0.5, -0.5);
    scene.add(rimLight);
    
    // Camera controls
    camera.position.z = 30;
    
    // Handle window resize
    window.addEventListener('resize', () => {
        // Update camera aspect ratio
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        
        // Update renderer size
        renderer.setSize(window.innerWidth, window.innerHeight);
        
        // Update page dimensions
        const pageWidth = window.innerWidth;
        const pageHeight = window.innerHeight;
        
        // Recalculate scaling factors
        const heightAtDepth = 2 * Math.tan(vFov / 2) * cameraZ;
        const widthAtDepth = heightAtDepth * camera.aspect;
        const scaleX = widthAtDepth / window.innerWidth;
        const scaleY = heightAtDepth / window.innerHeight;
        
        // Update rain positions to match new dimensions
        const rainPositionsAttribute = rain.geometry.getAttribute('position');
        
        for (let i = 0; i < rainCount; i++) {
            const i3 = i * 3;
            
            // Only adjust if the raindrops are out of bounds
            if (Math.abs(rainPositionsAttribute.array[i3] / scaleX) > pageWidth / 2) {
                rainPositionsAttribute.array[i3] = (Math.random() * pageWidth - pageWidth / 2) * scaleX;
            }
        }
        
        rainPositionsAttribute.needsUpdate = true;
    });
    
    // Animation loop
    const clock = new THREE.Clock();
    
    const animate = () => {
        const elapsedTime = clock.getElapsedTime();
        const deltaTime = clock.getDelta();
        
        // Rotate the entire galaxy group based on mouse position
        if (window.mouseX && window.mouseY) {
            galaxyGroup.rotation.y += window.mouseX * 0.00001;
            galaxyGroup.rotation.x += window.mouseY * 0.00001;
        }
        
        // Slowly rotate the galaxy regardless of mouse movement
        galaxyGroup.rotation.y += 0.0001;
        
        // Rotate space dust
        dust.rotation.y -= 0.0001;
        dust.rotation.x += 0.00005;
        
        // Animate each star system
        galaxyGroup.children.forEach(starSystem => {
            // Get stored rotation speeds
            const { rotationSpeedX, rotationSpeedY, rotationSpeedZ, pulseSpeed, pulseOffset, jetScale } = starSystem.userData;
            
            // Rotate each star system
            starSystem.rotation.x += rotationSpeedX;
            starSystem.rotation.y += rotationSpeedY;
            starSystem.rotation.z += rotationSpeedZ;
            
            // Pulse the star and its jets
            const pulseFactor = Math.sin(elapsedTime * pulseSpeed + pulseOffset) * 0.2 + 1;
            
            // Get star and glow (first two children)
            if (starSystem.children.length >= 2) {
                const star = starSystem.children[0];
                const glow = starSystem.children[1];
                const light = starSystem.children[2];
                
                // Pulse the star
                star.scale.set(pulseFactor, pulseFactor, pulseFactor);
                
                // Pulse the glow
                glow.scale.set(pulseFactor * 1.2, pulseFactor * 1.2, pulseFactor * 1.2);
                
                // Pulse the light intensity
                light.intensity = 1 + pulseFactor * 0.5;
                
                // Get jets (last child)
                if (starSystem.children.length >= 4) {
                    const jets = starSystem.children[3];
                    
                    // No need to modify jet particles individually, just scale the entire jets object
                    jets.scale.y = jetScale * pulseFactor;
                }
            }
        });
        
        // Animate rain
        const rainPositionsAttribute = rain.geometry.getAttribute('position');
        
        for (let i = 0; i < rainCount; i++) {
            const i3 = i * 3;
            
            // Move raindrop down
            rainPositionsAttribute.array[i3 + 1] -= rainVelocities[i];
            
            // Add slight horizontal movement for realism
            rainPositionsAttribute.array[i3] += Math.sin(elapsedTime + i) * 0.001;
            
            // Reset raindrop if it's out of view
            if (rainPositionsAttribute.array[i3 + 1] < -pageHeight * scaleY) {
                rainPositionsAttribute.array[i3] = (Math.random() * pageWidth - pageWidth / 2) * scaleX;
                rainPositionsAttribute.array[i3 + 1] = (pageHeight / 2 + Math.random() * 10) * scaleY;
                
                // Randomize velocity slightly when resetting
                const z = rainPositionsAttribute.array[i3 + 2];
                const depthFactor = 1 - (z + pageDepth/2) / pageDepth;
                rainVelocities[i] = (Math.random() * 0.03 + 0.01) * (0.5 + depthFactor);
            }
        }
        
        rainPositionsAttribute.needsUpdate = true;
        
        // Render the scene
        renderer.render(scene, camera);
        
        // Call animate again on the next frame
        requestAnimationFrame(animate);
    };
    
    // Track mouse movement
    window.mouseX = 0;
    window.mouseY = 0;
    
    document.addEventListener('mousemove', (event) => {
        window.mouseX = event.clientX - window.innerWidth / 2;
        window.mouseY = event.clientY - window.innerHeight / 2;
    });
    
    // Start animation
    animate();
};

// Function to setup the background canvas for the entire page
const setupPageBackground = () => {
    // Check if we already have a canvas
    let canvas = document.getElementById('bg-canvas');
    
    // If no canvas exists, create one
    if (!canvas) {
        canvas = document.createElement('canvas');
        canvas.id = 'bg-canvas';
        
        // Set canvas styles for fullscreen background
        canvas.style.position = 'fixed';
        canvas.style.top = '0';
        canvas.style.left = '0';
        canvas.style.width = '100%';
        canvas.style.height = '100%';
        canvas.style.zIndex = '-1';
        canvas.style.pointerEvents = 'none'; // Allow clicks to pass through
    }
    
    // Add the canvas to the body as a fixed background
    if (canvas.parentElement !== document.body) {
        document.body.appendChild(canvas);
    }
    
    return canvas;
};

// Add CSS to make content readable over the background
const addBackgroundCSS = () => {
    // Create a style element if it doesn't exist
    let style = document.getElementById('background-styles');
    if (!style) {
        style = document.createElement('style');
        style.id = 'background-styles';
        document.head.appendChild(style);
        
        // Add CSS rules
        style.textContent = `
            body {
                background-color: transparent !important;
                position: relative;
                z-index: 1;
            }
            
            main, article, section, .content, .container {
                position: relative;
                z-index: 1;
                background-color: rgba(0, 5, 16, 0.7);
                padding: 20px;
                border-radius: 5px;
                color: #fff;
            }
            
            h1, h2, h3, h4, h5, h6 {
                color: #ffffff;
            }
            
            a {
                color: #80afff;
            }
            
            /* Style adjustments for text contrast */
            p, li, span, div {
                text-shadow: 0 0 5px rgba(0, 0, 0, 0.7);
            }
            
            /* Add a subtle background to text containers */
            article, .content, .container, .card, .post {
                box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
                backdrop-filter: blur(3px);
                -webkit-backdrop-filter: blur(3px);
                margin-bottom: 20px;
            }
        `;
    }
};

// Initialize on DOM load
document.addEventListener('DOMContentLoaded', () => {
    setupPageBackground();
    addBackgroundCSS();
    initThreeBackground();
    
    // Add a mutation observer to ensure the background works on dynamically loaded pages
    const observer = new MutationObserver((mutations) => {
        let needsReattach = false;
        
        mutations.forEach(mutation => {
            if (mutation.type === 'childList') {
                // Check if our canvas was removed
                const canvas = document.getElementById('bg-canvas');
                if (!canvas || !document.body.contains(canvas)) {
                    needsReattach = true;
                }
            }
        });
        
        if (needsReattach) {
            setupPageBackground();
            initThreeBackground();
        }
    });
    
    // Start observing the document body for changes
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
});