import React, { useRef, useMemo } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
import { OrbitControls, Stars } from '@react-three/drei';
import * as THREE from 'three';

// Komponen 3D: Blackhole Tarpit
function BlackholeTarpit() {
  const blackholeRef = useRef();
  const accretionDiskRef = useRef();

  useFrame((state, delta) => {
    if (blackholeRef.current) {
      blackholeRef.current.rotation.y -= delta * 0.5;
    }
    if (accretionDiskRef.current) {
      accretionDiskRef.current.rotation.z += delta * 2;
    }
  });

  return (
    <group>
      {/* Inti Blackhole (Singularity) */}
      <mesh ref={blackholeRef}>
        <sphereGeometry args={[1.5, 32, 32]} />
        <meshBasicMaterial color={0x000000} />
      </mesh>
      
      {/* Piringan Akresi (Accretion Disk) melambangkan Tarpit */}
      <mesh ref={accretionDiskRef} rotation={[Math.PI / 2.5, 0, 0]}>
        <ringGeometry args={[1.8, 3.5, 64]} />
        <meshBasicMaterial 
          color={0xa855f7} 
          side={THREE.DoubleSide} 
          transparent={true} 
          opacity={0.4} 
          blending={THREE.AdditiveBlending}
        />
      </mesh>
    </group>
  );
}

// Komponen 3D: Paket Serangan DDoS yang tersedot
function DDoSAttackers() {
  const particlesRef = useRef();
  
  // Membuat 500 partikel ancaman
  const particlesCount = 500;
  const positions = useMemo(() => {
    const pos = new Float32Array(particlesCount * 3);
    for(let i=0; i<particlesCount; i++) {
      // Muncul secara acak dari jarak jauh
      pos[i*3] = (Math.random() - 0.5) * 20;
      pos[i*3+1] = (Math.random() - 0.5) * 20;
      pos[i*3+2] = (Math.random() - 0.5) * 20;
    }
    return pos;
  }, []);

  useFrame((state, delta) => {
    if (!particlesRef.current) return;
    
    const posAttribute = particlesRef.current.geometry.attributes.position;
    const posArray = posAttribute.array;
    
    for(let i=0; i<particlesCount; i++) {
      let x = posArray[i*3];
      let y = posArray[i*3+1];
      let z = posArray[i*3+2];
      
      // Sedot perlahan menuju koordinat (0,0,0) / Blackhole
      const speed = delta * 2;
      x -= x * speed;
      y -= y * speed;
      z -= z * speed;
      
      // Jika sudah masuk ke Event Horizon, respawn partikel di luar
      if (Math.abs(x) < 0.5 && Math.abs(y) < 0.5 && Math.abs(z) < 0.5) {
        x = (Math.random() - 0.5) * 20;
        y = (Math.random() - 0.5) * 20;
        z = (Math.random() - 0.5) * 20;
      }
      
      posArray[i*3] = x;
      posArray[i*3+1] = y;
      posArray[i*3+2] = z;
    }
    posAttribute.needsUpdate = true;
  });

  return (
    <points ref={particlesRef}>
      <bufferGeometry>
        <bufferAttribute 
          attach="attributes-position"
          count={particlesCount}
          array={positions}
          itemSize={3}
        />
      </bufferGeometry>
      <pointsMaterial 
        size={0.1} 
        color={0xff0000} 
        transparent={true} 
        opacity={0.8}
        blending={THREE.AdditiveBlending}
      />
    </points>
  );
}

export default function M1CerberusFirewall() {
  return (
    <div style={{animation: 'fadeIn 0.5s ease-out', height: '100%', display: 'flex', flexDirection: 'column'}}>
      
      {/* UI Overlay */}
      <div className="glass-panel" style={{
        padding: '15px', marginBottom: '15px', display: 'flex', justifyContent: 'space-between', 
        alignItems: 'center', borderColor: '#a855f7'
      }}>
        <div>
          <h2 style={{margin: 0, color: '#a855f7', letterSpacing: '2px', textTransform: 'uppercase'}}>M1: The Cerberus Matrix</h2>
          <div style={{color: 'var(--text-muted)', fontSize: '0.8rem', fontFamily: 'monospace', marginTop: '5px'}}>
            Quantum Entropy Firewall. Bare-Metal Deep Packet Inspection.
          </div>
        </div>
        <div style={{textAlign: 'right'}}>
          <div style={{color: '#888', fontSize: '0.7rem', letterSpacing: '2px'}}>DEFENSE STATUS</div>
          <div style={{color: '#a855f7', fontWeight: 'bold', fontFamily: 'monospace'}}>
            BLACKHOLE TARPIT ACTIVE
          </div>
        </div>
      </div>

      {/* 3D WebGL Spatial Environment */}
      <div style={{flex: 1, borderRadius: '8px', overflow: 'hidden', border: '1px solid #2a004d', background: '#050011', position: 'relative'}}>
        
        {/* Holographic grid UI overlay */}
        <div style={{
          position: 'absolute', top: '20px', left: '20px', zIndex: 10,
          background: 'rgba(168, 85, 247, 0.1)', padding: '10px', borderLeft: '2px solid #a855f7',
          fontFamily: 'monospace', fontSize: '0.8rem', color: '#a855f7', pointerEvents: 'none'
        }}>
          <div>THREAT DETECTED: BOTNET_SCANNER</div>
          <div>ACTION: TRAPPED IN TIMEOUT LOOP</div>
          <div>ATTACKER CPU: BURNING</div>
        </div>

        <Canvas camera={{ position: [0, 2, 8], fov: 60 }}>
          <color attach="background" args={['#000000']} />
          <ambientLight intensity={0.1} />
          
          <Stars radius={100} depth={50} count={2000} factor={4} saturation={0} fade speed={1} />
          <BlackholeTarpit />
          <DDoSAttackers />
          
          <OrbitControls 
            enablePan={false} 
            maxPolarAngle={Math.PI / 1.5} 
            minPolarAngle={Math.PI / 4}
            autoRotate={true}
            autoRotateSpeed={0.5}
          />
        </Canvas>
      </div>

    </div>
  );
}
