/**
 * Generic query context — a small key/value bag appended to every records
 * fetch as `context[key]=value`, with pub/sub so views refetch when it changes.
 *
 * The framework assigns NO meaning to the keys; hosts use it to carry
 * cross-cutting request state (e.g. a multilingual `lang`) from a toolbar
 * control down to the data provider. Mirrors the server-side `context` arg the
 * DataController forwards to providers.
 */
const listeners = new Set();
let context = {};

const queryContext = {
	/** Current context as a plain object. */
	get() {
		return { ...context };
	},

	/** Set (or clear, when value is empty/null) a context key, notifying subscribers. */
	set( key, value ) {
		if ( value === undefined || value === null || value === '' ) {
			delete context[ key ];
		} else {
			context[ key ] = value;
		}
		listeners.forEach( ( fn ) => fn( queryContext.get() ) );
	},

	/** Subscribe to changes; returns an unsubscribe function. */
	subscribe( fn ) {
		listeners.add( fn );
		return () => listeners.delete( fn );
	},
};

export default queryContext;
