'use client';
import { useState, useEffect, useRef, useCallback } from 'react';
export function useFeatureLogs(featureId) {
    const [content, setContent] = useState('');
    const [isConnected, setIsConnected] = useState(false);
    const [error, setError] = useState(null);
    const eventSourceRef = useRef(null);
    const cleanup = useCallback(() => {
        if (eventSourceRef.current) {
            eventSourceRef.current.close();
            eventSourceRef.current = null;
        }
        setIsConnected(false);
    }, []);
    useEffect(() => {
        if (!featureId) {
            setContent('');
            setIsConnected(false);
            setError(null);
            return;
        }
        // Reset state for new featureId
        setContent('');
        setError(null);
        // Connect EventSource for live updates
        const es = new EventSource(`/api/feature-logs?featureId=${featureId}`);
        eventSourceRef.current = es;
        es.onopen = () => {
            setIsConnected(true);
        };
        es.addEventListener('initial', (event) => {
            const data = JSON.parse(event.data);
            setContent(data.content);
        });
        es.addEventListener('log', (event) => {
            const data = JSON.parse(event.data);
            setContent((prev) => prev + data.content);
        });
        es.addEventListener('error', (event) => {
            try {
                const data = JSON.parse(event.data);
                setError(data.error);
            }
            catch {
                setError(event.data ? String(event.data) : 'Log stream unavailable');
            }
        });
        es.onerror = () => {
            setIsConnected(false);
        };
        return () => {
            es.close();
            eventSourceRef.current = null;
        };
    }, [featureId, cleanup]);
    return { content, isConnected, error };
}
