import { useState } from "react";

export default function HoustonChat() {
  const [command, setCommand] = useState("");
  const [response, setResponse] = useState("Salut Jo, je suis prêt !");
  const [isListening, setIsListening] = useState(false);

  const synth = window.speechSynthesis;
  const recognition =
    window.SpeechRecognition || window.webkitSpeechRecognition
      ? new (window.SpeechRecognition || window.webkitSpeechRecognition)()
      : null;

  const handleCommand = (text) => {
    setResponse(`Commande reçue : "${text}"`);
    speak(`Ok Jo, j'ai bien reçu ta commande : ${text}`);
  };

  const speak = (text) => {
    const utter = new SpeechSynthesisUtterance(text);
    utter.lang = "fr-FR";
    synth.speak(utter);
  };

  const handleMicClick = () => {
    if (!recognition) {
      alert("La reconnaissance vocale n'est pas supportée sur ce navigateur.");
      return;
    }

    setIsListening(true);
    recognition.lang = "fr-FR";
    recognition.start();

    recognition.onresult = (event) => {
      const spokenText = event.results[0][0].transcript;
      setCommand(spokenText);
      handleCommand(spokenText);
      setIsListening(false);
    };

    recognition.onerror = (event) => {
      console.error("Erreur reco vocale :", event.error);
      setIsListening(false);
    };
  };

  return (
    <div className="w-full max-w-md mx-auto p-6 rounded-2xl shadow-xl bg-white">
      <h2 className="text-xl font-bold mb-4 text-center">👨‍🚀 Jarvis Houston</h2>
      <div className