'use client';

import { createContext, useContext, useCallback } from 'react';
import { ro } from './locales/ro';
import type { Labels } from './types';

interface I18nContextValue {
  labels: Labels;
  t: (key: string) => string;
}

const I18nContext = createContext<I18nContextValue | null>(null);

interface I18nProviderProps {
  children: React.ReactNode;
}

export function I18nProvider({ children }: I18nProviderProps) {
  const labels = ro;

  const t = useCallback(
    (key: string): string => {
      const [namespace, ...rest] = key.split('.');
      const labelKey = rest.join('.');
      if (!namespace || !labelKey) return key;
      return labels[namespace]?.[labelKey] ?? key;
    },
    [labels]
  );

  return (
    <I18nContext.Provider value={{ labels, t }}>
      {children}
    </I18nContext.Provider>
  );
}

export function useI18n(): I18nContextValue {
  const ctx = useContext(I18nContext);
  if (!ctx) throw new Error('useI18n must be used within I18nProvider');
  return ctx;
}

export function useLabel(key: string): string {
  const { t } = useI18n();
  return t(key);
}
