'use client'; import { useState, useCallback } from 'react'; import { api } from '@/lib/api/client'; interface PipelineStage { id: string; name: string; position: number; } interface Pipeline { id: string; name: string; stages: PipelineStage[]; } export function usePipelines() { const [pipelines, setPipelines] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const fetchPipelines = useCallback(async () => { setLoading(true); setError(null); try { const result = await api.pipelines.getAll(); setPipelines(result.pipelines || []); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to fetch pipelines'); } finally { setLoading(false); } }, []); const getPipeline = async (id: string) => { const pipeline = await api.pipelines.getById(id); return pipeline; }; const createPipeline = async (data: { name: string; stages: { name: string }[] }) => { const pipeline = await api.pipelines.create(data); setPipelines(prev => [...prev, pipeline as Pipeline]); return pipeline; }; const addStage = async (pipelineId: string, name: string) => { const result = await api.pipelines.addStage(pipelineId, name); // Refresh the specific pipeline to get updated stages const updated = await api.pipelines.getById(pipelineId); setPipelines(prev => prev.map(p => p.id === pipelineId ? (updated as Pipeline) : p)); return result; }; return { pipelines, loading, error, fetchPipelines, getPipeline, createPipeline, addStage, }; }