import { useState, useEffect } from 'react';
import {
  getHLSStreamStatus,
  type HLSStreamStatus,
} from '../services/hlsService';

/**
 * Hook pour gérer l'état d'un stream HLS
 * T0340: Create HLS Streaming Frontend Hook
 *
 * @param trackId - ID du track
 * @returns État du stream HLS avec loading, error, status, isReady, isProcessing
 */
export function useHLSStream(trackId: string) {
  const [status, setStatus] = useState<HLSStreamStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    let cancelled = false;

    async function fetchStatus() {
      try {
        setLoading(true);
        const data = await getHLSStreamStatus(trackId);
        if (!cancelled) {
          setStatus(data);
          setError(null);
        }
      } catch (err) {
        if (!cancelled) {
          setError(err as Error);
          setStatus(null);
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }

    fetchStatus();

    return () => {
      cancelled = true;
    };
  }, [trackId]);

  const isReady = status?.status === 'ready';
  const isProcessing = status?.status === 'processing';

  return {
    status,
    loading,
    error,
    isReady,
    isProcessing,
  };
}
