'use client';

import { createContext, type ReactNode } from 'react';

import { MediaItem } from '@/shared/types/media.type';

export type MediaMap = Record<string, MediaItem>;

type MediaControlContextType = {
  m: (key: string) => string | null;
};

export const MediaControlContext = createContext<
  MediaControlContextType | undefined
>(undefined);

export function MediaControlProvider({
  children,
  mediaItems,
}: {
  children: ReactNode;
  mediaItems?: MediaItem[];
}) {
  const mediaMap = mediaItems?.reduce((pr, cr) => {
    pr[cr.key] = cr;
    return pr;
  }, {} as MediaMap);

  const getMedia = (key: string): string | null => {
    if (mediaMap?.[key]) {
      return mediaMap[key].photo;
    }
    console.warn(`Media key not found: ${key}`);
    return null;
  };

  return (
    <MediaControlContext.Provider value={{ m: getMedia }}>
      {children}
    </MediaControlContext.Provider>
  );
}
