// Per-widget command bus.
//
// Panel logic (logic.ts) runs in view mode and can drive individual widgets via
// the `action.widget` node: enable/disable, show/hide, and — for plot widgets —
// clear or pause/resume the live stream. Each widget id gets a small reactive
// store; widget components subscribe to their own store (Canvas wraps every
// widget in a <WidgetView> that honours disabled/hidden, and PlotWidget reacts
// to paused/clear). The engine writes commands through the setters below.

import { writable, type Writable } from './store';

export interface WidgetCmd {
  disabled: boolean;   // interaction blocked + dimmed
  hidden: boolean;     // removed from the view
  paused: boolean;     // plot: stop ingesting live samples
  clearNonce: number;  // plot: bumped to request a one-shot buffer clear
}

const DEFAULT: WidgetCmd = { disabled: false, hidden: false, paused: false, clearNonce: 0 };

const stores = new Map<string, Writable<WidgetCmd>>();

export function getWidgetCmdStore(id: string): Writable<WidgetCmd> {
  let s = stores.get(id);
  if (!s) { s = writable({ ...DEFAULT }); stores.set(id, s); }
  return s;
}

export function setWidgetDisabled(id: string, v: boolean): void {
  getWidgetCmdStore(id).update(c => ({ ...c, disabled: v }));
}
export function setWidgetHidden(id: string, v: boolean): void {
  getWidgetCmdStore(id).update(c => ({ ...c, hidden: v }));
}
export function setPlotPaused(id: string, v: boolean): void {
  getWidgetCmdStore(id).update(c => ({ ...c, paused: v }));
}
export function clearPlot(id: string): void {
  getWidgetCmdStore(id).update(c => ({ ...c, clearNonce: c.clearNonce + 1 }));
}

// Reset every widget back to its default state. Called when a panel unmounts so
// that re-opening the same panel (whose widget ids are stable) starts fresh
// rather than inheriting disabled/hidden/paused flags from the previous view.
export function resetWidgetCmds(): void {
  for (const s of stores.values()) s.set({ ...DEFAULT });
}
