import { createContext, useContext, useMemo, type ReactNode } from 'react';
import type { ScreenshotEvidence } from '@/features/report/types/report';

interface ScreenshotContextValue {
  screenshots: ScreenshotEvidence[];
  getById: (id: string) => ScreenshotEvidence | undefined;
  getByIds: (ids: string[]) => ScreenshotEvidence[];
}

const ScreenshotContext = createContext<ScreenshotContextValue>({
  screenshots: [],
  getById: () => undefined,
  getByIds: () => [],
});

export function ScreenshotProvider({
  screenshots,
  children,
}: {
  screenshots: ScreenshotEvidence[];
  children: ReactNode;
}) {
  const value = useMemo(() => {
    const map = new Map(screenshots.map((s) => [s.id, s]));
    return {
      screenshots,
      getById: (id: string) => map.get(id),
      getByIds: (ids: string[]) => ids.map((id) => map.get(id)).filter(Boolean) as ScreenshotEvidence[],
    };
  }, [screenshots]);

  return (
    <ScreenshotContext.Provider value={value}>
      {children}
    </ScreenshotContext.Provider>
  );
}

export function useScreenshots() {
  return useContext(ScreenshotContext);
}
