import React, { useEffect, useRef, useState } from 'react';

export default function M43PulsarMatrix() {
  const [engineStatus, setEngineStatus] = useState('OFFLINE');
  const [bitrate, setBitrate] = useState('0 bytes');
  
  const videoRef = useRef(null);
  const canvasRef = useRef(null);
  const isRunning = useRef(false);
  const lastFrameData = useRef(null);
  const streamRef = useRef(null);

  useEffect(() => {
    setEngineStatus('BOOTING PULSAR WASM...');

    async function initCamera() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 640, height: 360 } });
        streamRef.current = stream;
        
        if (videoRef.current) {
          videoRef.current.srcObject = stream;
          videoRef.current.play();
        }

        setEngineStatus('NEUROMORPHIC FRAMELESS ACTIVE');
        isRunning.current = true;
        
        requestAnimationFrame(processPulsarDelta);
      } catch (err) {
        console.error("Camera access denied:", err);
        setEngineStatus('CAMERA ACCESS DENIED');
      }
    }

    initCamera();

    return () => {
      isRunning.current = false;
      if (streamRef.current) {
        streamRef.current.getTracks().forEach(track => track.stop());
      }
    };
  }, []);

  const processPulsarDelta = () => {
    if (!isRunning.current) return;

    const video = videoRef.current;
    const canvas = canvasRef.current;
    
    if (video && canvas && video.readyState === video.HAVE_ENOUGH_DATA) {
      const ctx = canvas.getContext('2d', { willReadFrequently: true });
      
      // Menggambar frame kamera tersembunyi
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      const frame = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const data = frame.data;
      
      // Array baru untuk menampung hanya piksel yang bergerak (Delta)
      const outputData = new Uint8ClampedArray(data.length);
      let changedPixelsCount = 0;

      if (lastFrameData.current) {
        for (let i = 0; i < data.length; i += 4) {
          const diffR = Math.abs(data[i] - lastFrameData.current[i]);
          const diffG = Math.abs(data[i+1] - lastFrameData.current[i+1]);
          const diffB = Math.abs(data[i+2] - lastFrameData.current[i+2]);
          
          const diffTotal = diffR + diffG + diffB;
          
          if (diffTotal > 60) { // Threshold pergerakan
            changedPixelsCount++;
            // Berikan warna hijau khas "Matrix / X-Ray" untuk piksel yang bergerak
            outputData[i] = 0;     // R
            outputData[i+1] = 255; // G
            outputData[i+2] = 0;   // B
            outputData[i+3] = 255; // Alpha
          } else {
            // Hitam pekat untuk piksel diam
            outputData[i] = 0;
            outputData[i+1] = 0;
            outputData[i+2] = 0;
            outputData[i+3] = 255;
          }
        }
      }

      // Simpan untuk perbandingan frame berikutnya
      lastFrameData.current = new Uint8ClampedArray(data);

      // Gambar kembali delta murni ke kanvas untuk dilihat pengguna
      const outputImageData = new ImageData(outputData, canvas.width, canvas.height);
      ctx.putImageData(outputImageData, 0, 0);

      // Simulasi pengiriman biner
      // Setiap piksel yang berubah = 10 byte (X, Y, dR, dG, dB)
      if (changedPixelsCount > 0) {
        setBitrate((changedPixelsCount * 10 / 1024).toFixed(2) + ' KB/s');
      } else {
        setBitrate('0 KB/s (ZERO BANDWIDTH)');
      }
    }

    requestAnimationFrame(processPulsarDelta);
  };

  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: '#00ff41'
      }}>
        <div>
          <h2 style={{margin: 0, color: '#00ff41', letterSpacing: '2px', textTransform: 'uppercase'}}>M43: The Pulsar Matrix</h2>
          <div style={{color: 'var(--text-muted)', fontSize: '0.8rem', fontFamily: 'monospace', marginTop: '5px'}}>
            Neuromorphic Frameless Video Compression. X-Ray Movement Delta.
          </div>
        </div>
        <div style={{textAlign: 'right'}}>
          <div style={{color: '#888', fontSize: '0.7rem', letterSpacing: '2px'}}>COMPRESSION STATUS</div>
          <div style={{color: engineStatus.includes('ACTIVE') ? '#00ff41' : 'var(--accent-yellow)', fontWeight: 'bold', fontFamily: 'monospace'}}>
            {engineStatus}
          </div>
        </div>
      </div>

      {/* X-Ray Canvas Environment */}
      <div style={{flex: 1, borderRadius: '8px', overflow: 'hidden', border: '1px solid #003300', background: '#000000', position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
        
        {/* Holographic grid UI overlay */}
        <div style={{
          position: 'absolute', top: '20px', left: '20px', zIndex: 10,
          background: 'rgba(0, 255, 65, 0.1)', padding: '10px', borderLeft: '2px solid #00ff41',
          fontFamily: 'monospace', fontSize: '0.8rem', color: '#00ff41', pointerEvents: 'none'
        }}>
          <div>LOGIC: PIXEL DIFFERENCE ONLY</div>
          <div>CPU LOAD: ULTRA LIGHT</div>
          <div>DELTA BANDWIDTH: {bitrate}</div>
        </div>

        {/* Video mentah (tersembunyi) untuk ekstraksi piksel */}
        <video ref={videoRef} style={{ display: 'none' }} playsInline muted />
        
        {/* Kanvas visualisasi Pulsar Matrix */}
        <canvas 
          ref={canvasRef} 
          width={640} 
          height={360} 
          style={{ width: '100%', height: '100%', objectFit: 'contain', filter: 'brightness(1.5) contrast(1.2)' }}
        />

      </div>

    </div>
  );
}
