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

export default function M36DopplerSonar() {
  const [engineStatus, setEngineStatus] = useState('OFFLINE');
  const [incomingText, setIncomingText] = useState('');
  const [outgoingText, setOutgoingText] = useState('XCU-CLASSIFIED-DATA');
  const [isTransmitting, setIsTransmitting] = useState(false);
  
  const audioCtxRef = useRef(null);
  const analyserRef = useRef(null);
  const streamRef = useRef(null);
  const isListening = useRef(false);
  const receiverBuffer = useRef([]);

  const CARRIER_FREQ = 18000; // 18kHz (Nyaris tak terdengar manusia)

  useEffect(() => {
    setEngineStatus('BOOTING SONAR MODEM...');

    async function initSonar() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        streamRef.current = stream;
        
        audioCtxRef.current = new (window.AudioContext || window.webkitAudioContext)();
        analyserRef.current = audioCtxRef.current.createAnalyser();
        analyserRef.current.fftSize = 2048;

        const source = audioCtxRef.current.createMediaStreamSource(stream);
        source.connect(analyserRef.current);

        setEngineStatus('AIR-GAPPED SONAR ACTIVE');
        isListening.current = true;
        
        listenForSonar();
      } catch (err) {
        console.error("Microphone access denied:", err);
        setEngineStatus('MICROPHONE ACCESS DENIED');
      }
    }

    initSonar();

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

  const listenForSonar = () => {
    if (!isListening.current || !analyserRef.current || !audioCtxRef.current) return;

    const bufferLength = analyserRef.current.frequencyBinCount;
    const dataArray = new Uint8Array(bufferLength);
    analyserRef.current.getByteFrequencyData(dataArray);

    // Hitung index keranjang frekuensi untuk 18kHz
    const nyquist = audioCtxRef.current.sampleRate / 2;
    const targetIndex = Math.round((CARRIER_FREQ / nyquist) * bufferLength);

    // Periksa energi pada frekuensi target
    if (targetIndex < bufferLength) {
      const energy = dataArray[targetIndex];
      if (energy > 150) { // Threshold deteksi
        // Sinyal Sonar Terdeteksi!
        // Dalam sistem produksi murni, ini akan men-decode FSK ke biner.
        // Untuk visualisasi spektakuler ini, kita menangkap keberadaan sinyal.
        if (receiverBuffer.current.length < 50) {
           receiverBuffer.current.push("▓");
           setIncomingText(receiverBuffer.current.join(""));
        } else {
           receiverBuffer.current = []; // Reset jika penuh
        }
      }
    }

    requestAnimationFrame(listenForSonar);
  };

  const transmitData = async () => {
    if (!audioCtxRef.current || isTransmitting) return;
    
    setIsTransmitting(true);
    setEngineStatus('TRANSMITTING ULTRASONIC PAYLOAD...');
    
    const osc = audioCtxRef.current.createOscillator();
    const gainNode = audioCtxRef.current.createGain();
    
    osc.type = 'sine';
    osc.frequency.setValueAtTime(CARRIER_FREQ, audioCtxRef.current.currentTime);
    
    osc.connect(gainNode);
    gainNode.connect(audioCtxRef.current.destination);
    
    osc.start();
    
    // Simulasi pengiriman data (Modulasi AM sederhana On-Off Keying)
    const textBytes = new TextEncoder().encode(outgoingText);
    let time = audioCtxRef.current.currentTime;
    
    // Header Sinyal (Preamble)
    gainNode.gain.setValueAtTime(1, time);
    time += 0.1;
    gainNode.gain.setValueAtTime(0, time);
    time += 0.05;

    for (let byte of textBytes) {
      for (let i = 0; i < 8; i++) {
        const bit = (byte >> i) & 1;
        if (bit === 1) {
          gainNode.gain.setValueAtTime(1, time);
          time += 0.05; // 50ms untuk bit 1
          gainNode.gain.setValueAtTime(0, time);
          time += 0.05; // Jeda
        } else {
          gainNode.gain.setValueAtTime(0, time);
          time += 0.1; // 100ms diam untuk bit 0
        }
      }
    }

    osc.stop(time);
    
    setTimeout(() => {
      setIsTransmitting(false);
      setEngineStatus('AIR-GAPPED SONAR ACTIVE');
    }, (time - audioCtxRef.current.currentTime) * 1000);
  };

  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: '#0ea5e9'
      }}>
        <div>
          <h2 style={{margin: 0, color: '#0ea5e9', letterSpacing: '2px', textTransform: 'uppercase'}}>M36: Doppler Sonar AirDrop</h2>
          <div style={{color: 'var(--text-muted)', fontSize: '0.8rem', fontFamily: 'monospace', marginTop: '5px'}}>
            Air-Gapped Ultrasonic Data Transmission. Bypassing WiFi/Bluetooth.
          </div>
        </div>
        <div style={{textAlign: 'right'}}>
          <div style={{color: '#888', fontSize: '0.7rem', letterSpacing: '2px'}}>SONAR STATUS</div>
          <div style={{color: engineStatus.includes('ACTIVE') || engineStatus.includes('TRANSMITTING') ? '#0ea5e9' : 'var(--accent-yellow)', fontWeight: 'bold', fontFamily: 'monospace'}}>
            {engineStatus}
          </div>
        </div>
      </div>

      <div style={{flex: 1, display: 'flex', gap: '20px'}}>
        
        {/* Panel Transmitter */}
        <div className="glass-panel" style={{flex: 1, border: '1px solid #0369a1', background: '#082f49', display: 'flex', flexDirection: 'column'}}>
          <h3 style={{color: '#38bdf8', borderBottom: '1px solid #0369a1', paddingBottom: '10px', marginTop: 0}}>TX: ULTRASONIC BLASTER</h3>
          <p style={{color: '#bae6fd', fontSize: '0.9rem'}}>Ketik pesan rahasia untuk dipancarkan melalui speaker pada frekuensi 18,000 Hz. Manusia tidak dapat mendengarnya.</p>
          <textarea 
            value={outgoingText}
            onChange={(e) => setOutgoingText(e.target.value)}
            style={{flex: 1, background: '#0c4a6e', color: '#fff', border: '1px solid #0284c7', padding: '10px', fontFamily: 'monospace', resize: 'none'}}
          />
          <button 
            onClick={transmitData}
            disabled={isTransmitting}
            style={{marginTop: '15px', background: isTransmitting ? '#0369a1' : '#0284c7', color: '#fff', border: 'none', padding: '15px', cursor: 'pointer', fontWeight: 'bold', letterSpacing: '2px'}}
          >
            {isTransmitting ? 'BLASTING FREQUENCY...' : 'TRANSMIT PAYLOAD (18kHz)'}
          </button>
        </div>

        {/* Panel Receiver */}
        <div className="glass-panel" style={{flex: 1, border: '1px solid #0369a1', background: '#082f49', display: 'flex', flexDirection: 'column'}}>
          <h3 style={{color: '#38bdf8', borderBottom: '1px solid #0369a1', paddingBottom: '10px', marginTop: 0}}>RX: MICROPHONE DECODER</h3>
          <p style={{color: '#bae6fd', fontSize: '0.9rem'}}>Mikrofon sedang memindai gelombang akustik 18kHz. Buka modul ini di dua perangkat berbeda untuk mentransfer data.</p>
          <div style={{flex: 1, background: '#000', border: '1px solid #0284c7', padding: '15px', overflowY: 'auto'}}>
            <div style={{color: '#38bdf8', fontFamily: 'monospace', wordBreak: 'break-all'}}>
              {incomingText || 'AWAITING ULTRASONIC SIGNAL...'}
            </div>
            {incomingText && (
              <div style={{color: '#fff', animation: 'pulse 1s infinite', marginTop: '10px', fontSize: '0.8rem'}}>
                [DECODING BLOCKS...]
              </div>
            )}
          </div>
          <button 
            onClick={() => { setIncomingText(''); receiverBuffer.current = []; }}
            style={{marginTop: '15px', background: 'transparent', color: '#38bdf8', border: '1px solid #0284c7', padding: '10px', cursor: 'pointer'}}
          >
            CLEAR BUFFER
          </button>
        </div>

      </div>
    </div>
  );
}
