function findGroupChild(scene, child) {
  let match = null;
  scene.traverse(object => {
    if (child.type === 'object' && object.isMesh && object.userData?.objIndex === child.id) {
      match = object;
    } else if (child.type === 'light' && object.isLight && object.userData?.lightIndex === child.id) {
      match = object;
    }
  });
  return match;
}

export function createSceneGroups(THREE, scene, groups = []) {
  const threeGroups = {};
  groups.forEach(groupData => {
    const group = new THREE.Group();
    group.position.set(
      groupData.position?.x || 0,
      groupData.position?.y || 0,
      groupData.position?.z || 0
    );
    group.rotation.set(
      (groupData.rotation?.x || 0) * Math.PI / 180,
      (groupData.rotation?.y || 0) * Math.PI / 180,
      (groupData.rotation?.z || 0) * Math.PI / 180
    );
    group.scale.set(
      groupData.scale?.x || 1,
      groupData.scale?.y || 1,
      groupData.scale?.z || 1
    );
    group.userData.groupId = groupData.id;
    group.userData.isSceneGroup = true;
    group.visible = groupData.visible !== false;
    scene.add(group);
    threeGroups[groupData.id] = group;

    groupData.children?.forEach(child => {
      const object = findGroupChild(scene, child);
      if (!object) return;
      const worldPosition = object.getWorldPosition(new THREE.Vector3());
      scene.remove(object);
      group.add(object);
      object.position.set(
        worldPosition.x - (groupData.position?.x || 0),
        worldPosition.y - (groupData.position?.y || 0),
        worldPosition.z - (groupData.position?.z || 0)
      );
    });
  });
  return threeGroups;
}
