/**
 * Find the actual deletable target for a node. Linked nodes (owned by parent
 * components like ColumnLayout columns or Section inner) are structurally
 * non-deletable in Craft.js — actions.delete() throws on them. When the
 * selected node is an empty linked node and all its linked siblings are also
 * empty (i.e., the whole layout is empty), redirect deletion to the owning
 * parent so the layout itself goes away. Otherwise return null to refuse
 * deletion — protects against nuking a layout that has content in other cols.
 */
export function findDeletableTarget(query: any, nodeId: string | null | undefined): string | null {
  if (!nodeId || nodeId === 'ROOT') return null;
  try {
    const node = query.node(nodeId).get();
    const parentId: string | null | undefined = node?.data?.parent;
    if (!parentId) return nodeId;
    const parent = query.node(parentId).get();
    const linkedIds = Object.values((parent?.data?.linkedNodes || {}) as Record<string, string>);
    if (!linkedIds.includes(nodeId)) return nodeId;
    const allEmpty = linkedIds.every((id) => {
      const sib = query.node(id).get();
      return ((sib?.data?.nodes as string[] | undefined) || []).length === 0;
    });
    if (!allEmpty) return null;
    return findDeletableTarget(query, parentId);
  } catch {
    return null;
  }
}
