import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
import { Fragment, Slice } from '@atlaskit/editor-prosemirror/model';
import { findChildrenByType, findParentNodeOfType, findSelectedNodeOfType } from '@atlaskit/editor-prosemirror/utils';
import { getSupportedListTypesSet, isBulletOrOrderedList, isTaskList, convertBlockToInlineContent } from './list-utils';
var getContentSupportChecker = function getContentSupportChecker(targetNodeType) {
  return function (node) {
    try {
      return targetNodeType.validContent(Fragment.from(node));
    } catch (_unused) {
      return false;
    }
  };
};
var _transformListRecursively = function transformListRecursively(props, onhandleUnsupportedContent) {
  var transformedItems = [];
  var listNode = props.listNode,
    isSourceBulletOrOrdered = props.isSourceBulletOrOrdered,
    isTargetBulletOrOrdered = props.isTargetBulletOrOrdered,
    isSourceTask = props.isSourceTask,
    isTargetTask = props.isTargetTask,
    supportedListTypes = props.supportedListTypes,
    schema = props.schema,
    targetNodeType = props.targetNodeType;
  var _schema$nodes = schema.nodes,
    taskList = _schema$nodes.taskList,
    listItem = _schema$nodes.listItem,
    taskItem = _schema$nodes.taskItem,
    paragraph = _schema$nodes.paragraph;
  listNode.forEach(function (child) {
    if (isSourceBulletOrOrdered && isTargetTask) {
      // Convert bullet/ordered => task
      if (child.type === listItem) {
        var inlineContent = [];
        var nestedTaskLists = [];
        child.forEach(function (grandChild) {
          if (supportedListTypes.has(grandChild.type) && grandChild.type !== taskList) {
            nestedTaskLists.push(_transformListRecursively(_objectSpread(_objectSpread({}, props), {}, {
              listNode: grandChild
            }), onhandleUnsupportedContent));
          } else if (!getContentSupportChecker(taskItem)(grandChild) && !grandChild.isTextblock) {
            onhandleUnsupportedContent === null || onhandleUnsupportedContent === void 0 || onhandleUnsupportedContent(grandChild);
          } else {
            inlineContent.push.apply(inlineContent, _toConsumableArray(convertBlockToInlineContent(grandChild, schema)));
          }
        });
        transformedItems.push(taskItem.create(null, inlineContent.length > 0 ? inlineContent : null));
        transformedItems.push.apply(transformedItems, nestedTaskLists);
      }
    } else if (isSourceTask && isTargetBulletOrOrdered) {
      // Convert task => bullet/ordered
      if (child.type === taskItem) {
        var _inlineContent = _toConsumableArray(child.content.content);
        var paragraphNode = paragraph.create(null, _inlineContent.length > 0 ? _inlineContent : null);
        transformedItems.push(listItem.create(null, [paragraphNode]));
      } else if (child.type === taskList) {
        var transformedNestedList = _transformListRecursively(_objectSpread(_objectSpread({}, props), {}, {
          listNode: child
        }), onhandleUnsupportedContent);
        var lastItem = transformedItems[transformedItems.length - 1];
        if ((lastItem === null || lastItem === void 0 ? void 0 : lastItem.type) === listItem) {
          // Attach nested list to previous item
          var updatedContent = [].concat(_toConsumableArray(lastItem.content.content), [transformedNestedList]);
          transformedItems[transformedItems.length - 1] = listItem.create(lastItem.attrs, updatedContent);
        } else {
          // No previous item, flatten nested items
          transformedItems.push.apply(transformedItems, _toConsumableArray(transformedNestedList.content.content));
        }
      }
    } else if (isSourceBulletOrOrdered && isTargetBulletOrOrdered) {
      if (child.type === listItem) {
        var convertedNestedLists = [];
        child.forEach(function (grandChild) {
          if (supportedListTypes.has(grandChild.type) && grandChild.type !== targetNodeType) {
            var convertedNode = _transformListRecursively(_objectSpread(_objectSpread({}, props), {}, {
              listNode: grandChild
            }), onhandleUnsupportedContent);
            convertedNestedLists.push(convertedNode);
          } else {
            convertedNestedLists.push(grandChild);
          }
        });
        transformedItems.push(listItem.create(null, convertedNestedLists));
      }
    }
  });
  return targetNodeType.create(null, transformedItems);
};

/**
 * Transform list structure between different list types
 */
