// Cross-plot synchronisation for time-series plot widgets.
//
// Two things are shared across all *linked* timeseries plots:
//   1. The uPlot cursor crosshair, via uPlot's native cursor.sync keyed on
//      PLOT_SYNC_KEY (hovering one plot draws the matching-time crosshair on the
//      others). This works in both live and historical mode.
//   2. The visible x (time) range, for zoom/pan sync in historical mode — when a
//      user zooms one plot, the same [min,max] is applied to the others. Live
//      mode keeps its own rolling window (auto-scroll), so range sync is only
//      brokered here for historical views.
//
// A plot can opt out of both via its toolbar "link" toggle.

export const PLOT_SYNC_KEY = 'uopi-plots';

export interface XRange {
  min: number;
  max: number;
}

type RangeListener = (r: XRange) => void;

const rangeListeners = new Map<string, RangeListener>();

export function subscribeXRange(id: string, fn: RangeListener): () => void {
  rangeListeners.set(id, fn);
  return () => {
    rangeListeners.delete(id);
  };
}

// Broadcast a new visible x-range to every linked plot except the originator.
export function broadcastXRange(origin: string, r: XRange) {
  rangeListeners.forEach((fn, id) => {
    if (id !== origin) fn(r);
  });
}
