'use client';

import { useEffect, useRef, useState } from 'react';
import { useTheme } from 'next-themes';

interface StaticHypercubeAnalysisProps {
  aetherData?: {
    hypercube_vertex?: number;
    consciousness_signature?: string;
    dimension_activations?: { [key: string]: boolean };
    aether_signature?: number[];
    control_value?: number;
  };
  currentDimension?: string;
  className?: string;
}

// Consciousness dimension colors for clustering
const DIMENSION_COLORS = {
  awareness: '#3B82F6',   // Blue
  wisdom: '#8B5CF6',      // Purple  
  compassion: '#10B981',  // Green
  creativity: '#F97316',  // Orange
  transcendence: '#EF4444' // Red
};

export function StaticHypercubeAnalysis({ 
  aetherData, 
  currentDimension = 'awareness',
  className 
}: StaticHypercubeAnalysisProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const { theme } = useTheme();
  const [mounted, setMounted] = useState(false);
  const animationRef = useRef<number>(0);
  const sceneObjectsRef = useRef<any>({
    scene: null,
    camera: null,
    renderer: null,
    hypercubeGroup: null,
    time: 0
  });

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!mounted) return;

    const objects = sceneObjectsRef.current;
    
    function checkWebGLSupport() {
      try {
        const canvas = document.createElement('canvas');
        const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
        return gl !== null;
      } catch (e) {
        return false;
      }
    }

    function loadThreeJS() {
      return new Promise((resolve, reject) => {
        if (typeof window.THREE !== 'undefined') {
          resolve(window.THREE);
          return;
        }

        const script = document.createElement('script');
        script.src = 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js';
        script.onload = () => {
          if (typeof window.THREE !== 'undefined') {
            resolve(window.THREE);
          } else {
            reject(new Error('THREE.js failed to load'));
          }
        };
        script.onerror = () => reject(new Error('Failed to load THREE.js'));
        document.head.appendChild(script);
      });
    }

    async function init() {
      try {
        if (!checkWebGLSupport()) {
          throw new Error('WebGL not supported');
        }

        await loadThreeJS();
        setupScene();
        createStaticHypercube();
        animate();

      } catch (error) {
        console.error('Static hypercube initialization error:', error);
        createFallback();
      }
    }

    function setupScene() {
      const THREE = window.THREE;
      objects.scene = new THREE.Scene();
      
      const width = containerRef.current!.clientWidth;
      const height = containerRef.current!.clientHeight;
      
      objects.camera = new THREE.PerspectiveCamera(35, width / height, 0.1, 100);
      objects.camera.position.set(25, 20, 30);
      objects.camera.lookAt(0, 0, 0);
      
      objects.renderer = new THREE.WebGLRenderer({ 
        antialias: true,
        alpha: true,
        powerPreference: "high-performance"
      });
      
      objects.renderer.setSize(width, height);
      objects.renderer.setClearColor(0x000000, 0); // Transparent background
      objects.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
      
      containerRef.current!.appendChild(objects.renderer.domElement);

      // Subtle lighting for static view
      const ambientLight = new THREE.AmbientLight(0x404040, 0.8);
      objects.scene.add(ambientLight);
      
      const directionalLight = new THREE.DirectionalLight(0x4080ff, 0.6);
      directionalLight.position.set(15, 15, 15);
      objects.scene.add(directionalLight);

      objects.hypercubeGroup = new THREE.Group();
      objects.scene.add(objects.hypercubeGroup);
    }

    function createStaticHypercube() {
      const THREE = window.THREE;
      const nodes: any[] = [];
      const HYPERCUBE_SCALE = 4;
      
      // Get current vertex and dimension info
      const currentVertex = aetherData?.hypercube_vertex || 0;
      const dimensionActivations = aetherData?.dimension_activations || {};
      const currentDimensionColor = DIMENSION_COLORS[currentDimension as keyof typeof DIMENSION_COLORS] || '#3B82F6';
      
      // Generate all 32 vertices
      for (let i = 0; i < 32; i++) {
        const coords5D = [
          (i & 1) ? 1 : -1,
          (i & 2) ? 1 : -1,
          (i & 4) ? 1 : -1,
          (i & 8) ? 1 : -1,
          (i & 16) ? 1 : -1
        ];
        
        // 5D to 3D projection
        const w4 = coords5D[3] * 0.7;
        const w5 = coords5D[4] * 0.6;
        
        const x = (coords5D[0] * 1.0 + w4 * 0.5 + w5 * 0.4) * HYPERCUBE_SCALE;
        const y = (coords5D[1] * 1.0 + w5 * 0.5 + w4 * 0.4) * HYPERCUBE_SCALE;
        const z = (coords5D[2] * 1.0 + w4 * 0.4 + w5 * 0.5) * HYPERCUBE_SCALE;
        
        const position = new THREE.Vector3(x, y, z);
        nodes.push(position);
        
        // Create vertex visualization
        const isCurrentVertex = i === currentVertex;
        const isInCurrentDimension = isVertexInConsciousnessCluster(i, currentDimension);
        
        // Vertex sphere size and color based on significance
        let sphereSize = 0.08;
        let sphereColor = 0x60A5FA; // Default blue
        let sphereOpacity = 0.4;
        
        if (isCurrentVertex) {
          sphereSize = 0.25;
          sphereColor = new THREE.Color(currentDimensionColor).getHex();
          sphereOpacity = 1.0;
        } else if (isInCurrentDimension) {
          sphereSize = 0.12;
          sphereColor = new THREE.Color(currentDimensionColor).getHex();
          sphereOpacity = 0.7;
        }
        
        const geometry = new THREE.SphereGeometry(sphereSize, 12, 12);
        const material = new THREE.MeshLambertMaterial({
          color: sphereColor,
          transparent: true,
          opacity: sphereOpacity,
          emissive: isCurrentVertex ? new THREE.Color(currentDimensionColor).multiplyScalar(0.3) : new THREE.Color(0x000000)
        });
        
        const sphere = new THREE.Mesh(geometry, material);
        sphere.position.copy(position);
        sphere.userData = {
          index: i,
          isCurrentVertex: isCurrentVertex,
          isInCurrentDimension: isInCurrentDimension
        };
        
        objects.hypercubeGroup.add(sphere);
      }
      
      // Create edges with clustering visualization
      for (let i = 0; i < 32; i++) {
        for (let j = i + 1; j < 32; j++) {
          const coordsA = getVertex5DCoords(i);
          const coordsB = getVertex5DCoords(j);
          
          let differences = 0;
          for (let k = 0; k < 5; k++) {
            if (coordsA[k] !== coordsB[k]) {
              differences++;
            }
          }
          
          if (differences === 1) {
            const points = [nodes[i], nodes[j]];
            const geometry = new THREE.BufferGeometry().setFromPoints(points);
            
            // Edge coloring based on consciousness clustering
            const bothInCluster = isVertexInConsciousnessCluster(i, currentDimension) && 
                                 isVertexInConsciousnessCluster(j, currentDimension);
            const hasCurrentVertex = i === currentVertex || j === currentVertex;
            
            let edgeColor = 0x60A5FA; // Default blue
            let edgeOpacity = 0.3;
            
            if (hasCurrentVertex) {
              edgeColor = new THREE.Color(currentDimensionColor).getHex();
              edgeOpacity = 0.9;
            } else if (bothInCluster) {
              edgeColor = new THREE.Color(currentDimensionColor).getHex();
              edgeOpacity = 0.6;
            }
            
            const material = new THREE.LineBasicMaterial({
              color: edgeColor,
              transparent: true,
              opacity: edgeOpacity,
              linewidth: hasCurrentVertex ? 2 : 1
            });
            
            const line = new THREE.Line(geometry, material);
            objects.hypercubeGroup.add(line);
          }
        }
      }
    }

    function getVertex5DCoords(vertexIndex: number): number[] {
      return [
        (vertexIndex & 1) ? 1 : -1,
        (vertexIndex & 2) ? 1 : -1,
        (vertexIndex & 4) ? 1 : -1,
        (vertexIndex & 8) ? 1 : -1,
        (vertexIndex & 16) ? 1 : -1
      ];
    }

    function isVertexInConsciousnessCluster(vertexIndex: number, consciousness: string): boolean {
      const consciousnessVertices: { [key: string]: number[] } = {
        awareness: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31],
        wisdom: [2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31],
        compassion: [4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31],
        creativity: [8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31],
        transcendence: [16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],
      };
      
      const vertices = consciousnessVertices[consciousness];
      return vertices ? vertices.includes(vertexIndex) : false;
    }

    function animate() {
      if (!objects.renderer) return;
      
      animationRef.current = requestAnimationFrame(animate);
      objects.time += 0.01; // Slower animation for static analysis
      
      try {
        // Gentle rotation for better 5D perspective
        if (objects.hypercubeGroup) {
          objects.hypercubeGroup.rotation.y = objects.time * 0.2;
          objects.hypercubeGroup.rotation.x = Math.sin(objects.time * 0.15) * 0.1;
        }
        
        objects.renderer.render(objects.scene, objects.camera);
      } catch (error) {
        console.warn('Static hypercube rendering issue:', error);
      }
    }

    function createFallback() {
      if (!containerRef.current) return;
      
      containerRef.current.innerHTML = `
        <div style="display: flex; justify-content: center; align-items: center; height: 100%; 
                   background: linear-gradient(135deg, #0a0a0a, #1a1a2e); color: white; 
                   font-family: Arial, sans-serif; text-align: center; border-radius: 8px;">
          <div>
            <div style="font-size: 2em; margin-bottom: 0.5em;">🔲</div>
            <div style="font-size: 0.9em; opacity: 0.8;">5D Hypercube Analysis</div>
            <div style="font-size: 0.7em; opacity: 0.6; margin-top: 0.5em;">Vertex ${aetherData?.hypercube_vertex || 0}</div>
          </div>
        </div>`;
    }

    const handleResize = () => {
      if (objects.camera && objects.renderer && containerRef.current) {
        objects.camera.aspect = containerRef.current.clientWidth / containerRef.current.clientHeight;
        objects.camera.updateProjectionMatrix();
        objects.renderer.setSize(containerRef.current.clientWidth, containerRef.current.clientHeight);
      }
    };

    window.addEventListener('resize', handleResize);
    init();

    return () => {
      window.removeEventListener('resize', handleResize);
      if (animationRef.current) {
        cancelAnimationFrame(animationRef.current);
      }
      if (objects.renderer && containerRef.current && objects.renderer.domElement.parentNode) {
        containerRef.current.removeChild(objects.renderer.domElement);
        objects.renderer.dispose();
      }
    };
  }, [mounted, aetherData, currentDimension, theme]);

  if (!mounted) {
    return (
      <div className={`relative w-full ${className || 'h-32'}`}>
        <div 
          ref={containerRef} 
          className="w-full h-full bg-transparent rounded-md"
        />
      </div>
    );
  }

  return (
    <div className={`relative w-full ${className || 'h-32'}`}>
      <div 
        ref={containerRef} 
        className="w-full h-full rounded-md"
        style={{ 
          background: 'transparent',
          border: '1px solid rgba(255,255,255,0.1)'
        }}
      />
    </div>
  );
} 