import Logger from 'src/application/logging/logger';
import { useCallback } from 'react';

const logger = new Logger('useCustomerSupportHandoff');

/**
 * Hook to call the `click` method of the merchant's customer support chat widget.
 *
 * @param onSwitchToAgent a function to override the function returned by the hook. This is mainly to
 * preserve backward compatibility for merchants not using Kustomer and will be removed when all
 * CS integrations are handled.
 *
 * @returns a function that searches for the customer support chat widget and calls the `click` method.
 */
export const useCustomerSupportHandoff = (onSwitchToAgent?: () => void) => {
  // TODO handle Gorgias

  const onKustomerSwitch = useCallback(() => {
    const kustomerElement = document.getElementById('kustomer-ui-sdk-iframe');

    if (kustomerElement == null || !(kustomerElement instanceof HTMLIFrameElement)) {
      logger.logError('Kustomer iFrame element not found', undefined);
      return;
    }

    const kustomerButton = kustomerElement.contentWindow?.document?.getElementById('rootChatIcon');

    if (kustomerButton == null) {
      logger.logError('Kustomer button not found', undefined);
      return;
    }

    kustomerButton.click();
  }, []);

  if (onSwitchToAgent != null) {
    return { onSwitch: onSwitchToAgent };
  }

  return { onSwitch: onKustomerSwitch };
};
