const initOctagonalMetaBackground = () => {
    // Get the canvas element
    const container = document.getElementById('bg-container');
    if (!container) return;
    
    // Configuration options
    const CONFIG = {
        gridSize: 3, // Size in mm for each octagon
        columns: Math.ceil(window.innerWidth / 20) + 5, // Add extra columns to ensure coverage 
        rows: Math.ceil(window.innerHeight / 20) + 5,
        baseColor: '#222233',
        highlightColor: '#505090',
        shadowColor: '#15151c',
        accentColor: '#8080ff',
        parallaxIntensity: 0.03, // How strong the parallax effect is
        parallaxLayers: 5,      // How many depth layers to create
        animationDuration: 0.8,  // Animation duration in seconds
        patternFrequency: 2      // Frequency of meta-pattern repeats
    };
    
    // Create SVG element
    const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    svg.setAttribute('width', '100%');
    svg.setAttribute('height', '100%');
    svg.style.position = 'absolute';
    svg.style.top = '0';
    svg.style.left = '0';
    svg.style.zIndex = '-1';
    
    // Add a filter for drop shadows
    const defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
    
    // Create filter for soft shadows
    const filter = document.createElementNS('http://www.w3.org/2000/svg', 'filter');
    filter.setAttribute('id', 'shadow-filter');
    filter.setAttribute('x', '-50%');
    filter.setAttribute('y', '-50%');
    filter.setAttribute('width', '200%');
    filter.setAttribute('height', '200%');
    
    const feGaussianBlur = document.createElementNS('http://www.w3.org/2000/svg', 'feGaussianBlur');
    feGaussianBlur.setAttribute('in', 'SourceAlpha');
    feGaussianBlur.setAttribute('stdDeviation', '1');
    filter.appendChild(feGaussianBlur);
    
    const feOffset = document.createElementNS('http://www.w3.org/2000/svg', 'feOffset');
    feOffset.setAttribute('dx', '0.5');
    feOffset.setAttribute('dy', '0.5');
    filter.appendChild(feOffset);
    
    const feComponentTransfer = document.createElementNS('http://www.w3.org/2000/svg', 'feComponentTransfer');
    const feFuncA = document.createElementNS('http://www.w3.org/2000/svg', 'feFuncA');
    feFuncA.setAttribute('type', 'linear');
    feFuncA.setAttribute('slope', '0.5');
    feComponentTransfer.appendChild(feFuncA);
    filter.appendChild(feComponentTransfer);
    
    const feMerge = document.createElementNS('http://www.w3.org/2000/svg', 'feMerge');
    const feMergeNode1 = document.createElementNS('http://www.w3.org/2000/svg', 'feMergeNode');
    const feMergeNode2 = document.createElementNS('http://www.w3.org/2000/svg', 'feMergeNode');
    feMergeNode2.setAttribute('in', 'SourceGraphic');
    feMerge.appendChild(feMergeNode1);
    feMerge.appendChild(feMergeNode2);
    filter.appendChild(feMerge);
    
    defs.appendChild(filter);
    svg.appendChild(defs);
    
    // Add a gradient for realistic lighting
    const gradient = document.createElementNS('http://www.w3.org/2000/svg', 'radialGradient');
    gradient.setAttribute('id', 'octagon-gradient');
    gradient.setAttribute('cx', '50%');
    gradient.setAttribute('cy', '50%');
    gradient.setAttribute('r', '50%');
    
    const stop1 = document.createElementNS('http://www.w3.org/2000/svg', 'stop');
    stop1.setAttribute('offset', '0%');
    stop1.setAttribute('stop-color', CONFIG.highlightColor);
    
    const stop2 = document.createElementNS('http://www.w3.org/2000/svg', 'stop');
    stop2.setAttribute('offset', '70%');
    stop2.setAttribute('stop-color', CONFIG.baseColor);
    
    const stop3 = document.createElementNS('http://www.w3.org/2000/svg', 'stop');
    stop3.setAttribute('offset', '100%');
    stop3.setAttribute('stop-color', CONFIG.shadowColor);
    
    gradient.appendChild(stop1);
    gradient.appendChild(stop2);
    gradient.appendChild(stop3);
    defs.appendChild(gradient);
    
    // Add linear gradient for edge lighting
    const edgeGradient = document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient');
    edgeGradient.setAttribute('id', 'edge-gradient');
    edgeGradient.setAttribute('x1', '0%');
    edgeGradient.setAttribute('y1', '0%');
    edgeGradient.setAttribute('x2', '100%');
    edgeGradient.setAttribute('y2', '100%');
    
    const edgeStop1 = document.createElementNS('http://www.w3.org/2000/svg', 'stop');
    edgeStop1.setAttribute('offset', '0%');
    edgeStop1.setAttribute('stop-color', 'rgba(255, 255, 255, 0.2)');
    
    const edgeStop2 = document.createElementNS('http://www.w3.org/2000/svg', 'stop');
    edgeStop2.setAttribute('offset', '100%');
    edgeStop2.setAttribute('stop-color', 'rgba(0, 0, 0, 0.3)');
    
    edgeGradient.appendChild(edgeStop1);
    edgeGradient.appendChild(edgeStop2);
    defs.appendChild(edgeGradient);
    
    // Add pattern for texture overlay
    const pattern = document.createElementNS('http://www.w3.org/2000/svg', 'pattern');
    pattern.setAttribute('id', 'texture-pattern');
    pattern.setAttribute('patternUnits', 'userSpaceOnUse');
    pattern.setAttribute('width', '10');
    pattern.setAttribute('height', '10');
    
    const patternRect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
    patternRect.setAttribute('width', '10');
    patternRect.setAttribute('height', '10');
    patternRect.setAttribute('fill', 'none');
    
    const patternPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    patternPath.setAttribute('d', 'M0,0 L2,2 L0,4 M6,6 L8,8 L6,10');
    patternPath.setAttribute('stroke', 'rgba(255, 255, 255, 0.05)');
    patternPath.setAttribute('stroke-width', '0.5');
    
    pattern.appendChild(patternRect);
    pattern.appendChild(patternPath);
    defs.appendChild(pattern);
    
    // Create a function to generate an octagon path
    function createOctagonPath(x, y, size) {
        // Calculate octagon points - this creates a regular octagon
        const points = [];
        const radius = size / 2;
        for (let i = 0; i < 8; i++) {
            const angle = i * Math.PI / 4; // 8 sides, so 2π/8 = π/4
            const px = x + radius * Math.cos(angle);
            const py = y + radius * Math.sin(angle);
            points.push([px, py]);
        }
        
        // Create path
        return points.map((point, i) => 
            (i === 0 ? 'M' : 'L') + point[0] + ',' + point[1]
        ).join(' ') + 'Z';
    }
    
    // Generate depth values with perlin noise for a natural appearance
    function generateDepthMap() {
        const depthMap = [];
        const noiseScale = 0.1; // Adjust for smoother or rougher terrain
        
        for (let row = 0; row < CONFIG.rows; row++) {
            depthMap[row] = [];
            for (let col = 0; col < CONFIG.columns; col++) {
                // Create a pseudo-perlin noise function since we don't have a library
                const noise = 
                    Math.sin(col * noiseScale) * Math.cos(row * noiseScale) + 
                    Math.sin(col * noiseScale * 2.5) * Math.cos(row * noiseScale * 2.5) * 0.5 +
                    Math.sin(col * noiseScale * 5) * Math.cos(row * noiseScale * 5) * 0.25;
                
                // Normalize to 0-1 range
                const normalizedNoise = (noise + 1.5) / 3;
                
                // Create meta-pattern
                const metaRow = Math.floor(row / CONFIG.patternFrequency);
                const metaCol = Math.floor(col / CONFIG.patternFrequency);
                const metaPattern = (metaRow + metaCol) % 4;
                
                let depth = normalizedNoise;
                
                // Apply meta patterns
                switch(metaPattern) {
                    case 0:
                        // Raised plateau
                        depth = Math.min(1, depth * 1.4);
                        break;
                    case 1:
                        // Valleys
                        depth = Math.max(0, depth * 0.7);
                        break;
                    case 2:
                        // Normal with slight enhancement
                        depth = Math.pow(depth, 0.8);
                        break;
                    case 3:
                        // Checkered pattern
                        if ((row % 2 === 0 && col % 2 === 0) || (row % 2 === 1 && col % 2 === 1)) {
                            depth = Math.min(1, depth * 1.3);
                        } else {
                            depth = Math.max(0, depth * 0.6);
                        }
                        break;
                }
                
                depthMap[row][col] = depth;
            }
        }
        
        return depthMap;
    }
    
    // Calculate the octagon position with offset for a tiled layout
    function getOctagonPosition(row, col, size) {
        // For a tightly packed grid of octagons, we need to offset alternate rows
        const offsetX = col * size * 0.85; // Slightly overlap to avoid gaps
        const offsetY = row * size * 0.85;
        
        return {
            x: offsetX + (row % 2 === 0 ? 0 : size * 0.425), // Offset every other row
            y: offsetY
        };
    }
    
    // Generate the initial octagon grid
    function generateOctagons() {
        const depthMap = generateDepthMap();
        const size = CONFIG.gridSize;
        const octagons = [];
        
        // Create layers for parallax effect
        for (let layer = 0; layer < CONFIG.parallaxLayers; layer++) {
            const layerGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
            layerGroup.setAttribute('class', 'parallax-layer');
            layerGroup.setAttribute('data-depth', ((layer + 1) / CONFIG.parallaxLayers).toFixed(2));
            svg.appendChild(layerGroup);
            
            for (let row = 0; row < CONFIG.rows; row++) {
                for (let col = 0; col < CONFIG.columns; col++) {
                    // Skip some octagons in deeper layers for a more natural look
                    if (layer > 0 && Math.random() > 0.7) continue;
                    
                    const depth = depthMap[row][col];
                    
                    // Only render this octagon in this layer if it falls within the layer's depth range
                    const layerMin = layer / CONFIG.parallaxLayers;
                    const layerMax = (layer + 1) / CONFIG.parallaxLayers;
                    
                    if (depth < layerMin || depth >= layerMax) continue;
                    
                    // Get position with offset
                    const {x, y} = getOctagonPosition(row, col, size * 10); // Scale up from mm
                    
                    // Create octagon path
                    const octagonPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
                    const pathData = createOctagonPath(x, y, size * 10);
                    octagonPath.setAttribute('d', pathData);
                    
                    // Style based on depth
                    const brightness = 0.7 + depth * 0.6; // Brighter for higher depth
                    const hueShift = depth * 40; // Color variation
                    
                    // Parse the base color and adjust it
                    const baseColorMatch = CONFIG.baseColor.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
                    let r = parseInt(baseColorMatch[1], 16);
                    let g = parseInt(baseColorMatch[2], 16);
                    let b = parseInt(baseColorMatch[3], 16);
                    
                    // Apply brightness and hue shift
                    const adjustedColor = `rgb(${Math.min(255, Math.floor(r * brightness))}, ${Math.min(255, Math.floor(g * brightness))}, ${Math.min(255, Math.floor(b * brightness + hueShift))})`;
                    
                    // Use gradient fill with adjusted color
                    octagonPath.setAttribute('fill', `url(#octagon-gradient)`);
                    
                    // Add subtle texture
                    octagonPath.setAttribute('stroke', 'rgba(255, 255, 255, 0.1)');
                    octagonPath.setAttribute('stroke-width', '0.5');
                    
                    // Add filter
                    octagonPath.setAttribute('filter', 'url(#shadow-filter)');
                    
                    // Add depth as data attribute for parallax effect
                    octagonPath.setAttribute('data-depth', depth.toFixed(2));
                    
                    // Set transform origin for animations
                    octagonPath.style.transformOrigin = `${x}px ${y}px`;
                    
                    // Store position data for animation
                    octagonPath.setAttribute('data-x', x);
                    octagonPath.setAttribute('data-y', y);
                    octagonPath.setAttribute('data-row', row);
                    octagonPath.setAttribute('data-col', col);
                    
                    // Add to layer group
                    layerGroup.appendChild(octagonPath);
                    octagons.push(octagonPath);
                    
                    // Occasionally add a highlight for accent
                    if (Math.random() < 0.05) {
                        const highlight = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
                        highlight.setAttribute('cx', x);
                        highlight.setAttribute('cy', y);
                        highlight.setAttribute('r', size * 2);
                        highlight.setAttribute('fill', 'rgba(255, 255, 255, 0.1)');
                        highlight.setAttribute('filter', 'blur(3px)');
                        
                        layerGroup.appendChild(highlight);
                    }
                }
            }
        }
        
        return octagons;
    }
    
    // Set up parallax effect
    function setupParallax() {
        let mouseX = 0, mouseY = 0;
        
        // Track mouse position
        document.addEventListener('mousemove', (e) => {
            mouseX = (e.clientX / window.innerWidth) - 0.5;
            mouseY = (e.clientY / window.innerHeight) - 0.5;
            
            // Apply parallax effect to layers
            document.querySelectorAll('.parallax-layer').forEach(layer => {
                const depth = parseFloat(layer.getAttribute('data-depth'));
                const translateX = mouseX * CONFIG.parallaxIntensity * 100 * depth;
                const translateY = mouseY * CONFIG.parallaxIntensity * 100 * depth;
                
                layer.style.transform = `translate(${translateX}px, ${translateY}px)`;
            });
        });
        
        // Handle touch events for mobile
        document.addEventListener('touchmove', (e) => {
            if (e.touches.length > 0) {
                mouseX = (e.touches[0].clientX / window.innerWidth) - 0.5;
                mouseY = (e.touches[0].clientY / window.innerHeight) - 0.5;
                
                document.querySelectorAll('.parallax-layer').forEach(layer => {
                    const depth = parseFloat(layer.getAttribute('data-depth'));
                    const translateX = mouseX * CONFIG.parallaxIntensity * 100 * depth;
                    const translateY = mouseY * CONFIG.parallaxIntensity * 100 * depth;
                    
                    layer.style.transform = `translate(${translateX}px, ${translateY}px)`;
                });
            }
        });
        
        // Add subtle animation even without mouse movement
        function animateLayers() {
            const time = Date.now() * 0.001;
            
            document.querySelectorAll('.parallax-layer').forEach(layer => {
                const depth = parseFloat(layer.getAttribute('data-depth'));
                const baseX = Math.sin(time * 0.2) * 5 * depth;
                const baseY = Math.cos(time * 0.3) * 5 * depth;
                
                // Apply the base animation - only if there's no active mouse parallax
                if (Math.abs(mouseX) < 0.01 && Math.abs(mouseY) < 0.01) {
                    layer.style.transform = `translate(${baseX}px, ${baseY}px)`;
                }
            });
            
            requestAnimationFrame(animateLayers);
        }
        
        // Start the animation
        animateLayers();
    }
    
    // Add subtle pulsing animations to random octagons
    function animateOctagons(octagons) {
        // Animate a subset of octagons with subtle scaling/brightness changes
        octagons.forEach(octagon => {
            if (Math.random() < 0.3) { // Only animate 30% of octagons
                const duration = 3 + Math.random() * 4; // Random duration between 3-7s
                const delay = Math.random() * 5; // Random delay up to 5s
                
                // Add CSS animations
                octagon.style.animation = `pulse ${duration}s ease-in-out ${delay}s infinite alternate`;
            }
        });
        
        // Add keyframes for the pulse animation
        const style = document.createElement('style');
        style.textContent = `
            @keyframes pulse {
                0% {
                    transform: scale(1);
                    opacity: 1;
                }
                100% {
                    transform: scale(1.05);
                    opacity: 0.8;
                }
            }
        `;
        document.head.appendChild(style);
    }
    
    // Simulate POM (Parallax Occlusion Mapping) effect by adjusting layers on scroll
    function setupScrollEffect() {
        window.addEventListener('scroll', () => {
            const scrollY = window.scrollY;
            
            document.querySelectorAll('.parallax-layer').forEach(layer => {
                const depth = parseFloat(layer.getAttribute('data-depth'));
                const translateY = scrollY * depth * 0.05; // Subtle effect
                
                layer.style.transform = `translateY(${translateY}px)`;
            });
        });
    }
    
    // Initialize the octagonal background
    function init() {
        // Append SVG to container
        container.appendChild(svg);
        
        // Generate octagons
        const octagons = generateOctagons();
        
        // Set up parallax effect
        setupParallax();
        
        // Set up scroll effect
        setupScrollEffect();
        
        // Animate octagons
        animateOctagons(octagons);
        
        // Handle window resize
        window.addEventListener('resize', () => {
            // Update grid dimensions
            CONFIG.columns = Math.ceil(window.innerWidth / 20) + 5;
            CONFIG.rows = Math.ceil(window.innerHeight / 20) + 5;
            
            // Clear existing octagons
            while (svg.firstChild) {
                if (svg.firstChild === defs) {
                    svg.removeChild(svg.lastChild);
                } else {
                    svg.removeChild(svg.firstChild);
                }
            }
            
            // Re-append defs if removed
            if (!svg.contains(defs)) {
                svg.appendChild(defs);
            }
            
            // Regenerate octagons
            const newOctagons = generateOctagons();
            
            // Re-animate octagons
            animateOctagons(newOctagons);
        });
    }
    
    // Start initialization
    init();
};

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

