'use client';

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { isRtlLanguage, type Language } from '@/domain/language/entities';
import {
  persistLanguage,
  resolveInitialLanguage,
} from '@/application/language/language-use-cases';
import { container } from '@/infrastructure/di/container';

interface LanguageContextType {
  language: Language;
  setLanguage: (lang: Language) => void;
  isRtl: boolean;
}

const LanguageContext = createContext<LanguageContextType | undefined>(undefined);

export function LanguageProvider({ children }: { children: ReactNode }) {
  const [language, setLanguageState] = useState<Language>('sv');

  useEffect(() => {
    setLanguageState(resolveInitialLanguage(container.languageRepository));
  }, []);

  useEffect(() => {
    const root = document.documentElement;
    root.lang = language;
    root.dir = isRtlLanguage(language) ? 'rtl' : 'ltr';
    root.dataset.locale = language;
  }, [language]);

  const setLanguage = (lang: Language) => {
    setLanguageState(lang);
    persistLanguage(container.languageRepository, lang);
  };

  return (
    <LanguageContext.Provider
      value={{ language, setLanguage, isRtl: isRtlLanguage(language) }}
    >
      {children}
    </LanguageContext.Provider>
  );
}

export function useLanguage() {
  const context = useContext(LanguageContext);
  if (context === undefined) {
    throw new Error('useLanguage must be used within a LanguageProvider');
  }
  return context;
}