import { useCallback, useMemo, useState } from 'react';

export interface CollectionFilterInitialFetchTimingProps {
  /**
   * At which point the initial fetch of the filter collection data takes place. If this prop is omitted, it will take place on component mount.<br> <br>
   * Supported values: <br>
   * - `focus`: On the first visitor interaction with the filter component.
   * @default undefined - on component mount
   * @external
   */
  initialFetchTiming?: 'focus';
  collection: {
    initialFetch: () => unknown;
  };
}
export function useCollectionFilterInitialFetchTiming(
  props: CollectionFilterInitialFetchTimingProps,
) {
  const { initialFetchTiming, collection } = props;

  useState(() => {
    if (!initialFetchTiming) {
      collection.initialFetch();
    }
  });

  const onFocus = useCallback(() => {
    initialFetchTiming === 'focus' && collection.initialFetch();
  }, [initialFetchTiming]);

  const skipInitialFetch = useMemo(
    () => initialFetchTiming === 'focus',
    [initialFetchTiming],
  );

  return {
    onFocus,
    skipInitialFetch,
  };
}
