import { cloneFieldWithNewIds } from "./fieldNames.js";
import { findField, transformAtId } from "./treeWalk.js";
export const updateFieldDeep = (fields, fieldId, updates) => {
    return fields.map((field) => {
        if (field.id === fieldId) {
            return {
                ...field,
                ...updates,
                id: field.id,
            };
        }
        if (field.type === 'section') {
            return {
                ...field,
                fields: updateFieldDeep(field.fields, fieldId, updates),
            };
        }
        return field;
    });
};
export const removeFieldDeep = (fields, fieldId) => {
    const filtered = fields.filter((field) => field.id !== fieldId);
    return filtered.map((field) => field.type === 'section'
        ? { ...field, fields: removeFieldDeep(field.fields, fieldId) }
        : field);
};
export const addChildToSectionDeep = (fields, sectionId, newChild) => {
    return fields.map((field) => {
        if (field.id === sectionId && field.type === 'section') {
            return { ...field, fields: [...field.fields, newChild] };
        }
        if (field.type === 'section') {
            return {
                ...field,
                fields: addChildToSectionDeep(field.fields, sectionId, newChild),
            };
        }
        return field;
    });
};
export const containsId = (field, id) => findField([field], (f) => f.id === id) !== null;
export const isArrayModeSection = (fields, sectionId) => {
    const section = findField(fields, (f) => f.id === sectionId);
    return section?.type === 'section' && Boolean(section.index);
};
export const insertAtTargetDeep = (fields, targetId, offset, makeField) => transformAtId(fields, targetId, (siblings, index, parent) => {
    const arrayMode = Boolean(parent?.index);
    const newField = makeField(arrayMode);
    return [...siblings.slice(0, index + offset), newField, ...siblings.slice(index + offset)];
});
export const duplicateFieldDeep = (fields, fieldId, generateId, existingNames) => transformAtId(fields, fieldId, (siblings, index) => {
    const clone = cloneFieldWithNewIds(siblings[index], generateId, existingNames);
    return [...siblings.slice(0, index + 1), clone, ...siblings.slice(index + 1)];
});
export const swapInListDeep = (fields, fieldId, delta) => {
    let didSwap = false;
    const result = transformAtId(fields, fieldId, (siblings, index) => {
        const target = index + delta;
        if (target < 0 || target >= siblings.length) {
            return siblings;
        }
        const next = [...siblings];
        [next[index], next[target]] = [next[target], next[index]];
        didSwap = true;
        return next;
    });
    return result === null || !didSwap ? { fields, handled: false } : { fields: result, handled: true };
};
//# sourceMappingURL=fieldTreeOps.js.map
