// src/utils.js

/**
 * Recursively finds an item by its ID in a tree structure.
 * @param {Array} items - The array of items to search.
 * @param {String} id - The ID of the item to find.
 * @returns {Object|null} The found item or null.
 */
export function findItemDeep(items, id) {
  for (const item of items) {
    if (item.id === id) {
      return item;
    }
    if (item.children) {
      const found = findItemDeep(item.children, id);
      if (found) {
        return found;
      }
    }
  }
  return null;
}

/**
 * Recursively finds the container (parent's children array) of an item by its ID.
 * @param {Array} items - The array of items to search.
 * @param {String} id - The ID of the item whose container to find.
 * @returns {Array|null} The container array or null.
 */
export function findContainer(items, id) {
    for (const item of items) {
      if (item.children?.find(child => child.id === id)) {
        return item.children;
      }
      if (item.children) {
        const found = findContainer(item.children, id);
        if (found) {
          return found;
        }
      }
    }
    // Check if the ID is in the root
    if (items.find(item => item.id === id)) {
        return items;
    }
    return null;
}


/**
 * Removes an item from the tree.
 * @param {Array} items - The array of items.
 * @param {String} id - The ID of the item to remove.
 * @returns {Array} A new array with the item removed.
 */
export function removeItem(items, id) {
  const newItems = [];
  for (const item of items) {
    if (item.id === id) continue;
    if (item.children) {
      item.children = removeItem(item.children, id);
    }
    newItems.push(item);
  }
  return newItems;
}

/**
 * Adds an item to the tree at a specific location.
 * @param {Array} items - The array of items.
 * @param {Object} activeItem - The item being dragged.
 * @param {String} overId - The ID of the item being hovered over.
 * @param {Boolean} isBelow - If true, place below; otherwise, above.
 * @param {Boolean} isChild - If true, place as a child.
 * @returns {Array} A new array with the item added.
 */
export function addItem(items, activeItem, overId, isBelow, isChild) {
  if (isChild) {
    // Dropping as a child
    for (const item of items) {
      if (item.id === overId) {
        item.children = item.children ? [...item.children, activeItem] : [activeItem];
        break;
      }
      if (item.children) {
        item.children = addItem(item.children, activeItem, overId, isBelow, isChild);
      }
    }
  } else {
    // Dropping as a sibling
    const container = findContainer(items, overId);
    if (container) {
      const overIndex = container.findIndex(item => item.id === overId);
      const newIndex = isBelow ? overIndex + 1 : overIndex;
      container.splice(newIndex, 0, activeItem);
    }
  }
  return items;
}