import { useState, useEffect } from 'react';

// Voice registry - assign voices to characters
const VOICE_REGISTRY = {
  narrator: { name: 'narrator', preferredGender: 'male' },
  characters: {
    // Default voices will be assigned dynamically
  }
};

export function useTextToSpeech() {
  const [voices, setVoices] = useState([]);
  const [isSpeaking, setIsSpeaking] = useState(false);
  const [isSupported, setIsSupported] = useState(false);
  const [selectedVoice, setSelectedVoice] = useState(null);
  const [rate, setRate] = useState(1); // Speech speed
  const [volume, setVolume] = useState(1); // Volume 0-1

  useEffect(() => {
    // Check browser support
    if ('speechSynthesis' in window) {
      setIsSupported(true);
      
      const loadVoices = () => {
        const availableVoices = window.speechSynthesis.getVoices();
        setVoices(availableVoices);
        
        // Set default voice (English)
        const defaultVoice = availableVoices.find(v => 
          v.lang.includes('en') && v.name.includes('Female')
        ) || availableVoices.find(v => v.lang.includes('en')) || availableVoices[0];
        
        if (defaultVoice) {
          setSelectedVoice(defaultVoice);
        }
      };

      loadVoices();
      
      // Voices load asynchronously in some browsers
      if (window.speechSynthesis.onvoiceschanged !== undefined) {
        window.speechSynthesis.onvoiceschanged = loadVoices;
      }
    } else {
      console.warn('Text-to-Speech not supported');
      setIsSupported(false);
    }

    return () => {
      window.speechSynthesis.cancel();
    };
  }, []);

  const getVoiceForCharacter = (characterName, gender) => {
    // Filter voices by language and gender
    let voiceCandidates = voices.filter(v => v.lang.includes('en'));
    
    if (gender === 'female') {
      voiceCandidates = voiceCandidates.filter(v => 
        v.name.includes('Female') || v.name.includes('Woman') || v.name.includes('Girl')
      );
    } else if (gender === 'male') {
      voiceCandidates = voiceCandidates.filter(v => 
        v.name.includes('Male') || v.name.includes('Man') || v.name.includes('Boy')
      );
    }

    // Return first match or default
    return voiceCandidates[0] || selectedVoice;
  };

  const speak = (text, options = {}) => {
    if (!isSupported || !text) return;

    const {
      voice = selectedVoice,
      rate: customRate = rate,
      volume: customVolume = volume,
      onEnd,
      onError
    } = options;

    // Cancel any ongoing speech
    window.speechSynthesis.cancel();

    const utterance = new SpeechSynthesisUtterance(text);
    
    if (voice) {
      utterance.voice = voice;
    }
    
    utterance.rate = customRate;
    utterance.volume = customVolume;

    utterance.onend = () => {
      setIsSpeaking(false);
      if (onEnd) onEnd();
    };

    utterance.onerror = (event) => {
      console.error('TTS Error:', event);
      setIsSpeaking(false);
      if (onError) onError(event);
    };

    setIsSpeaking(true);
    window.speechSynthesis.speak(utterance);
  };

  const speakWithSegments = (segments) => {
    if (!isSupported || !segments || segments.length === 0) return;

    // Cancel any ongoing speech
    window.speechSynthesis.cancel();

    let currentSegmentIndex = 0;

    const playSegment = (index) => {
      if (index >= segments.length) {
        setIsSpeaking(false);
        return;
      }

      const segment = segments[index];
      const voice = getVoiceForCharacter(segment.character, segment.gender);

      const utterance = new SpeechSynthesisUtterance(segment.text);
      
      if (voice) {
        utterance.voice = voice;
      }
      
      utterance.rate = rate;
      utterance.volume = volume;

      utterance.onend = () => {
        playSegment(index + 1);
      };

      utterance.onerror = (event) => {
        console.error('TTS Segment Error:', event);
        playSegment(index + 1); // Continue to next segment
      };

      setIsSpeaking(true);
      window.speechSynthesis.speak(utterance);
    };

    playSegment(0);
  };

  const stop = () => {
    window.speechSynthesis.cancel();
    setIsSpeaking(false);
  };

  const pause = () => {
    window.speechSynthesis.pause();
  };

  const resume = () => {
    window.speechSynthesis.resume();
  };

  return {
    isSpeaking,
    isSupported,
    voices,
    selectedVoice,
    setSelectedVoice,
    rate,
    setRate,
    volume,
    setVolume,
    speak,
    speakWithSegments,
    stop,
    pause,
    resume,
    getVoiceForCharacter
  };
}

export default useTextToSpeech;
