import { useState, useEffect } from "react";
import { traceApi } from "../api/traceApi";
import type { TraceDetailResponse } from "../types/trace";

export const useTrace = (traceId: string | null) => {
  const [trace, setTrace] = useState<TraceDetailResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    if (!traceId) return;

    const loadTrace = async () => {
      setLoading(true);
      setError(null);
      try {
        const data = await traceApi.fetchTraceDetail(traceId);
        setTrace(data);
      } catch (err) {
        setError(err as Error);
      } finally {
        setLoading(false);
      }
    };

    loadTrace();
  }, [traceId]);

  return { trace, loading, error };
};
