// src/hooks/useAudioPlayer.ts
import { useState, useCallback, useEffect } from 'react';
import Taro from '@tarojs/taro';

type AudioPlayStatus = 'idle' | 'playing' | 'paused' | 'stopped' | 'error';

export interface AudioInstance {
  play: () => void;
  pause: () => void;
  stop: () => void;
  destroy: () => void;
  getStatus: () => AudioPlayStatus;
}

export default function useAudioPlayer(url: string) {
  const [status, setStatus] = useState<AudioPlayStatus>('idle');
  const [audio, setAudio] = useState<Taro.InnerAudioContext | null>(null);

  // 初始化音频实例
  useEffect(() => {
    const audioInstance = Taro.createInnerAudioContext();
    audioInstance.src = url;

    // 事件监听
    audioInstance.onPlay(() => setStatus('playing'));
    audioInstance.onPause(() => setStatus('paused'));
    audioInstance.onStop(() => setStatus('stopped'));
    audioInstance.onEnded(() => setStatus('stopped'));
    audioInstance.onError(() => {
      setStatus('error');
      audioInstance.destroy();
    });

    setAudio(audioInstance);

    // 清理函数
    return () => {
      audioInstance.destroy();
      setAudio(null);
    };
  }, [url]);

  // 播放控制方法
  const play = useCallback(() => {
    if (audio && status !== 'playing') {
      audio.play();
    }
  }, [audio, status]);

  const pause = useCallback(() => {
    if (audio && status === 'playing') {
      audio.pause();
    }
  }, [audio, status]);

  const stop = useCallback(() => {
    if (audio && (status === 'playing' || status === 'paused')) {
      audio.stop();
    }
  }, [audio, status]);

  return {
    status,
    play,
    pause,
    stop,
    audioInstance: audio, // 可选：暴露原始实例用于扩展
  };
}