import { Room } from 'matrix-js-sdk';
import { useMemo } from 'react';
import { Widget, WidgetParser, IStateEvent } from 'matrix-widget-api';
import { StateEvent } from '../../../../types/matrix/room';
import { useRoomState } from '../../../hooks/useRoomState';

/**
 * All valid `im.vector.modular.widgets` room widgets, reactive on room state.
 * `WidgetParser` drops empty/removed (`{}`) and malformed entries.
 */
export const useRoomWidgets = (room: Room): Widget[] => {
  const state = useRoomState(room);
  return useMemo(() => {
    const widgetEvents = state.get(StateEvent.Widget);
    if (!widgetEvents) return [];
    const stateEvents = Array.from(widgetEvents.values()).map(
      (event) => event.getEffectiveEvent() as unknown as IStateEvent,
    );
    return WidgetParser.parseWidgetsFromRoomState(stateEvents);
  }, [state]);
};
