import { createContext, useContext, useRef, useCallback } from 'react';

const DraftConfigContext = createContext(null);

export function DraftConfigProvider({ children }) {
  const flushersRef = useRef({});  // key → async flush fn

  const registerFlusher = useCallback((key, fn) => {
    flushersRef.current[key] = fn;
    return () => { delete flushersRef.current[key]; };  // cleanup
  }, []);

  const hasDirtyRef = useRef({});  // key → boolean

  const setDirty = useCallback((key, isDirty) => {
    hasDirtyRef.current[key] = isDirty;
  }, []);

  const hasDirty = useCallback(() => {
    return Object.values(hasDirtyRef.current).some(Boolean);
  }, []);

  const flushAll = useCallback(async () => {
    const flushers = Object.values(flushersRef.current);
    await Promise.all(flushers.map(fn => fn()));
  }, []);

  return (
    <DraftConfigContext.Provider value={{ registerFlusher, setDirty, hasDirty, flushAll }}>
      {children}
    </DraftConfigContext.Provider>
  );
}

export function useDraftConfig() {
  return useContext(DraftConfigContext);
}
