import { Node } from 'prosemirror-model';
import { EditorState, TextSelection } from 'prosemirror-state';
import { CellSelection, TableMap } from 'prosemirror-tables';
import { findParentNodeOfType } from 'prosemirror-utils';
import { TABLE_CELL, TABLE_HEADER } from './NodeNames.js';
function findActionableCellFromSelection(selection) {
  var $anchorCell = selection.$anchorCell;
  var start = $anchorCell.start(-1);
  var table = $anchorCell.node(-1);
  var tableMap = TableMap.get(table);
  var topRightRect;
  var posFound = null;
  var nodeFound = null;
  selection.forEachCell(function (cell, cellPos) {
    var cellRect = tableMap.findCell(cellPos - start);
    if (!topRightRect || cellRect.top >= topRightRect.top && cellRect.left > topRightRect.left) {
      topRightRect = cellRect;
      posFound = cellPos;
      nodeFound = cell;
    }
  });
  return posFound === null ? null : {
    node: nodeFound,
    pos: posFound
  };
}
export default function findActionableCell(state) {
  var doc = state.doc,
    selection = state.selection,
    schema = state.schema;
  var tdType = schema.nodes[TABLE_CELL];
  var thType = schema.nodes[TABLE_HEADER];
  if (!tdType && !thType) {
    return null;
  }
  var userSelection = selection;
  if (userSelection instanceof TextSelection) {
    var from = selection.from,
      to = selection.to;
    if (from !== to) {
      return null;
    }
    var result = tdType && findParentNodeOfType(tdType)(selection) || thType && findParentNodeOfType(thType)(selection);
    if (!result) {
      return null;
    }
    userSelection = CellSelection.create(doc, result.pos);
  }
  if (userSelection instanceof CellSelection) {
    return findActionableCellFromSelection(userSelection);
  }
  return null;
}