// First, ensure Three.js is loaded
function loadThreeJS(callback) {
    // Check if Three.js is already loaded
    if (window.THREE) {
        console.log('Three.js is already loaded');
        callback();
        return;
    }

    console.log('Loading Three.js library...');
    const script = document.createElement('script');
    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js';
    script.onload = function() {
        console.log('Three.js loaded successfully');
        callback();
    };
    script.onerror = function() {
        console.error('Failed to load Three.js. Please check your internet connection.');
        alert('Failed to load Three.js library. Please refresh the page and try again.');
    };
    document.head.appendChild(script);
}

// Initialize the galaxy background once Three.js is loaded
function initSombreroGalaxy() {
    try {
        // Get the canvas element
        const canvas = document.getElementById('bg-canvas');
        if (!canvas) {
            console.error('Canvas element not found');
            return;
        }
        
        console.log('Initializing Sombrero Galaxy background...');
        
        // Create scene
        const scene = new THREE.Scene();
        scene.background = new THREE.Color(0x000005);
        
        // Create camera
        const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 2000);
        camera.position.set(120, 80, 120);
        camera.lookAt(0, 0, 0);
        
        // Create renderer
        const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
        
        console.log('Renderer created with size:', window.innerWidth, 'x', window.innerHeight);
        
        // Create a simple test object to verify rendering
        const testGeometry = new THREE.SphereGeometry(50, 32, 32);
        const testMaterial = new THREE.MeshBasicMaterial({ color: 0x0088ff, wireframe: true });
        const testSphere = new THREE.Mesh(testGeometry, testMaterial);
        scene.add(testSphere);
        
        console.log('Test object added to scene');
        
        // Create galaxy container
        const galaxy = new THREE.Group();
        scene.add(galaxy);
        
        // Create a simple star field for the background
        const starCount = 5000;
        const starGeometry = new THREE.BufferGeometry();
        const starPositions = new Float32Array(starCount * 3);
        
        for (let i = 0; i < starCount; i++) {
            const i3 = i * 3;
            starPositions[i3] = (Math.random() - 0.5) * 2000;
            starPositions[i3 + 1] = (Math.random() - 0.5) * 2000;
            starPositions[i3 + 2] = (Math.random() - 0.5) * 2000;
        }
        
        starGeometry.setAttribute('position', new THREE.BufferAttribute(starPositions, 3));
        
        const starMaterial = new THREE.PointsMaterial({
            color: 0xffffff,
            size: 1.5,
            sizeAttenuation: true
        });
        
        const stars = new THREE.Points(starGeometry, starMaterial);
        scene.add(stars);
        
        console.log('Stars added to scene');
        
        // Create central galaxy disk
        const diskGeometry = new THREE.CircleGeometry(80, 64);
        const diskMaterial = new THREE.MeshBasicMaterial({
            color: 0x4466aa,
            transparent: true,
            opacity: 0.4,
            side: THREE.DoubleSide
        });
        const disk = new THREE.Mesh(diskGeometry, diskMaterial);
        disk.rotation.x = Math.PI / 2;
        galaxy.add(disk);
        
        // Create central bulge
        const bulgeGeometry = new THREE.SphereGeometry(20, 32, 16);
        const bulgeMaterial = new THREE.MeshBasicMaterial({
            color: 0xffffaa,
            transparent: true,
            opacity: 0.5
        });
        const bulge = new THREE.Mesh(bulgeGeometry, bulgeMaterial);
        bulge.scale.y = 0.6;
        galaxy.add(bulge);
        
        // Create dust lane
        const laneGeometry = new THREE.RingGeometry(30, 70, 64, 1);
        const laneMaterial = new THREE.MeshBasicMaterial({
            color: 0x000000,
            transparent: true,
            opacity: 0.8,
            side: THREE.DoubleSide
        });
        const lane = new THREE.Mesh(laneGeometry, laneMaterial);
        lane.rotation.x = Math.PI / 2;
        galaxy.add(lane);
        
        console.log('Galaxy basic structure created');
        
        // Create individual stars within the galaxy
        const galaxyStarCount = 20000; // Reduced for better performance
        const galaxyStarGeometry = new THREE.BufferGeometry();
        const galaxyStarPositions = new Float32Array(galaxyStarCount * 3);
        const galaxyStarVelocities = new Float32Array(galaxyStarCount);
        const galaxyStarRadii = new Float32Array(galaxyStarCount);
        
        for (let i = 0; i < galaxyStarCount; i++) {
            const i3 = i * 3;
            
            // Determine if star is in bulge or disk
            const isBulge = Math.random() < 0.3;
            let radius, height, angle;
            
            if (isBulge) {
                // Bulge stars
                radius = Math.pow(Math.random(), 2) * 25;
                height = (Math.random() - 0.5) * 20;
            } else {
                // Disk stars
                radius = 20 + Math.sqrt(Math.random()) * 60;
                height = (Math.random() - 0.5) * 5;
            }
            
            angle = Math.random() * Math.PI * 2;
            
            // Set positions
            galaxyStarPositions[i3] = radius * Math.cos(angle);
            galaxyStarPositions[i3 + 1] = height;
            galaxyStarPositions[i3 + 2] = radius * Math.sin(angle);
            
            // Store radius for rotation calculations
            galaxyStarRadii[i] = radius;
            
            // Calculate rotation velocity (Keplerian-like)
            // Closer stars move faster
            galaxyStarVelocities[i] = 0.5 / Math.sqrt(Math.max(radius, 1));
        }
        
        galaxyStarGeometry.setAttribute('position', new THREE.BufferAttribute(galaxyStarPositions, 3));
        
        const galaxyStarMaterial = new THREE.PointsMaterial({
            color: 0xffffff,
            size: 0.8,
            sizeAttenuation: true,
            transparent: true,
            opacity: 0.8
        });
        
        const galaxyStars = new THREE.Points(galaxyStarGeometry, galaxyStarMaterial);
        galaxy.add(galaxyStars);
        
        console.log('Galaxy stars added:', galaxyStarCount);
        
        // Animation variables
        let cameraAngle = 0;
        let cameraRadius = 170;
        let cameraHeight = 80;
        
        // Handle window resize
        window.addEventListener('resize', () => {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(window.innerWidth, window.innerHeight);
            console.log('Window resized to:', window.innerWidth, 'x', window.innerHeight);
        });
        
        // Mouse interaction
        let mouseX = 0;
        let mouseY = 0;
        let targetRotationX = 0;
        let targetRotationY = 0;
        let currentRotationX = 0;
        let currentRotationY = 0;
        
        window.addEventListener('mousemove', (event) => {
            mouseX = (event.clientX / window.innerWidth) * 2 - 1;
            mouseY = (event.clientY / window.innerHeight) * 2 - 1;
            
            targetRotationX = mouseX * 0.5;
            targetRotationY = mouseY * 0.3;
        });
        
        // Animation loop
        const clock = new THREE.Clock();
        
        function animate() {
            const delta = clock.getDelta();
            
            // Update camera position based on mouse
            currentRotationX += (targetRotationX - currentRotationX) * 0.05;
            currentRotationY += (targetRotationY - currentRotationY) * 0.05;
            
            // Update camera position for orbit
            cameraAngle += 0.05 * delta;
            const cameraX = cameraRadius * Math.cos(cameraAngle + currentRotationX);
            const cameraZ = cameraRadius * Math.sin(cameraAngle + currentRotationX);
            const cameraY = cameraHeight + currentRotationY * 40;
            
            camera.position.set(cameraX, cameraY, cameraZ);
            camera.lookAt(0, 0, 0);
            
            // Rotate test sphere
            testSphere.rotation.y += 0.01;
            
            // Rotate galaxy
            galaxy.rotation.y += 0.005 * delta;
            
            // Rotate stars within galaxy with differential rotation
            const posAttr = galaxyStars.geometry.getAttribute('position');
            
            for (let i = 0; i < galaxyStarCount; i++) {
                const i3 = i * 3;
                
                // Skip stars very close to center
                if (galaxyStarRadii[i] < 1) continue;
                
                // Current position
                const x = posAttr.array[i3];
                const z = posAttr.array[i3 + 2];
                
                // Calculate current angle
                let angle = Math.atan2(z, x);
                
                // Update angle based on distance
                angle += galaxyStarVelocities[i] * delta;
                
                // Set new position
                posAttr.array[i3] = galaxyStarRadii[i] * Math.cos(angle);
                posAttr.array[i3 + 2] = galaxyStarRadii[i] * Math.sin(angle);
            }
            
            posAttr.needsUpdate = true;
            
            // Render scene
            renderer.render(scene, camera);
            
            // Continue animation
            requestAnimationFrame(animate);
        }
        
        // Start animation
        animate();
        console.log('Animation started');
        
    } catch (error) {
        console.error('Error initializing galaxy:', error);
        alert('Error creating galaxy background: ' + error.message);
    }
}

