"use client";

import { useState, useEffect, useCallback } from "react";

// Generic data type for sales_pipeline
type Sales_pipeline = Record<string, unknown>;

/**
 * Fetch and manage sales_pipeline data.
 */
export function useSales_pipeline() {
  const [data, setData] = useState<Sales_pipeline[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await fetch(`/api/sales_pipeline`);
      const json = await res.json();
      setData(Array.isArray(json) ? json : json?.data || []);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to load data");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return { data, loading, error, refetch: fetchData };
}
