import { findDomRefAtPos } from '@atlaskit/editor-prosemirror/utils';
import { ACTION, ACTION_SUBJECT, EVENT_TYPE } from '../analytics';
export const getDomRefFromSelection = (view, actionSubjectId, editorAnalyticsAPI) => {
  try {
    const domRef = findDomRefAtPos(view.state.selection.from, view.domAtPos.bind(view));
    if (domRef instanceof HTMLElement) {
      // If element is not a paragraph, we need to find the closest paragraph parent
      if (domRef.nodeName !== 'P') {
        const paragraphRef = domRef.closest('p');
        if (paragraphRef) {
          return paragraphRef;
        }
      }
      return domRef;
    } else {
      throw new Error('Invalid DOM reference');
    }
  } catch (error) {
    if (editorAnalyticsAPI) {
      const payload = {
        action: ACTION.ERRORED,
        actionSubject: ACTION_SUBJECT.PICKER,
        actionSubjectId: actionSubjectId,
        eventType: EVENT_TYPE.OPERATIONAL,
        attributes: {
          error: 'Error getting DOM reference from selection'
        }
      };
      editorAnalyticsAPI.fireAnalyticsEvent(payload);
    }
  }
};