import { useState, useCallback } from 'react';
import type { AccountDataEvents } from 'matrix-js-sdk';
import { useMatrixClient } from './useMatrixClient';
import { useAccountDataCallback } from './useAccountDataCallback';

export function useAccountData(eventType: string) {
  const mx = useMatrixClient();
  // Generic hook accepts arbitrary string keys (incl. custom Vojo / Ponies
  // event-types augmented in sdkAugmentation.d.ts and one-off dev-tool keys).
  // Cast through `keyof AccountDataEvents` to satisfy the SDK literal-union.
  const [event, setEvent] = useState(() => mx.getAccountData(eventType as keyof AccountDataEvents));

  useAccountDataCallback(
    mx,
    useCallback(
      (evt) => {
        if (evt.getType() === eventType) {
          setEvent(evt);
        }
      },
      [eventType, setEvent]
    )
  );

  return event;
}
