/**
 * Command palette registry (Cmd/Ctrl+K). Core registers navigation + common actions;
 * Add-ons and features add theirs through window.StreamSeraAdminApi.registerCommand().
 */
export interface Command {
	id: string;
	label: string;
	/** Secondary text (shortcut hint, section name). */
	hint?: string;
	/** Group heading in the palette. */
	group?: string;
	icon?: string;
	keywords?: string[];
	/** Navigate to this route when selected (or run `run`). */
	to?: string;
	run?: ( ctx: {
		notify: ( message: string, status?: string ) => void;
	} ) => void | Promise< void >;
	order?: number;
}

const commands = new Map< string, Command >();
const listeners = new Set< () => void >();

export function registerCommand( cmd: Command ) {
	commands.set( cmd.id, cmd );
	listeners.forEach( ( l ) => l() );
}

export function unregisterCommand( id: string ) {
	commands.delete( id );
	listeners.forEach( ( l ) => l() );
}

export function getCommands(): Command[] {
	return [ ...commands.values() ].sort(
		( a, b ) => ( a.order || 50 ) - ( b.order || 50 )
	);
}

export function onCommandsChange( cb: () => void ): () => void {
	listeners.add( cb );
	return () => {
		listeners.delete( cb );
	};
}

/** Open the palette programmatically (e.g. from a header button). */
export function openPalette() {
	window.dispatchEvent( new Event( 'streamsera:palette-open' ) );
}
