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

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

export { useShippingOptionTarget };
