/* Voice section — "Habla con nosotros" mic with Whisper-style listening */
const VoiceSection = () => {
  const [listening, setListening] = React.useState(false);
  const [transcript, setTranscript] = React.useState('');
  const [audioCtx, setAudioCtx] = React.useState(null);
  const [analyser, setAnalyser] = React.useState(null);
  const streamRef = React.useRef(null);
  const recRef = React.useRef(null);
  const rafRef = React.useRef(null);
  const [waveData, setWaveData] = React.useState(() => new Array(64).fill(8));

  // Play short tones for connect / disconnect
  const tone = (freq, dur = 0.18, type = 'sine') => {
    try {
      const ctx = new (window.AudioContext || window.webkitAudioContext)();
      const osc = ctx.createOscillator();
      const gain = ctx.createGain();
      osc.type = type;
      osc.frequency.value = freq;
      osc.connect(gain);
      gain.connect(ctx.destination);
      gain.gain.setValueAtTime(0, ctx.currentTime);
      gain.gain.linearRampToValueAtTime(0.18, ctx.currentTime + 0.02);
      gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + dur);
      osc.start();
      osc.stop(ctx.currentTime + dur + 0.02);
      setTimeout(() => ctx.close(), (dur + 0.2) * 1000);
    } catch (_) {}
  };
  const connectTone = () => { tone(440, 0.14); setTimeout(() => tone(660, 0.16), 110); };
  const disconnectTone = () => { tone(330, 0.14); setTimeout(() => tone(220, 0.18), 110); };

  const start = async () => {
    if (listening) return stop();
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      streamRef.current = stream;
      connectTone();
      // Audio analysis for live waves
      const Ctx = window.AudioContext || window.webkitAudioContext;
      const aCtx = new Ctx();
      const src = aCtx.createMediaStreamSource(stream);
      const an = aCtx.createAnalyser();
      an.fftSize = 256;
      src.connect(an);
      setAudioCtx(aCtx);
      setAnalyser(an);
      setListening(true);
      setTranscript('');
      const buf = new Uint8Array(an.frequencyBinCount);
      const tick = () => {
        an.getByteTimeDomainData(buf);
        const samples = [];
        const step = Math.floor(buf.length / 64);
        for (let i = 0; i < 64; i++) {
          const v = (buf[i * step] - 128) / 128;
          samples.push(Math.max(4, Math.abs(v) * 36 + 4));
        }
        setWaveData(samples);
        rafRef.current = requestAnimationFrame(tick);
      };
      tick();
      // MediaRecorder for Whisper-like flow
      try {
        const rec = new MediaRecorder(stream);
        const chunks = [];
        rec.ondataavailable = (e) => chunks.push(e.data);
        rec.onstop = async () => {
          // Demo: pretend we transcribed
          const demo = [
            'Hola, quiero construir una plataforma SaaS para mi negocio.',
            "Hi, I'd like to launch a mobile app and an admin panel.",
            'Necesito un panel para administrar mis clientes y pagos.',
            'Can you help me design a Web4 gaming experience?',
          ];
          setTranscript(demo[Math.floor(Math.random() * demo.length)]);
        };
        rec.start();
        recRef.current = rec;
      } catch (_) {}
    } catch (err) {
      // permission denied — fake the experience
      connectTone();
      setListening(true);
      setTranscript('');
      const fakeTick = () => {
        const samples = new Array(64).fill(0).map(() => 6 + Math.random() * 22);
        setWaveData(samples);
        rafRef.current = setTimeout(fakeTick, 100);
      };
      fakeTick();
    }
  };

  const stop = () => {
    setListening(false);
    disconnectTone();
    if (rafRef.current) {
      cancelAnimationFrame(rafRef.current);
      clearTimeout(rafRef.current);
    }
    if (recRef.current && recRef.current.state !== 'inactive') {
      try { recRef.current.stop(); } catch (_) {}
    }
    if (streamRef.current) {
      streamRef.current.getTracks().forEach(t => t.stop());
      streamRef.current = null;
    }
    if (audioCtx) {
      try { audioCtx.close(); } catch (_) {}
      setAudioCtx(null);
    }
    setWaveData(new Array(64).fill(8));
  };

  React.useEffect(() => () => stop(), []);

  // Build SVG wave path from waveData
  const w = 1200, h = 80, mid = h / 2;
  const step = w / (waveData.length - 1);
  const top = waveData.map((v, i) => `${i === 0 ? 'M' : 'L'}${i * step},${mid - v}`).join(' ');
  const bot = waveData.map((v, i) => `${i === 0 ? 'M' : 'L'}${i * step},${mid + v}`).join(' ');

  return (
    <section className="sec-voice">
      <div className="voice-bg">
        <div className="voice-orb-1"/>
        <div className="voice-orb-2"/>
      </div>

      <div className="container voice-inner">
        <div className="voice-mic-wrap">
          <svg className="voice-mic-waves" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
            <defs>
              <linearGradient id="voice-wave-g" x1="0" y1="0" x2="1" y2="0">
                <stop offset="0" stopColor="#22d3ee" stopOpacity="0.1"/>
                <stop offset="0.5" stopColor="#22d3ee" stopOpacity="0.9"/>
                <stop offset="1" stopColor="#22d3ee" stopOpacity="0.1"/>
              </linearGradient>
            </defs>
            <path d={top} stroke="url(#voice-wave-g)" strokeWidth="2" fill="none" strokeLinecap="round"/>
            <path d={bot} stroke="url(#voice-wave-g)" strokeWidth="2" fill="none" strokeLinecap="round" opacity="0.7"/>
          </svg>

          <button
            className={"voice-mic" + (listening ? " listening" : "")}
            onClick={start}
            aria-label={listening ? "Stop listening" : "Talk to us"}
          >
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
              {listening ? (
                <React.Fragment>
                  <rect x="8" y="8" width="8" height="8" rx="1.5" fill="currentColor"/>
                </React.Fragment>
              ) : (
                <React.Fragment>
                  <rect x="9" y="3" width="6" height="11" rx="3" fill="currentColor"/>
                  <path d="M5 11a7 7 0 0 0 14 0"/>
                  <line x1="12" y1="18" x2="12" y2="22"/>
                  <line x1="8" y1="22" x2="16" y2="22"/>
                </React.Fragment>
              )}
            </svg>
          </button>
        </div>

        <h2 className="voice-heading">
          Still have questions? <em>Ask Axai.</em>
        </h2>
        <p className="voice-sub">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
            <rect x="9" y="3" width="6" height="11" rx="3" fill="currentColor"/>
            <path d="M5 11a7 7 0 0 0 14 0" strokeLinecap="round"/>
          </svg>
          Tap the mic for instant voice answers · 24/7
        </p>

        <button
          className={"voice-cta" + (listening ? " active" : "")}
          onClick={start}
        >
          <span className="dot"/>
          {listening ? 'Listening… tap mic to stop' : 'Activate voice conversation'}
        </button>

        {transcript && (
          <div className="voice-transcript">
            <span className="muted-2">Transcript · demo</span>
            "{transcript}"
          </div>
        )}
      </div>
    </section>
  );
};

Object.assign(window, { VoiceSection });
