import { Object3D } from "three";

const STATE_LAYER_PATTERN = /_S(\d+)$/i;

function getStateLayerNumber(name: string): number | null {
  const match = name.match(STATE_LAYER_PATTERN);
  return match ? Number(match[1]) : null;
}

/** Повертає damage-шари з контейнера *_States*, відсортовані за номером _S*. */
export function findDamageStateLayers(root: Object3D): Object3D[] {
  const containers: Object3D[] = [];

  root.traverse((child) => {
    if (/states/i.test(child.name)) {
      containers.push(child);
    }
  });

  const statesContainer = containers[0];
  if (!statesContainer) return [];

  return statesContainer.children
    .filter((child) => getStateLayerNumber(child.name) !== null)
    .sort((a, b) => getStateLayerNumber(a.name)! - getStateLayerNumber(b.name)!);
}
