'use client';

import React, { createContext, useContext, useState, useEffect } from 'react';
import { en } from '../lib/i18n/en';
import { ar } from '../lib/i18n/ar';
import type { Translations } from '../lib/i18n/en';

type Language = 'en' | 'ar';

interface LanguageContextType {
  language: Language;
  t: Translations;
  toggleLanguage: () => void;
  isRTL: boolean;
}

const LanguageContext = createContext<LanguageContextType>({
  language: 'en',
  t: en,
  toggleLanguage: () => {},
  isRTL: false,
});

export function LanguageProvider({ children }: { children: React.ReactNode }) {
  const [language, setLanguage] = useState<Language>('en');

  useEffect(() => {
    const saved = localStorage.getItem('ftp-lang') as Language;
    if (saved === 'ar' || saved === 'en') {
      setLanguage(saved);
    }
  }, []);

  useEffect(() => {
    const html = document.documentElement;
    if (language === 'ar') {
      html.setAttribute('dir', 'rtl');
      html.setAttribute('lang', 'ar');
    } else {
      html.setAttribute('dir', 'ltr');
      html.setAttribute('lang', 'en');
    }
    localStorage.setItem('ftp-lang', language);
  }, [language]);

  const toggleLanguage = () => {
    setLanguage(prev => prev === 'en' ? 'ar' : 'en');
  };

  const t = language === 'ar' ? ar : en;
  const isRTL = language === 'ar';

  return (
    <LanguageContext.Provider value={{ language, t, toggleLanguage, isRTL }}>
      {children}
    </LanguageContext.Provider>
  );
}

export const useLanguage = () => useContext(LanguageContext);
