const MODE_REQUEST_TYPES = Object.freeze({
  media: ['images', 'videos'],
  postfx: ['postfx'],
  shader: ['shaders'],
  audio: ['audio'],
  scenes: ['scenes'],
  '3d': ['3d'],
  lut: ['luts'],
});

const MODE_ASSET_TYPES = Object.freeze({
  postfx: 'shader',
  shader: 'shader',
  audio: 'audio',
  scenes: 'scene',
  '3d': '3d',
  lut: 'lut',
});

export function assetRequestTypes(mode) {
  return MODE_REQUEST_TYPES[mode] ? [...MODE_REQUEST_TYPES[mode]] : [];
}

export function normalizeAssetCatalog(mode, catalogs) {
  const assets = catalogs.flatMap(catalog => catalog?.assets || []).map(asset => ({
    ...asset,
    assetType: mode === 'media'
      ? (/\.(mp4|webm)$/i.test(asset.name) ? 'video' : 'image')
      : MODE_ASSET_TYPES[mode],
  }));
  return assets
    .filter(asset => mode !== 'scenes' || !asset.name.startsWith('wc_'))
    .sort((left, right) => (right.mtime || 0) - (left.mtime || 0));
}

export function filterAssetCatalog(assets, mediaFilter = 'all', searchTerms = []) {
  let filtered = assets;
  if (mediaFilter === 'images') {
    filtered = filtered.filter(asset => asset.assetType === 'image');
  } else if (mediaFilter === 'videos') {
    filtered = filtered.filter(asset => asset.assetType === 'video');
  }
  for (const term of searchTerms.map(value => value.trim().toLowerCase()).filter(Boolean)) {
    filtered = filtered.filter(asset => asset.name.toLowerCase().includes(term));
  }
  return filtered;
}
