export type BackgroundImageOption = {
  id: string;
  url: string;
  label: string;
};

// Preload background assets from public/storage/layouts/backgrounds.
// Vite does not process the public directory, so we try a glob (for cases where assets are in src)
// and fall back to known public URLs.
const backgroundImports: Record<string, string> = {
  ...import.meta.glob('../../../../../public/storage/layouts/backgrounds/*.{jpg,jpeg,png,webp,avif}', {
    eager: true,
    as: 'url',
  }),
  ...import.meta.glob('/storage/layouts/backgrounds/*.{jpg,jpeg,png,webp,avif}', {
    eager: true,
    as: 'url',
  }),
};

const fallbackFiles = ['bg-blue-floral.png', 'bg-goldframe.png', 'gr-green-floral.png'];

const importedBackgrounds: BackgroundImageOption[] = Object.entries(backgroundImports).map(([path, url]) => {
  const filename = path.split('/').pop() ?? path;
  const id = filename.replace(/\.[^.]+$/, '');
  return { id, url: url as string, label: filename };
});

const fallbackBackgrounds: BackgroundImageOption[] = fallbackFiles.map((filename) => ({
  id: filename.replace(/\.[^.]+$/, ''),
  url: `/storage/layouts/backgrounds/${filename}`,
  label: filename,
}));

const merged = [...importedBackgrounds, ...fallbackBackgrounds];

export const preloadedBackgrounds: BackgroundImageOption[] = Array.from(
  merged.reduce((map, item) => {
    if (!map.has(item.id)) {
      map.set(item.id, item);
    }
    return map;
  }, new Map<string, BackgroundImageOption>()),
).map(([, value]) => value);