export { _transformListRecursively as transformListRecursively };
export var transformListStructure = function transformListStructure(context) {
  var tr = context.tr,
    sourceNode = context.sourceNode,
    sourcePos = context.sourcePos,
    targetNodeType = context.targetNodeType;
  var nodes = tr.doc.type.schema.nodes;
  var unsupportedContent = [];
  var onhandleUnsupportedContent = function onhandleUnsupportedContent(content) {
    unsupportedContent.push(content);
  };
  try {
    var listNode = {
      node: sourceNode,
      pos: sourcePos
    };
    var sourceList = listNode.node,
      listPos = listNode.pos;
    // const { taskList, listItem, taskItem, paragraph } = nodes;

    var isSourceBulletOrOrdered = isBulletOrOrderedList(sourceList.type);
    var isTargetTask = isTaskList(targetNodeType);
    var isSourceTask = isTaskList(sourceList.type);
    var isTargetBulletOrOrdered = isBulletOrOrderedList(targetNodeType);
    var supportedListTypes = getSupportedListTypesSet(nodes);
    var newList = _transformListRecursively({
      isSourceBulletOrOrdered: isSourceBulletOrOrdered,
      isSourceTask: isSourceTask,
      isTargetBulletOrOrdered: isTargetBulletOrOrdered,
      isTargetTask: isTargetTask,
      listNode: sourceList,
      schema: tr.doc.type.schema,
      supportedListTypes: supportedListTypes,
      targetNodeType: targetNodeType
    }, onhandleUnsupportedContent);
    tr.replaceWith(listPos, listPos + sourceList.nodeSize, [newList].concat(unsupportedContent));
    return tr;
  } catch (_unused2) {
    return tr;
  }
};

/**
 * Transform between different list types
 */
export var transformBetweenListTypes = function transformBetweenListTypes(context) {
  var tr = context.tr,
    sourceNode = context.sourceNode,
    sourcePos = context.sourcePos,
    targetNodeType = context.targetNodeType;
  var nodes = tr.doc.type.schema.nodes;
  var sourceListType = sourceNode.type;
  var isSourceBulletOrOrdered = isBulletOrOrderedList(sourceListType);
  var isTargetTask = isTaskList(targetNodeType);
  var isSourceTask = isTaskList(sourceListType);
  var isTargetBulletOrOrdered = isBulletOrOrderedList(targetNodeType);

  // Check if we need structure transformation
  var needsStructureTransform = isSourceBulletOrOrdered && isTargetTask || isSourceTask && isTargetBulletOrOrdered;
  try {
    if (!needsStructureTransform) {
      // Simple type change for same structure lists (bullet <-> ordered)
      // Apply to the main list
      tr.setNodeMarkup(sourcePos, targetNodeType);

      // Apply to nested lists
      var listStart = sourcePos;
      var listEnd = sourcePos + sourceNode.nodeSize;
      var supportedListTypesSet = getSupportedListTypesSet(nodes);
      tr.doc.nodesBetween(listStart, listEnd, function (node, pos, parent) {
        // Only process nested lists (not the root list we already handled)
        if (supportedListTypesSet.has(node.type) && pos !== sourcePos) {
          var isNestedList = parent && (supportedListTypesSet.has(parent.type) || parent.type === nodes.listItem);
          if (isNestedList) {
            var shouldTransformNode = node.type === sourceListType || isBulletOrOrderedList(node.type) && isTargetBulletOrOrdered;
            if (shouldTransformNode) {
              tr.setNodeMarkup(pos, targetNodeType);
            }
          }
        }
        return true; // Continue traversing
      });
      return tr;
    } else {
      return transformListStructure(context);
    }
  } catch (_unused3) {
    return null;
  }
};

/**
 * Transform selection to task list
 * Handles the special structure where taskItem contains text directly (no paragraph wrapper)
 */
