const DIRECT_TARGETS = Object.freeze({
  camera: 'camera',
  grassField: 'grassField',
  voxelTunnel: 'voxelTunnel',
  sphereCloner: 'sphereCloner',
  heartField: 'heartField',
  landscapeField: 'landscapeField',
  clothSimulation: 'clothSimulation',
  particleSystem: 'particleSystem',
  displacedSphere: 'displacedSphere',
  fractalTree: 'fractalTree',
  sierpinskiPyramid: 'sierpinskiPyramid',
  mengerSponge: 'mengerSponge',
  coralGrowth: 'coralGrowth',
  crystalLattice: 'crystalLattice',
  starCrawl: 'starCrawl',
  fireworksDisplay: 'fireworksDisplay',
});

export function resolveParameterTarget(sceneData, type, id) {
  if (!sceneData) return null;
  if (type === 'scene') return { value: sceneData, id };
  if (type === 'group') {
    const value = sceneData.groups?.find(group => group.id === id);
    return value ? { value, id } : null;
  }
  if (type === 'light' || type === 'object') {
    const index = Number.parseInt(id, 10);
    const collection = type === 'light' ? sceneData.lights : sceneData.objects;
    const value = collection?.[index];
    return value ? { value, id: index } : null;
  }
  const property = DIRECT_TARGETS[type];
  const value = property ? sceneData[property] : null;
  return value ? { value, id } : null;
}

export function parameterPanelItemSelector(type, id) {
  const escapedType = String(type).replaceAll('"', '\\"');
  if (type === 'light' || type === 'object' || type === 'group') {
    const escapedId = String(id).replaceAll('"', '\\"');
    return `.obj-item[data-type="${escapedType}"][data-id="${escapedId}"]`;
  }
  return `.obj-item[data-type="${escapedType}"]`;
}

export function createParameterDomainController({ handlers }) {
  return {
    show({ sceneData, sceneIdx, type, id }) {
      const target = resolveParameterTarget(sceneData, type, id);
      const handler = handlers[type];
      if (!target || typeof handler !== 'function') return false;
      handler(target.value, sceneIdx, target.id);
      return true;
    },
  };
}
