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

export default function M28InquisitorAI() {
  const [engineStatus, setEngineStatus] = useState('OFFLINE');
  const [transcript, setTranscript] = useState('');
  const [isMuted, setIsMuted] = useState(false);
  const [lastViolation, setLastViolation] = useState(null);
  
  const recognitionRef = useRef(null);

  // Daftar kata terlarang (Blacklist)
  const FORBIDDEN_WORDS = ['rahasia', 'bocor', 'bom', 'intel', 'bunuh'];

  useEffect(() => {
    setEngineStatus('BOOTING INQUISITOR AI...');

    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    
    if (!SpeechRecognition) {
      setEngineStatus('BROWSER TIDAK MENDUKUNG NATIVE AI SPEECH');
      return;
    }

    const recognition = new SpeechRecognition();
    recognition.continuous = true;
    recognition.interimResults = true;
    recognition.lang = 'id-ID';

    recognition.onstart = () => {
      setEngineStatus('AI LISTENING (OFFLINE EDGE)');
    };

    recognition.onresult = (event) => {
      let interimTranscript = '';
      let finalTranscript = '';

      for (let i = event.resultIndex; i < event.results.length; ++i) {
        if (event.results[i].isFinal) {
          finalTranscript += event.results[i][0].transcript;
        } else {
          interimTranscript += event.results[i][0].transcript;
        }
      }

      const currentText = finalTranscript || interimTranscript;
      setTranscript(currentText);

      // AI POLICE LOGIC: Cek pelanggaran
      const lowerText = currentText.toLowerCase();
      const violation = FORBIDDEN_WORDS.find(word => lowerText.includes(word));
      
      if (violation) {
        triggerInquisitorMute(violation);
        // Hentikan pendengaran secara agresif
        recognition.stop();
      }
    };

    recognition.onerror = (event) => {
      console.error("Inquisitor AI Error:", event.error);
      if (event.error === 'not-allowed') {
        setEngineStatus('MICROPHONE BLOCKED');
      }
    };

    recognition.onend = () => {
      // Jika di-mute karena pelanggaran, jangan otomatis restart
      if (!isMuted) {
         try {
           recognition.start();
         } catch(e){}
      }
    };

    try {
      recognition.start();
      recognitionRef.current = recognition;
    } catch (e) {
      console.error(e);
    }

    return () => {
      if (recognitionRef.current) {
        recognitionRef.current.stop();
      }
    };
  }, [isMuted]);

  const triggerInquisitorMute = (word) => {
    setIsMuted(true);
    setLastViolation(word);
    setEngineStatus('INQUISITOR PENALTY: MIC DESTROYED');
  };

  const resetInquisitor = () => {
    setIsMuted(false);
    setTranscript('');
    setLastViolation(null);
    if (recognitionRef.current) {
       try { recognitionRef.current.start(); } catch(e){}
    }
  };

  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: isMuted ? '#ef4444' : '#10b981'
      }}>
        <div>
          <h2 style={{margin: 0, color: isMuted ? '#ef4444' : '#10b981', letterSpacing: '2px', textTransform: 'uppercase'}}>M28: The Inquisitor AI</h2>
          <div style={{color: 'var(--text-muted)', fontSize: '0.8rem', fontFamily: 'monospace', marginTop: '5px'}}>
            Edge-Based Real-Time Voice Policer. Zero-Cloud Audio Moderation.
          </div>
        </div>
        <div style={{textAlign: 'right'}}>
          <div style={{color: '#888', fontSize: '0.7rem', letterSpacing: '2px'}}>AI STATUS</div>
          <div style={{color: isMuted ? '#ef4444' : '#10b981', fontWeight: 'bold', fontFamily: 'monospace', animation: isMuted ? 'flash 0.5s infinite' : 'none'}}>
            {engineStatus}
          </div>
        </div>
      </div>

      <div style={{flex: 1, display: 'flex', gap: '20px'}}>
        
        {/* Panel AI Transcript */}
        <div className="glass-panel" style={{flex: 1, border: `1px solid ${isMuted ? '#991b1b' : '#065f46'}`, background: isMuted ? '#450a0a' : '#022c22', display: 'flex', flexDirection: 'column', position: 'relative'}}>
          
          {isMuted && (
            <div style={{position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(239, 68, 68, 0.2)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 10}}>
               <h1 style={{color: '#f87171', fontSize: '3rem', border: '5px solid #f87171', padding: '20px', transform: 'rotate(-10deg)', textShadow: '0 0 20px red'}}>BANNED</h1>
            </div>
          )}

          <h3 style={{color: isMuted ? '#fca5a5' : '#34d399', borderBottom: `1px solid ${isMuted ? '#991b1b' : '#065f46'}`, paddingBottom: '10px', marginTop: 0}}>REAL-TIME TRANSCRIPT</h3>
          
          <div style={{color: '#fff', fontSize: '1.2rem', fontFamily: 'monospace', flex: 1, wordWrap: 'break-word', whiteSpace: 'pre-wrap'}}>
            {transcript || 'Silakan berbicara (Bahasa Indonesia)...'}
          </div>

          {lastViolation && (
            <div style={{background: '#7f1d1d', color: '#fff', padding: '10px', marginTop: '15px', borderLeft: '5px solid #f87171'}}>
              <span style={{fontWeight: 'bold'}}>VIOLATION DETECTED:</span> Pengucapan kata terlarang "{lastViolation}" telah memicu pemutusan mikrofon secara otomatis.
            </div>
          )}

        </div>

        {/* Panel Policy Configuration */}
        <div className="glass-panel" style={{width: '300px', border: '1px solid #1f2937', background: '#111827'}}>
          <h3 style={{color: '#9ca3af', borderBottom: '1px solid #374151', paddingBottom: '10px', marginTop: 0}}>INQUISITOR BLACKLIST</h3>
          <p style={{color: '#6b7280', fontSize: '0.8rem'}}>Kata-kata berikut dipantau secara lokal oleh memori browser. Pengucapan kata ini akan mengakibatkan MUTE absolut.</p>
          
          <ul style={{color: '#ef4444', fontFamily: 'monospace', paddingLeft: '20px', margin: '20px 0'}}>
             {FORBIDDEN_WORDS.map((w, i) => <li key={i} style={{marginBottom: '5px'}}>"{w}"</li>)}
          </ul>

          <p style={{color: '#6b7280', fontSize: '0.8rem'}}>Ucapkan kalimat seperti: "Tolong jangan <strong>bocor</strong>kan rahasia ini", dan saksikan sistem menendang Anda.</p>
          
          <button 
            onClick={resetInquisitor}
            disabled={!isMuted}
            style={{width: '100%', marginTop: '20px', background: isMuted ? '#10b981' : '#374151', color: '#fff', border: 'none', padding: '15px', cursor: isMuted ? 'pointer' : 'not-allowed', fontWeight: 'bold'}}
          >
            {isMuted ? 'RESTORE MICROPHONE' : 'MIC ACTIVE'}
          </button>
        </div>

      </div>
    </div>
  );
}