export var transformToTaskList = function transformToTaskList(tr, range, targetNodeType, targetAttrs, nodes) {
  try {
    var taskItem = nodes.taskItem;
    var listItems = [];

    // Process each block in the range
    tr.doc.nodesBetween(range.start, range.end, function (node) {
      if (node.isBlock) {
        // For block nodes like paragraphs, directly use their inline content
        var inlineContent = _toConsumableArray(node.content.content);
        if (inlineContent.length > 0) {
          // Create task item with inline content directly
          var listItem = taskItem.create(targetAttrs, inlineContent);
          listItems.push(listItem);
        }
      }
      return false; // Don't traverse into children
    });
    if (listItems.length === 0) {
      return null;
    }

    // Create the new task list
    var newList = targetNodeType.create(targetAttrs, listItems);

    // Replace the range with the new list
    tr.replaceWith(range.start, range.end, newList);
    return tr;
  } catch (_unused4) {
    return null;
  }
};
export var transformTaskListToBlockNodes = function transformTaskListToBlockNodes(context) {
  var tr = context.tr,
    targetNodeType = context.targetNodeType,
    targetAttrs = context.targetAttrs,
    sourceNode = context.sourceNode,
    sourcePos = context.sourcePos;
  var selection = tr.selection;
  var schema = selection.$from.doc.type.schema;
  var taskItemsResult = findChildrenByType(sourceNode, schema.nodes.taskItem);
  var taskItems = taskItemsResult.map(function (item) {
    return item.node;
  });
  var taskItemFragments = taskItems.map(function (taskItem) {
    return taskItem.content;
  });
  var targetNodes = [];

  // Convert fragments to headings if target is heading
  if (targetNodeType === schema.nodes.heading && targetAttrs) {
    // convert the fragments to headings
    var targetHeadingLevel = targetAttrs.level;
    targetNodes = taskItemFragments.map(function (fragment) {
      return schema.nodes.heading.createChecked({
        level: targetHeadingLevel
      }, fragment.content);
    });
  }

  // Convert fragments to paragraphs if target is paragraphs
  if (targetNodeType === schema.nodes.paragraph) {
    // convert the fragments to paragraphs
    targetNodes = taskItemFragments.map(function (fragment) {
      return schema.nodes.paragraph.createChecked({}, fragment.content);
    });
  }

  // Convert fragments to code block if target is code block
  if (targetNodeType === schema.nodes.codeBlock) {
    // convert the fragments to one code block
    var codeBlockContent = taskItemFragments.map(function (fragment) {
      return fragment.textBetween(0, fragment.size, '\n');
    }).join('\n');
    targetNodes = [schema.nodes.codeBlock.createChecked({}, schema.text(codeBlockContent))];
  }

  // Replace the task list node with the new content in the transaction
  var slice = new Slice(Fragment.fromArray(targetNodes), 0, 0);
  var rangeStart = sourcePos !== null ? sourcePos : selection.from;
  tr.replaceRange(rangeStart, rangeStart + sourceNode.nodeSize, slice);
  return tr;
};
export var getFormattedNode = function getFormattedNode(tr) {
  var selection = tr.selection;
  var nodes = tr.doc.type.schema.nodes;

  // Find the node to format from the current selection
  var nodeToFormat;
  var nodePos = selection.from;

  // Try to find the current node from selection
  var selectedNode = findSelectedNodeOfType([nodes.paragraph, nodes.heading, nodes.blockquote, nodes.panel, nodes.expand, nodes.codeBlock, nodes.bulletList, nodes.orderedList, nodes.taskList, nodes.layoutSection])(selection);
  if (selectedNode) {
    nodeToFormat = selectedNode.node;
    nodePos = selectedNode.pos;
  } else {
    // Try to find parent node (including list parents)
    var parentNode = findParentNodeOfType([nodes.blockquote, nodes.panel, nodes.expand, nodes.codeBlock, nodes.listItem, nodes.taskItem, nodes.layoutSection])(selection);
    if (parentNode) {
      nodeToFormat = parentNode.node;
      nodePos = parentNode.pos;
      var paragraphOrHeadingNode = findParentNodeOfType([nodes.paragraph, nodes.heading])(selection);
      // Special case: if we found a listItem, check if we need the parent list instead
      if (parentNode.node.type === nodes.listItem || parentNode.node.type === nodes.taskItem) {
        var listParent = findParentNodeOfType([nodes.bulletList, nodes.orderedList, nodes.taskList])(selection);
        if (listParent) {
          // For list transformations, we want the list parent, not the listItem
          nodeToFormat = listParent.node;
          nodePos = listParent.pos;
        }
      } else if (parentNode.node.type !== nodes.blockquote && paragraphOrHeadingNode) {
        nodeToFormat = paragraphOrHeadingNode.node;
        nodePos = paragraphOrHeadingNode.pos;
      }
    }
  }
  if (!nodeToFormat) {
    nodeToFormat = selection.$from.node();
    nodePos = selection.$from.pos;
  }
  return {
    node: nodeToFormat,
    pos: nodePos
  };
};