// Add CSS to make content readable over the meta octagon 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 for the octagonal background
        style.textContent = `
            body {
                background-color: #111122 !important;
                position: relative;
                z-index: 1;
                color: #ffffff;
            }
            
            main, article, section, .content, .container {
                position: relative;
                z-index: 1;
                background-color: rgba(17, 17, 34, 0.75);
                padding: 20px;
                border-radius: 5px;
                color: #e0e0ff;
                backdrop-filter: blur(3px);
                -webkit-backdrop-filter: blur(3px);
            }
            
            h1, h2, h3, h4, h5, h6 {
                color: #ffffff;
                text-shadow: 0 0 10px rgba(128, 128, 255, 0.5);
            }
            
            a {
                color: #8080ff;
                text-shadow: 0 0 5px rgba(128, 128, 255, 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(0, 0, 40, 0.3);
                border: 1px solid rgba(128, 128, 255, 0.1);
                margin-bottom: 20px;
            }
            
            /* Style form elements */
            input, textarea, select, button {
                background-color: rgba(20, 20, 40, 0.8);
                border: 1px solid rgba(128, 128, 255, 0.3);
                color: #fff;
            }
            
            button, .button, input[type="submit"] {
                background-color: rgba(80, 80, 160, 0.7);
                color: white;
                border: 1px solid rgba(128, 128, 255, 0.5);
                text-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
            }
            
            /* Add a subtle glow effect to focused elements */
            a:hover, button:hover, .button:hover {
                text-shadow: 0 0 8px rgba(128, 128, 255, 0.8);
                box-shadow: 0 0 15px rgba(128, 128, 255, 0.3);
            }
        `;
    }
};

// Initialize on DOM load
document.addEventListener('DOMContentLoaded', () => {
    // Setup container
    setupPageBackground();
    addBackgroundCSS();
    
    // Initialize background
    initOctagonalMetaBackground();
    
    // 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 container was removed
                const container = document.getElementById('bg-container');
                if (!container || !document.body.contains(container)) {
                    needsReattach = true;
                }
            }
        });
        
        if (needsReattach) {
            setupPageBackground();
            initOctagonalMetaBackground();
        }
    });
    
    // Start observing the document body for changes
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
});