import { atom } from 'jotai';
import { getAtomStore } from 'src/atoms/atomStore/atomStore';

const internalWidgetArrayAtom = atom<HTMLElement[]>([]);

export const widgetArrayAtom = atom(get => get(internalWidgetArrayAtom));

/**
 * This function call is used to create a list of the Spiffy widgets
 * that are rendering on the page.
 *
 * It is used by the FloatingButton widget to slide out of view when it
 * overlaps with another Spiffy widget.
 *
 * The spiffy widgets should be added to the this array for the floating button
 * to know about them.
 *
 * Today the "SuggestionBar" widget is not added, but the other widgets are.
 *
 */
export const addWidget = (ref: HTMLElement, idx?: number) => {
  const atomStore = getAtomStore();
  const val = atomStore.get(internalWidgetArrayAtom);
  const insertIdx = idx ?? val.length;
  val[insertIdx] = ref;
  atomStore.set(internalWidgetArrayAtom, val);
};
