"use client"; import { useState, useEffect, useRef } from "react"; export default function VoiceWidget() { const [isListening, setIsListening] = useState(false); const [transcript, setTranscript] = useState(""); const [response, setResponse] = useState(""); const [isSpeaking, setIsSpeaking] = useState(false); const [isLoading, setIsLoading] = useState(false); const recognitionRef = useRef(null); const synthRef = useRef(null); useEffect(() => { const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition; const synth = window.speechSynthesis; if (SpeechRecognition) { recognitionRef.current = new SpeechRecognition(); recognitionRef.current.continuous = false; recognitionRef.current.interimResults = true; recognitionRef.current.lang = "es-ES"; recognitionRef.current.onresult = (event: any) => { const last = event.results.length - 1; const text = event.results[last][0].transcript; setTranscript(text); if (event.results[last].isFinal) { handleSend(text); } }; recognitionRef.current.onend = () => { setIsListening(false); }; } if (synth) { synthRef.current = synth; } return () => { if (recognitionRef.current) recognitionRef.current.abort(); }; }, []); const startListening = () => { if (recognitionRef.current && !isListening) { setTranscript(""); recognitionRef.current.start(); setIsListening(true); } }; const stopListening = () => { if (recognitionRef.current && isListening) { recognitionRef.current.stop(); setIsListening(false); } }; const handleSend = async (text: string) => { if (!text.trim()) return; setIsLoading(true); setResponse("Pensando..."); try { const res = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text }) }); const data = await res.json(); const reply = (data.response || "¡Hola! Estoy aquí. ¿En qué puedo ayudarte?").substring(0, 200); setResponse(reply); speak(reply); } catch (e) { console.error(e); setResponse("Tengo problemas para conectar. Intenta de nuevo."); } setIsLoading(false); }; const speak = (text: string) => { if (!synthRef.current) return; synthRef.current.cancel(); const utterance = new SpeechSynthesisUtterance(text); utterance.lang = "es-ES"; utterance.rate = 0.85; utterance.pitch = 0.9; const voices = synthRef.current.getVoices(); const spanishVoice = voices.find((v: any) => v.lang.includes("es")); if (spanishVoice) utterance.voice = spanishVoice; utterance.onstart = () => setIsSpeaking(true); utterance.onend = () => setIsSpeaking(false); utterance.onerror = () => setIsSpeaking(false); synthRef.current.speak(utterance); }; return (
👑

Cleopatra Voice

Asistente de Ventas IA

{isListening ? "🎤 Escuchando..." : isSpeaking ? "🔊 Hablando..." : isLoading ? "⏳ Pensando..." : "💬 Lista"}
{[...Array(12)].map((_, i) => (
))}
{transcript && (

Dijiste:

{transcript}

)} {response && (

Cleopatra:

{response}

)}

{isListening ? "Habla ahora..." : "Toca el micrófono para empezar"}

); }