const initRainingFireBackground = () => {
    // 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: false, antialias: true });
    
    // Set renderer size and pixel ratio
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
    
    // Create dark background
    scene.background = new THREE.Color(0x000000);
    
    // Create raining flames
    const flameCount = 5000; // Increased from 300 for better edge coverage
    const flameGeometry = new THREE.BufferGeometry();
    const flamePositions = new Float32Array(flameCount * 3);
    const flameSizes = new Float32Array(flameCount);
    const flameColors = new Float32Array(flameCount * 3);
    const flameLifetimes = new Float32Array(flameCount);
    const flameMaxLifetimes = new Float32Array(flameCount);
    const flameRotations = new Float32Array(flameCount);
    const flameRotationSpeeds = new Float32Array(flameCount);
    const flameEdges = new Array(flameCount); // Track which edge each flame belongs to
    
    // Convert screen coordinates to camera space
    const getScaledCoords = () => {
        const fov = camera.fov * (Math.PI / 180);
        const height = 2 * Math.tan(fov / 2) * Math.abs(camera.position.z);
        const width = height * camera.aspect;
        return { width, height };
    };
    
    // Initialize flame particles
    function initFlames() {
        const { width, height } = getScaledCoords();
        
        for (let i = 0; i < flameCount; i++) {
            resetFlame(i, true, width, height);
        }
    }
    
    // Reset a flame particle
    function resetFlame(index, initial = false, width, height) {
        const i3 = index * 3;
        
        // Determine which edge this flame will appear on
        // 0 = top, 1 = right, 2 = bottom, 3 = left
        const edge = Math.floor(Math.random() * 4);
        
        // Add margin width - how thick the fire border is
        const marginWidth = width * 0.15; // 15% of screen width on each side
        const marginHeight = height * 0.15; // 15% of screen height on top/bottom
        
        // Position based on selected edge
        switch(edge) {
            case 0: // Top edge
                flamePositions[i3] = (Math.random() - 0.5) * width; // Full width
                flamePositions[i3 + 1] = height/2 - Math.random() * marginHeight; // Top margin
                break;
            case 1: // Right edge
                flamePositions[i3] = width/2 - Math.random() * marginWidth; // Right margin
                flamePositions[i3 + 1] = (Math.random() - 0.5) * height; // Full height
                break;
            case 2: // Bottom edge
                flamePositions[i3] = (Math.random() - 0.5) * width; // Full width
                flamePositions[i3 + 1] = -height/2 + Math.random() * marginHeight; // Bottom margin
                break;
            case 3: // Left edge
                flamePositions[i3] = -width/2 + Math.random() * marginWidth; // Left margin
                flamePositions[i3 + 1] = (Math.random() - 0.5) * height; // Full height
                break;
        }
        
        // Save the edge this flame belongs to for animation
        flameEdges[index] = edge;
        
        // Depth - varies to create parallax
        flamePositions[i3 + 2] = Math.random() * 5 - 2.5;
        
        // Size varies by depth - closer flames are larger
        const depthFactor = (flamePositions[i3 + 2] + 2.5) / 5; // 0 to 1, deeper = smaller
        flameSizes[index] = (0.15 + Math.random() * 0.2) * (0.3 + depthFactor * 0.7);
        
        // Random lifetime 
        flameMaxLifetimes[index] = 2 + Math.random() * 3; // 2-5 seconds
        flameLifetimes[index] = flameMaxLifetimes[index];
        
        // Set rotation and rotation speed
        flameRotations[index] = Math.random() * Math.PI * 2;
        flameRotationSpeeds[index] = (Math.random() - 0.5) * 2;
        
        // Flame colors - red to orange to yellow
        const colorType = Math.random();
        
        if (colorType < 0.3) {
            // Yellower flames (hotter)
            flameColors[i3] = 1.0;
            flameColors[i3 + 1] = 0.8 + Math.random() * 0.2;
            flameColors[i3 + 2] = 0.2 + Math.random() * 0.3;
        } else if (colorType < 0.7) {
            // Orange flames
            flameColors[i3] = 1.0;
            flameColors[i3 + 1] = 0.5 + Math.random() * 0.3;
            flameColors[i3 + 2] = 0.1 + Math.random() * 0.2;
        } else {
            // Redder flames
            flameColors[i3] = 1.0;
            flameColors[i3 + 1] = 0.3 + Math.random() * 0.2;
            flameColors[i3 + 2] = 0.05 + Math.random() * 0.15;
        }
    }
    
    // Initialize all flames
    const { width, height } = getScaledCoords();
    initFlames(width, height);
    
    // Set up geometry attributes
    flameGeometry.setAttribute('position', new THREE.BufferAttribute(flamePositions, 3));
    flameGeometry.setAttribute('size', new THREE.BufferAttribute(flameSizes, 1));
    flameGeometry.setAttribute('color', new THREE.BufferAttribute(flameColors, 3));
    flameGeometry.setAttribute('lifetime', new THREE.BufferAttribute(flameLifetimes, 1));
    flameGeometry.setAttribute('maxLifetime', new THREE.BufferAttribute(flameMaxLifetimes, 1));
    flameGeometry.setAttribute('rotation', new THREE.BufferAttribute(flameRotations, 1));
    
    // Create flame shader material
    const flameMaterial = new THREE.ShaderMaterial({
        uniforms: {
            time: { value: 0 }
        },
        vertexShader: `
            attribute float size;
            attribute vec3 color;
            attribute float lifetime;
            attribute float maxLifetime;
            attribute float rotation;
            
            varying vec3 vColor;
            varying float vLifetime;
            varying float vRotation;
            
            void main() {
                vColor = color;
                vLifetime = lifetime / maxLifetime; // Normalized 0-1
                vRotation = rotation;
                
                vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
                gl_PointSize = size * (100.0 / -mvPosition.z);
                gl_Position = projectionMatrix * mvPosition;
            }
        `,
        fragmentShader: `
            varying vec3 vColor;
            varying float vLifetime;
            varying float vRotation;
            
            // Function to create a 2D rotation matrix
            mat2 rotate2D(float angle) {
                float s = sin(angle);
                float c = cos(angle);
                return mat2(c, -s, s, c);
            }
            
            // Traditional teardrop flame shape with orientation based on edge
            float flameShape(vec2 uv, float lifetime, float rotation) {
                // Apply rotation to the UV coordinates
                uv = rotate2D(rotation) * uv;
                
                // Traditional teardrop flame shape
                float shape = 1.0 - length(uv * vec2(1.0, 1.3 - uv.y * 0.6)); // Narrower at top
                
                // Add some random variation to flame edge
                float noiseEdge = sin(uv.x * 20.0) * sin(uv.y * 20.0) * 0.1;
                shape += noiseEdge;
                
                // Apply lifetime factor - flame gets smaller as it burns out
                float lifeFactor = smoothstep(0.0, 0.3, lifetime);
                shape *= lifeFactor;
                
                // Define sharp edges
                return smoothstep(0.2, 0.5, shape);
            }
            
            void main() {
                // Convert from 0-1 space to -1 to 1 space
                vec2 uv = gl_PointCoord * 2.0 - 1.0;
                
                // Get flame shape
                float flame = flameShape(uv, vLifetime, vRotation);
                
                // Base color from vertex with gradient based on Y position
                vec3 baseColor = vColor;
                
                // Yellow-hot inner core
                float core = 1.0 - length(uv * vec2(1.0, 2.0));
                vec3 innerColor = vec3(1.0, 0.9, 0.6);
                
                // Blend between inner and outer colors
                vec3 flameColor = mix(baseColor, innerColor, smoothstep(0.2, 0.8, core) * 0.7);
                
                // Apply lifetime gradient (yellower when newer, redder when older)
                flameColor = mix(vec3(1.0, 0.2, 0.0), flameColor, vLifetime);
                
                // Adjust opacity based on flame shape
                float alpha = flame;
                
                // Higher intensity at the center
                flameColor *= 1.0 + core * 0.5;
                
                gl_FragColor = vec4(flameColor, alpha);
                
                // Discard pixels outside the flame shape for crisp edges
                if (flame < 0.01) discard;
            }
        `,
        transparent: true,
        blending: THREE.AdditiveBlending,
        depthWrite: false
    });
    
    // Create flames
    const flames = new THREE.Points(flameGeometry, flameMaterial);
    scene.add(flames);
    
    // Add more dramatic lighting for the margins
    const ambientLight = new THREE.AmbientLight(0x222222);
    scene.add(ambientLight);
    
    // Add corner lights for a more dramatic effect
    const cornerLights = [
        { position: [-width/2, height/2, 10], color: 0xFF5500, intensity: 1.2 },  // Top left
        { position: [width/2, height/2, 10], color: 0xFF7700, intensity: 1.2 },   // Top right
        { position: [-width/2, -height/2, 10], color: 0xFF3300, intensity: 1.2 }, // Bottom left
        { position: [width/2, -height/2, 10], color: 0xFF6600, intensity: 1.2 }   // Bottom right
    ];
    
    cornerLights.forEach(lightData => {
        const light = new THREE.PointLight(lightData.color, lightData.intensity, 50);
        light.position.set(...lightData.position);
        scene.add(light);
    });
    
    // Position camera
    camera.position.z = 10;
    
    // 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);
        
        // Recalculate scaled coordinates
        const { width, height } = getScaledCoords();
        
        // Update flame positions if they're out of bounds
        const posAttr = flameGeometry.getAttribute('position');
        
        for (let i = 0; i < flameCount; i++) {
            const i3 = i * 3;
            
            // If a flame is out of the new bounds horizontally, reset it
            if (Math.abs(posAttr.array[i3]) > width / 2) {
                resetFlame(i, false, width, height);
            }
        }
        
        posAttr.needsUpdate = true;
    });
    
    // Animation loop
    const clock = new THREE.Clock();
    
    const animate = () => {
        const elapsedTime = clock.getElapsedTime();
        const deltaTime = clock.getDelta();
        
        // Update shader time
        flameMaterial.uniforms.time.value = elapsedTime;
        
        // Animate flames
        const positionAttribute = flameGeometry.getAttribute('position');
        const sizeAttribute = flameGeometry.getAttribute('size');
        const lifetimeAttribute = flameGeometry.getAttribute('lifetime');
        const rotationAttribute = flameGeometry.getAttribute('rotation');
        const { width, height } = getScaledCoords();
        
        for (let i = 0; i < flameCount; i++) {
            const i3 = i * 3;
            
            // Update lifetime
            lifetimeAttribute.array[i] -= deltaTime;
            
            // Get the edge this flame belongs to
            const edge = flameEdges[i];
            
            // Update position based on edge - flames move inward from the borders
            switch(edge) {
                case 0: // Top edge - move downward 
                    positionAttribute.array[i3 + 1] -= (0.3 + Math.random() * 0.3) * deltaTime;
                    positionAttribute.array[i3] += Math.sin(i + elapsedTime) * 0.01; // Gentle side-to-side
                    break;
                case 1: // Right edge - move leftward
                    positionAttribute.array[i3] -= (0.3 + Math.random() * 0.3) * deltaTime;
                    positionAttribute.array[i3 + 1] += Math.sin(i + elapsedTime) * 0.01; // Gentle up-down
                    break;
                case 2: // Bottom edge - move upward
                    positionAttribute.array[i3 + 1] += (0.3 + Math.random() * 0.3) * deltaTime;
                    positionAttribute.array[i3] += Math.sin(i + elapsedTime) * 0.01; // Gentle side-to-side
                    break;
                case 3: // Left edge - move rightward
                    positionAttribute.array[i3] += (0.3 + Math.random() * 0.3) * deltaTime;
                    positionAttribute.array[i3 + 1] += Math.sin(i + elapsedTime) * 0.01; // Gentle up-down
                    break;
            }
            
            // Update rotation
            rotationAttribute.array[i] += flameRotationSpeeds[i] * deltaTime;
            
            // Update size - flames shrink as they burn out
            const lifetimeRatio = lifetimeAttribute.array[i] / flameMaxLifetimes[i];
            sizeAttribute.array[i] = flameSizes[i] * (0.5 + lifetimeRatio * 0.5);
            
            // Calculate distance from center
            const centerX = positionAttribute.array[i3];
            const centerY = positionAttribute.array[i3 + 1];
            const distFromCenter = Math.sqrt(centerX*centerX + centerY*centerY);
            
            // If flame is burnt out, off screen, or moved too far inward, reset it
            const marginThreshold = Math.min(width, height) * 0.25; // How far flames can move inward
            if (lifetimeAttribute.array[i] <= 0 || 
                Math.abs(positionAttribute.array[i3]) > width/2 || 
                Math.abs(positionAttribute.array[i3 + 1]) > height/2 ||
                distFromCenter < marginThreshold) {
                resetFlame(i, false, width, height);
            }
        }
        
        // Update all attributes
        positionAttribute.needsUpdate = true;
        sizeAttribute.needsUpdate = true;
        lifetimeAttribute.needsUpdate = true;
        rotationAttribute.needsUpdate = true;
        
        // Render the scene
        renderer.render(scene, camera);
        
        // Call animate again on the next frame
        requestAnimationFrame(animate);
    };
    
    // 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 fire 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: #000000 !important;
                position: relative;
                z-index: 1;
            }
            
            main, article, section, .content, .container {
                position: relative;
                z-index: 1;
                background-color: rgba(0, 0, 0, 0.7);
                padding: 20px;
                border-radius: 5px;
                color: #fff;
            }
            
            h1, h2, h3, h4, h5, h6 {
                color: #ffffff;
                text-shadow: 0 0 10px rgba(255, 100, 0, 0.5);
            }
            
            a {
                color: #FFA500;
                text-shadow: 0 0 5px rgba(255, 165, 0, 0.3);
            }
            
            /* Style adjustments for text contrast */
            p, li, span, div {
                text-shadow: 0 0 5px rgba(0, 0, 0, 0.9);
            }
            
            /* Add a subtle background to text containers */
            article, .content, .container, .card, .post {
                box-shadow: 0 0 20px rgba(255, 100, 0, 0.2);
                backdrop-filter: blur(5px);
                -webkit-backdrop-filter: blur(5px);
                margin-bottom: 20px;
                border: 1px solid rgba(255, 100, 0, 0.2);
            }
            
            /* Style form elements to be readable on fire background */
            input, textarea, select, button {
                background-color: rgba(40, 40, 40, 0.8);
                border: 1px solid rgba(255, 150, 50, 0.5);
                color: #fff;
            }
            
            button, .button, input[type="submit"] {
                background-color: rgba(255, 100, 0, 0.7);
                color: white;
                border: 1px solid rgba(255, 200, 100, 0.7);
                text-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
            }
        `;
    }
};

// Initialize on DOM load
document.addEventListener('DOMContentLoaded', () => {
    setupPageBackground();
    addBackgroundCSS();
    initRainingFireBackground();
    
    // 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();
            initRainingFireBackground();
        }
    });
    
    // Start observing the document body for changes
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
});