import type {InstructionStepModel} from "../../models/InstructionStepModel.ts";

/**
 * ======= Shared hook for common logic =======
 *
 * Provides add/remove/update functionality used by both mobile and desktop editors.
 */
export function instructionStepListEditorMethods(
    instructionStepList: InstructionStepModel[],
    onChange: (steps: InstructionStepModel[]) => void
) {
    /**
     * Update the text of a specific step
     */
    const handleUpdate = (index: number, value: string) => {
        const updated = instructionStepList.map((step, i) =>
            i === index ? {...step, text: value} : step
        );
        onChange(updated);
    };

    /**
     * Add a new step at the end
     */
    const handleAdd = () => {
        onChange([...instructionStepList,
            {
                text: "",
                internalId: crypto.randomUUID() // add internalId required for drag & drop
            }]);
    };

    /**
     * Remove a step by index
     */
    const handleRemove = (index: number) => {
        onChange(instructionStepList.filter((_, i) => i !== index));
    };

    return {handleUpdate, handleAdd, handleRemove};
}