import { useEffect, useRef, useCallback } from 'react'; import { saveProductDraft, clearProductDraft, type ProductDraftData, } from '@/lib/product-draft'; type DraftType = 'create' | 'edit'; export function useProductDraftSave( type: DraftType, data: ProductDraftData, userId?: number, productId?: number, delay = 500, ) { const timeoutRef = useRef | null>(null); const dataRef = useRef(data); dataRef.current = data; const flush = useCallback(() => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); timeoutRef.current = null; } const ok = saveProductDraft(type, dataRef.current, userId, productId); return ok; }, [type, userId, productId]); useEffect(() => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } timeoutRef.current = setTimeout(() => { saveProductDraft(type, dataRef.current, userId, productId); timeoutRef.current = null; }, delay); return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }; }, [data, type, userId, productId, delay]); useEffect(() => { return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } saveProductDraft(type, dataRef.current, userId, productId); }; }, [type, userId, productId]); return { flush }; } export function useProductDraftClear( type: DraftType, userId?: number, productId?: number, ) { useEffect(() => { return () => { clearProductDraft(type, userId, productId); }; }, [type, userId, productId]); }