'use client';
import React, { createContext, useContext, useState, useEffect } from 'react';

type Language = 'ar' | 'en';

interface LanguageContextType {
  language: Language;
  toggleLanguage: () => void;
  t: (ar: string, en: string) => string;
}

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

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

  useEffect(() => {
    try {
      const stored = window.localStorage.getItem('aau_language');
      if (stored === 'ar' || stored === 'en') {
        setLanguage(stored);
      }
    } catch {
      // no-op: localStorage might be unavailable in strict browser modes
    }
  }, []);

  useEffect(() => {
    document.documentElement.dir = language === 'ar' ? 'rtl' : 'ltr';
    document.documentElement.lang = language;
    try {
      window.localStorage.setItem('aau_language', language);
    } catch {
      // no-op: localStorage might be unavailable in strict browser modes
    }
  }, [language]);

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

  const normalizeSpaces = (value: string) => String(value || '').replace(/\s+/g, ' ').trim();

  const t = (ar: string, en: string) => {
    const arText = normalizeSpaces(ar);
    const enText = normalizeSpaces(en);

    if (language === 'ar') {
      return arText || enText;
    }
    return enText || arText;
  };

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

export const useLanguage = () => {
  const context = useContext(LanguageContext);
  // Return a safe fallback if used outside provider (mostly for SSR/Testing)
  if (!context) {
    return {
      language: 'ar' as Language,
      toggleLanguage: () => { },
      t: (ar: string, en: string) => ar
    };
  }
  return context;
};