// Function to setup the background canvas
function setupPageBackground() {
    try {
        console.log('Setting up page background...');
        
        // Check if we already have a canvas
        let canvas = document.getElementById('bg-canvas');
        
        // If no canvas exists, create one
        if (!canvas) {
            console.log('Creating new canvas element');
            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) {
            console.log('Attaching canvas to document body');
            document.body.appendChild(canvas);
        }
        
        console.log('Canvas setup complete');
        return canvas;
        
    } catch (error) {
        console.error('Error setting up canvas:', error);
        alert('Error setting up background: ' + error.message);
    }
}

// Add CSS to make content readable over the galaxy background
function addBackgroundCSS() {
    try {
        console.log('Adding background CSS...');
        
        // 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: #000005 !important;
                    position: relative;
                    z-index: 1;
                    color: #fff;
                }
                
                main, article, section, .content, .container {
                    position: relative;
                    z-index: 1;
                    background-color: rgba(0, 5, 15, 0.7);
                    padding: 20px;
                    border-radius: 5px;
                    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
                }
                
                h1, h2, h3, h4, h5, h6 {
                    color: #ffffff;
                    text-shadow: 0 0 10px rgba(150, 170, 255, 0.5);
                }
                
                a {
                    color: #aaccff;
                    text-shadow: 0 0 5px rgba(170, 204, 255, 0.5);
                }
                
                /* 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 {
                    backdrop-filter: blur(5px);
                    -webkit-backdrop-filter: blur(5px);
                    margin-bottom: 20px;
                    border: 1px solid rgba(150, 170, 255, 0.2);
                }
            `;
        }
        
        console.log('Background CSS added');
        
    } catch (error) {
        console.error('Error adding CSS:', error);
    }
}

// Initialize everything when the page loads
function initializeBackground() {
    console.log('Starting background initialization...');
    setupPageBackground();
    addBackgroundCSS();
    loadThreeJS(initSombreroGalaxy);
}

// Wait for DOM to be fully loaded
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeBackground);
} else {
    // DOM already loaded, initialize now
    initializeBackground();
}

// 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) {
        console.log('Canvas was removed, reattaching...');
        setupPageBackground();
        initSombreroGalaxy();
    }
});

// Start observing the document body for changes
observer.observe(document.body, {
    childList: true,
    subtree: true
});