import { useMemo } from 'preact/hooks';
import { ExtensionHasNoTargetError } from './errors.mjs';
import { useApi } from './api.mjs';
import { useSubscription } from './subscription.mjs';

/**
 * Returns the pickup location option the extension is attached to. This hook can only be used by extensions in the following
 * extension target:
 * - `purchase.checkout.pickup-location-option-item.render-after`
 */
function usePickupLocationOptionTarget() {
  const api = useApi();
  if (!api.target || api.isTargetSelected === undefined) {
    throw new ExtensionHasNoTargetError('usePickupLocationOptionTarget', api.extension.target);
  }
  const pickupLocationOptionTarget = useSubscription(api.target);
  const isTargetSelected = useSubscription(api.isTargetSelected);
  const pickupLocationOption = useMemo(() => {
    return {
      pickupLocationOptionTarget,
      isTargetSelected
    };
  }, [pickupLocationOptionTarget, isTargetSelected]);
  return pickupLocationOption;
}

export { usePickupLocationOptionTarget };
