export function sceneBackgroundIsTransparent(segment, isFirstScene) {
  return segment?.transparentBackground === true || !isFirstScene;
}

const VU_DETAIL_SHADER_FILES = new Set([
  'vu-dot-matrix-spectrum.glsl',
  'vu-micro-bar-bank.glsl',
  'vu-orbit-tick-dial.glsl',
  'vu-pulse-trace.glsl',
  'vu-twin-led-ladder.glsl',
]);

export function shaderSupportsPostFxBypass(shaderFile) {
  const basename = String(shaderFile || '').split('/').pop().toLowerCase();
  return VU_DETAIL_SHADER_FILES.has(basename);
}

export function splitPostFxShaderLayers(layers = []) {
  const affected = [];
  const ignored = [];
  for (const layer of layers) {
    if (layer?.type === 'shader' && layer.seg?.ignorePostFx === true) {
      ignored.push(layer);
    } else {
      affected.push(layer);
    }
  }
  return { affected, ignored };
}

export function renderWebGlLayerPlan(layers, callbacks) {
  const {
    clear,
    renderScene,
    compositeScene,
    renderShader,
  } = callbacks;
  if (layers.length === 0) {
    clear();
    return { rendered: false, sceneLayers: [], activeSceneTrackIds: [], sceneIndex: -1 };
  }

  const webglLayers = layers.filter(layer => layer.type === 'scene' || layer.type === 'shader');
  const sceneLayers = webglLayers.filter(layer => layer.type === 'scene');
  const firstSceneTrackId = sceneLayers[0]?.trackId ?? null;
  const activeSceneTrackIds = [];
  clear();

  for (const layer of webglLayers) {
    if (layer.type === 'scene') {
      activeSceneTrackIds.push(layer.trackId);
      const texture = renderScene(layer, layer.trackId === firstSceneTrackId);
      if (texture) {
        compositeScene(
          texture,
          layer.seg?.opacity ?? 1.0,
          layer.seg?.blendMode ?? 'normal'
        );
      }
    } else {
      renderShader(layer);
    }
  }

  return {
    rendered: true,
    sceneLayers,
    activeSceneTrackIds,
    sceneIndex: sceneLayers[0]?.data?.sceneIndex ?? -1,
  };
}
