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

export default function M39AegisWatermark() {
  const [engineStatus, setEngineStatus] = useState('OFFLINE');
  const videoRef = useRef(null);
  const canvasRef = useRef(null);
  const isRunning = useRef(false);
  const streamRef = useRef(null);

  // Payload Rahasia yang akan disuntikkan ke dalam Video
  const WATERMARK_PAYLOAD = "DNA-SEED: VVIP-XCU-999";

  useEffect(() => {
    setEngineStatus('BOOTING AEGIS WATERMARK...');

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

        setEngineStatus('STEGANOGRAPHY ACTIVE');
        isRunning.current = true;
        
        requestAnimationFrame(renderWatermark);
      } 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 renderWatermark = (timestamp) => {
    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 video asli
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      
      // INJEKSI AEGIS WATERMARK (Steganografi Temporal)
      // Kita membuat kedipan pada interval milidetik tertentu.
      // Mata manusia tidak menyadarinya (karena hanya 1-2 frame per detik dengan opacity 1-2%).
      // Namun kamera HP 60fps akan menangkap frame ini.
      
      const isFlashFrame = Math.floor(timestamp / 50) % 10 === 0; // Berkedip sangat cepat

      if (isFlashFrame) {
        ctx.fillStyle = "rgba(255, 255, 255, 0.03)"; // 3% opacity, hampir tak terlihat
        ctx.font = "bold 40px monospace";
        
        // Memenuhi layar dengan watermark agar tidak bisa di-crop
        for (let i = 0; i < 15; i++) {
          for (let j = 0; j < 15; j++) {
            ctx.fillText(WATERMARK_PAYLOAD, i * 200 - 100, j * 100);
          }
        }
        
        // Mengubah saturasi gambar secara mikroskopis sebagai penanda tambahan
        ctx.fillStyle = "rgba(255, 0, 0, 0.01)";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
      }
    }

    requestAnimationFrame(renderWatermark);
  };

  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: '#facc15'
      }}>
        <div>
          <h2 style={{margin: 0, color: '#facc15', letterSpacing: '2px', textTransform: 'uppercase'}}>M39: Aegis Forensic Watermark</h2>
          <div style={{color: 'var(--text-muted)', fontSize: '0.8rem', fontFamily: 'monospace', marginTop: '5px'}}>
            Kinetic Steganography. Invisible DNA Tracker.
          </div>
        </div>
        <div style={{textAlign: 'right'}}>
          <div style={{color: '#888', fontSize: '0.7rem', letterSpacing: '2px'}}>SECURITY STATUS</div>
          <div style={{color: engineStatus.includes('ACTIVE') ? '#facc15' : 'var(--accent-red)', fontWeight: 'bold', fontFamily: 'monospace'}}>
            {engineStatus}
          </div>
        </div>
      </div>

      <div style={{flex: 1, borderRadius: '8px', overflow: 'hidden', border: '1px solid #333300', 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(250, 204, 21, 0.1)', padding: '10px', borderLeft: '2px solid #facc15',
          fontFamily: 'monospace', fontSize: '0.8rem', color: '#facc15', pointerEvents: 'none'
        }}>
          <div>PAYLOAD: {WATERMARK_PAYLOAD}</div>
          <div>INJECTION RATE: 20Hz TEMPORAL</div>
          <div>VISIBILITY: 3% (INVISIBLE TO NAKED EYE)</div>
          <div style={{marginTop: '10px', color: '#fff'}}>Coba rekam layar ini pakai HP Anda, lalu putar lambat!</div>
        </div>

        {/* Video mentah */}
        <video ref={videoRef} style={{ display: 'none' }} playsInline muted />
        
        {/* Kanvas dengan Injeksi Watermark */}
        <canvas 
          ref={canvasRef} 
          width={1280} 
          height={720} 
          style={{ width: '100%', height: '100%', objectFit: 'contain' }}
        />

      </div>

    </div>
  );
}
