/* global React, Icon, SOPVoice */
/* MicButton — toggleable mic that emits onTranscript(text, isFinal).
   Designed to be absolutely-positioned inside a textarea wrapper. */

const { useState: useStateMic, useRef: useRefMic, useEffect: useEffectMic } = React;

function MicButton({ onTranscript, onInterim, lang = "es-ES", size = 34, label = "Dictar", title }) {
  const [recording, setRecording] = useStateMic(false);
  const [error, setError] = useStateMic("");
  const [supported] = useStateMic(() => window.SOPVoice && window.SOPVoice.isSupported());
  const recRef = useRefMic(null);

  useEffectMic(() => () => { try { recRef.current && recRef.current.stop(); } catch (e) {} }, []);

  const toggle = () => {
    if (!supported) {
      setError("Tu navegador no soporta el micrófono. Usa Chrome, Edge o Safari.");
      setTimeout(() => setError(""), 4500);
      return;
    }
    if (recording) {
      recRef.current && recRef.current.stop();
      setRecording(false);
      return;
    }
    if (!recRef.current) {
      recRef.current = window.SOPVoice.createRecorder({
        lang,
        onText: (t) => onTranscript && onTranscript(t, true),
        onInterim: (t) => onInterim && onInterim(t),
        onError: (msg) => {
          setError(msg);
          setRecording(false);
          setTimeout(() => setError(""), 4500);
        },
        onEnd: () => setRecording(false),
      });
    }
    recRef.current.start();
    setRecording(true);
  };

  return (
    <div className={`mic-btn-wrap ${recording ? "mic-btn-wrap--active" : ""}`}>
      <button
        type="button"
        className={`mic-btn ${recording ? "mic-btn--recording" : ""}`}
        onClick={toggle}
        title={title || (recording ? "Detener" : "Dictar por voz")}
        style={{ width: size, height: size }}
      >
        {recording && <span className="mic-btn__pulse" />}
        <Icon name={supported ? "mic" : "micOff"} size={Math.round(size * 0.5)} />
      </button>
      {error && <div className="mic-btn__err">{error}</div>}
    </div>
  );
}

window.MicButton = MicButton;
