import { useState, useEffect, useRef } from 'react';
import { useIam } from '../context/IamContext';

export default function QuantumSandbox({ moduleId }) {
  const { identity } = useIam();
  const [logs, setLogs] = useState([]);
  const [isWasmLoaded, setIsWasmLoaded] = useState(false);
  const [wasmSdk, setWasmSdk] = useState(null);
  
  // Status koneksi Kuantum (WebTransport)
  const [isConnected, setIsConnected] = useState(false);
  const [isConnecting, setIsConnecting] = useState(false);

  // Chat State (Scribe)
  const [messages, setMessages] = useState([]);
  const [inputMessage, setInputMessage] = useState('');

  const logEndRef = useRef(null);

  // Feature Gating: Cek apakah tenant punya hak akses OMNI-ENGINE
  const hasOmniAccess = identity?.packages?.includes('JUMPA.ID OMNI-ENGINE');

  // Menambahkan log ke konsol Kinetic
  const addLog = (msg, type = 'info') => {
    const timestamp = new Date().toISOString().split('T')[1].slice(0, -1);
    setLogs(prev => [...prev.slice(-49), { text: `[${timestamp}] ${msg}`, type }]);
  };

  useEffect(() => {
    if (logEndRef.current) {
      logEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [logs]);

  // Load WASM SDK
  useEffect(() => {
    let mounted = true;
    async function loadWasm() {
      try {
        addLog('Mencari cip WebAssembly dari Edge Server...', 'system');
        // Dynamic Import dari public/sdk (ES Module)
        const sdkUrl = window.location.origin + '/sdk/xcu_wasm_sdk.js?v=' + Date.now();
        const sdk = await import(sdkUrl);
        // Inisialisasi WASM
        await sdk.default();
        if (mounted) {
          setWasmSdk(sdk);
          setIsWasmLoaded(true);
          addLog('CIP WEBASSEMBLY (RUST CORE) BERHASIL DIMUAT KE DALAM MEMORI PERAMBAN!', 'success');
        }
      } catch (err) {
        if (mounted) {
          addLog('GAGAL MEMUAT WASM: ' + err.message, 'error');
          console.error(err);
        }
      }
    }
    loadWasm();
    return () => { mounted = false; };
  }, []);

  const handleConnect = async () => {
    setIsConnecting(true);
    addLog('Melakukan Pukulan UDP (UDP Punching) ke SG-1 (Port 8443)...', 'system');
    
    // Simulasi waktu tempuh WebTransport (karena ini sandbox)
    setTimeout(() => {
      addLog('Handshake WebTransport (QUIC) Berhasil. Latensi: 4ms.', 'success');
      setIsConnected(true);
      setIsConnecting(false);
    }, 1500);
  };

  const handleSendMessage = (e) => {
    e.preventDefault();
    if (!inputMessage.trim()) return;
    
    // Simulasi pengiriman via WASM CRDT Scribe
    const msg = inputMessage;
    setInputMessage('');
    addLog(`[CRDT Scribe] Memancarkan Datagram: "${msg}"`, 'info');
    
    setMessages(prev => [...prev, { sender: 'You', text: msg }]);
    
    setTimeout(() => {
      setMessages(prev => [...prev, { sender: 'SG-1 ECHO', text: `Echo dari lorong Kuantum: ${msg}` }]);
      addLog(`[CRDT Scribe] Gema diterima dalam 4ms.`, 'success');
    }, 300);
  };

  // Fungsi-Fungsi Senjata Rahasia
  const fireWeapon = async (weaponName, sdkFunction) => {
    if (!hasOmniAccess) {
      addLog(`AKSES DITOLAK: Fitur [${weaponName}] membutuhkan Lisensi OMNI-ENGINE!`, 'error');
      return;
    }
    if (!isWasmLoaded) {
      addLog('WASM belum dimuat!', 'error');
      return;
    }
    
    addLog(`MEMICU PROTOKOL: ${weaponName}...`, 'warning');
    try {
      if (weaponName === 'Neural Whisper') {
        await sdkFunction('id-ID'); // Bahasa Indonesia
      } else if (weaponName === 'Aegis Watermark') {
        await sdkFunction('A8F9C2B'); // Hex Seed
      } else if (weaponName === 'Doppler Matrix') {
        await sdkFunction('XCU-SECURE-PAYLOAD');
      } else {
        await sdkFunction();
      }
      addLog(`[BERHASIL] ${weaponName} aktif! Cek console browser (F12) untuk log dari Rust.`, 'success');
    } catch (err) {
      addLog(`[GAGAL] Eksekusi ${weaponName} dibatalkan: ${err.message}`, 'error');
    }
  };

  return (
    <div style={{ display: 'flex', gap: '20px', marginTop: '20px' }}>
      
      {/* KOLOM KIRI: Taktikal Obrolan & Video */}
      <div className="glass-panel" style={{ flex: 2, padding: '20px', borderColor: 'var(--accent-purple)', display: 'flex', flexDirection: 'column' }}>
        <h2 style={{ color: 'var(--accent-purple)', marginBottom: '15px', textTransform: 'uppercase' }}>
          OMNI-LINK: {moduleId}
        </h2>
        
        <div style={{ display: 'flex', gap: '10px', marginBottom: '20px' }}>
          <button 
            className="btn-primary" 
            onClick={handleConnect}
            disabled={!isWasmLoaded || isConnected || isConnecting}
            style={{ flex: 1, background: isConnected ? 'rgba(0, 255, 136, 0.2)' : 'rgba(168, 85, 247, 0.2)', border: `1px solid ${isConnected ? 'var(--accent-green)' : 'var(--accent-purple)'}`, color: isConnected ? 'var(--accent-green)' : 'white' }}
          >
            {isConnected ? 'TERHUBUNG KE JARINGAN KUANTUM' : isConnecting ? 'MENCOCOKKAN KUNCI LATTICE...' : 'HUBUNGKAN KE SG-1 (QUIC/8443)'}
          </button>
        </div>

        {/* Panel Obrolan Scribe */}
        <div style={{ flex: 1, border: '1px solid var(--glass-border)', borderRadius: '8px', background: 'rgba(0,0,0,0.5)', display: 'flex', flexDirection: 'column', overflow: 'hidden', minHeight: '300px' }}>
          <div style={{ padding: '10px', background: 'rgba(168, 85, 247, 0.1)', borderBottom: '1px solid var(--glass-border)', fontSize: '0.8rem', color: 'var(--accent-purple)', fontWeight: 'bold' }}>
            CRDT SCRIBE (Zero-Database Chat)
          </div>
          <div className="custom-scrollbar" style={{ flex: 1, padding: '15px', overflowY: 'auto' }}>
            {messages.length === 0 && <div style={{ color: '#555', textAlign: 'center', marginTop: '20px', fontStyle: 'italic' }}>Menunggu pancaran Kuantum...</div>}
            {messages.map((m, i) => (
              <div key={i} style={{ marginBottom: '10px', textAlign: m.sender === 'You' ? 'right' : 'left' }}>
                <span style={{ fontSize: '0.7rem', color: m.sender === 'You' ? 'var(--accent-green)' : 'var(--accent-purple)' }}>{m.sender}</span>
                <div style={{ background: m.sender === 'You' ? 'rgba(0, 255, 136, 0.1)' : 'rgba(168, 85, 247, 0.1)', border: `1px solid ${m.sender === 'You' ? 'var(--accent-green)' : 'var(--accent-purple)'}`, padding: '8px 12px', borderRadius: '4px', display: 'inline-block', maxWidth: '80%', wordBreak: 'break-word', color: 'white' }}>
                  {m.text}
                </div>
              </div>
            ))}
          </div>
          <form onSubmit={handleSendMessage} style={{ display: 'flex', padding: '10px', borderTop: '1px solid var(--glass-border)' }}>
            <input 
              type="text" 
              value={inputMessage} 
              onChange={e => setInputMessage(e.target.value)} 
              placeholder="Tulis pesan untuk dikirim via Datagram..." 
              disabled={!isConnected}
              style={{ flex: 1, background: 'transparent', border: 'none', color: 'white', outline: 'none', padding: '0 10px', fontFamily: 'monospace' }} 
            />
            <button type="submit" disabled={!isConnected} style={{ background: 'transparent', border: 'none', color: isConnected ? 'var(--accent-purple)' : '#555', cursor: isConnected ? 'pointer' : 'not-allowed', fontWeight: 'bold' }}>
              &gt;&gt; TRANSMIT
            </button>
          </form>
        </div>
      </div>

      {/* KOLOM KANAN: Terminal Kinetic & Senjata Rahasia */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: '20px' }}>
        
        {/* Kinetic Terminal */}
        <div className="glass-panel" style={{ padding: '15px', borderColor: 'var(--accent-green)', flex: 1, display: 'flex', flexDirection: 'column' }}>
          <h3 style={{ color: 'var(--accent-green)', fontSize: '0.8rem', marginBottom: '10px', textTransform: 'uppercase' }}>KINETIC LOGS</h3>
          <div className="custom-scrollbar" style={{ flex: 1, background: '#050a05', border: '1px solid #113311', borderRadius: '4px', padding: '10px', fontFamily: 'monospace', fontSize: '0.7rem', overflowY: 'auto' }}>
            {logs.map((log, i) => (
              <div key={i} style={{ 
                color: log.type === 'error' ? '#ff4444' : log.type === 'warning' ? '#ffaa00' : log.type === 'success' ? '#00ff88' : '#88aa88', 
                marginBottom: '4px' 
              }}>
                {log.text}
              </div>
            ))}
            <div ref={logEndRef} />
          </div>
        </div>

        {/* Feature Gating: Senjata Rahasia */}
        <div className="glass-panel" style={{ padding: '15px', borderColor: 'var(--glass-border)' }}>
          <h3 style={{ color: 'var(--text-main)', fontSize: '0.8rem', marginBottom: '15px', textTransform: 'uppercase', display: 'flex', justifyContent: 'space-between' }}>
            <span>Persenjataan Kuantum</span>
            {hasOmniAccess ? (
              <span style={{ color: 'var(--accent-green)', fontWeight: 'bold' }}>[OMNI-ENGINE UNLOCKED]</span>
            ) : (
              <span style={{ color: '#ff4444', fontWeight: 'bold' }}>[LOCKED]</span>
            )}
          </h3>

          <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
            <button 
              onClick={() => fireWeapon('Neural Whisper', wasmSdk?.enable_neural_whisper)}
              style={{ background: hasOmniAccess ? 'rgba(59, 130, 246, 0.2)' : 'rgba(50, 50, 50, 0.5)', color: hasOmniAccess ? '#3b82f6' : '#666', border: `1px solid ${hasOmniAccess ? '#3b82f6' : '#444'}`, padding: '10px', borderRadius: '4px', textAlign: 'left', cursor: hasOmniAccess ? 'pointer' : 'not-allowed', transition: 'all 0.3s' }}
            >
              <div style={{ fontWeight: 'bold', fontSize: '0.8rem' }}>🎙️ The Neural Whisper (AI Offline)</div>
              <div style={{ fontSize: '0.6rem', opacity: 0.8, marginTop: '4px' }}>Eksploitasi NPU untuk Terjemahan Suara-ke-Teks lokal.</div>
            </button>

            <button 
              onClick={() => fireWeapon('Post-Quantum Shield', wasmSdk?.enable_post_quantum_shield)}
              style={{ background: hasOmniAccess ? 'rgba(236, 72, 153, 0.2)' : 'rgba(50, 50, 50, 0.5)', color: hasOmniAccess ? '#ec4899' : '#666', border: `1px solid ${hasOmniAccess ? '#ec4899' : '#444'}`, padding: '10px', borderRadius: '4px', textAlign: 'left', cursor: hasOmniAccess ? 'pointer' : 'not-allowed', transition: 'all 0.3s' }}
            >
              <div style={{ fontWeight: 'bold', fontSize: '0.8rem' }}>🛡️ Post-Quantum Shield</div>
              <div style={{ fontSize: '0.6rem', opacity: 0.8, marginTop: '4px' }}>Bungkus panggilan dengan sandi Kyber-1024 anti-superkomputer.</div>
            </button>

            <button 
              onClick={() => fireWeapon('Doppler Matrix', wasmSdk?.enable_doppler_matrix)}
              style={{ background: hasOmniAccess ? 'rgba(245, 158, 11, 0.2)' : 'rgba(50, 50, 50, 0.5)', color: hasOmniAccess ? '#f59e0b' : '#666', border: `1px solid ${hasOmniAccess ? '#f59e0b' : '#444'}`, padding: '10px', borderRadius: '4px', textAlign: 'left', cursor: hasOmniAccess ? 'pointer' : 'not-allowed', transition: 'all 0.3s' }}
            >
              <div style={{ fontWeight: 'bold', fontSize: '0.8rem' }}>🦇 The Doppler Matrix (Sonar)</div>
              <div style={{ fontSize: '0.6rem', opacity: 0.8, marginTop: '4px' }}>Pancarkan gelombang suara ultrasonik (Air-Gapped Comm).</div>
            </button>

            <button 
              onClick={() => fireWeapon('Aegis Watermark', wasmSdk?.enable_aegis_forensic_watermark)}
              style={{ background: hasOmniAccess ? 'rgba(220, 38, 38, 0.2)' : 'rgba(50, 50, 50, 0.5)', color: hasOmniAccess ? '#dc2626' : '#666', border: `1px solid ${hasOmniAccess ? '#dc2626' : '#444'}`, padding: '10px', borderRadius: '4px', textAlign: 'left', cursor: hasOmniAccess ? 'pointer' : 'not-allowed', transition: 'all 0.3s' }}
            >
              <div style={{ fontWeight: 'bold', fontSize: '0.8rem' }}>👁️ Aegis Forensic Watermark</div>
              <div style={{ fontSize: '0.6rem', opacity: 0.8, marginTop: '4px' }}>Suntikkan sandi morse mikroskopis penangkal pembajak layar.</div>
            </button>
          </div>
        </div>

      </div>
    </div>
  );
}
