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

import { TextItem } from '@/shared/types/text.types';

export type Translations = Record<string, string>;

// Create context
type TextControlContextType = {
  t: (key: string) => string;
};

export const TextControlContext = createContext<
  TextControlContextType | undefined
>(undefined);

// Create provider

export function TextControlProvider({
  children,
  textItems,
}: {
  children: ReactNode;
  textItems?: TextItem[];
}) {
  const textMap = textItems?.reduce(
    (pr, cr) => {
      pr[cr.key] = cr.value;

      return pr;
    },
    {} as Record<string, string | null>,
  );

  // Translation function for flat structure
  const t = (key: string): string => {
    if (textMap?.[key]) {
      return textMap[key];
    }

    console.warn(`Translation key not found: ${key}`);
    return key;
  };

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