import { useCallback } from 'react';
import { useTranslation } from './useTranslation';
import { supportedLanguages } from '@/lib/i18n/config';

export type MeasurementSystem = 'metric' | 'imperial';

/**
 * Custom hook for managing locale and measurement preferences
 */
export function useLocale() {
  const { i18n, language, changeLanguage } = useTranslation();

  const setLanguage = useCallback(
    async (lang: string) => {
      await changeLanguage(lang);
      localStorage.setItem('preferred-language', lang);
    },
    [changeLanguage]
  );

  const getCurrentLanguage = useCallback(() => {
    return supportedLanguages.find((lang) => lang.code === language) || supportedLanguages[0];
  }, [language]);

  const getMeasurementSystem = useCallback((): MeasurementSystem => {
    const stored = localStorage.getItem('measurement-system');
    return (stored as MeasurementSystem) || 'metric';
  }, []);

  const setMeasurementSystem = useCallback((system: MeasurementSystem) => {
    localStorage.setItem('measurement-system', system);
    // Trigger a custom event so other components can react to the change
    window.dispatchEvent(
      new CustomEvent('measurement-system-changed', { detail: system })
    );
  }, []);

  return {
    language,
    setLanguage,
    currentLanguage: getCurrentLanguage(),
    supportedLanguages,
    measurementSystem: getMeasurementSystem(),
    setMeasurementSystem,
  };
}
