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

const I18nContext = createContext(null);

export function I18nProvider({ children }) {
	const [locale, setLocale] = useState("ro");
	const [translations, setTranslations] = useState({});
	const [hydrated, setHydrated] = useState(false);

	useEffect(() => {
		const saved = localStorage.getItem("locale");
		if (saved === "en" || saved === "ro" || saved === "it" || saved === "fr" || saved === "de") {
			setLocale(saved);
          }
		setHydrated(true);
	}, []);

	useEffect(() => {
		if (!hydrated) return;

		const loadTranslations = async () => {
			try {
				const res = await fetch(`/locales/${locale}/common.json`);
				const data = await res.json();
				setTranslations(data);
			} catch (e) {
				console.error("Eroare la încărcarea traducerilor:", e);
			}
		};

		loadTranslations();
	}, [locale, hydrated]);

	const changeLocale = (lang) => {
		setLocale(lang);
		localStorage.setItem("locale", lang);
	};

	const t = (key) => translations?.[key] ?? key;

	return <I18nContext.Provider value={{ t, locale, setLocale: changeLocale }}>{children}</I18nContext.Provider>;
}

export function useT() {
	const ctx = useContext(I18nContext);
	if (!ctx) return { t: (key) => key, locale: "ro", setLocale: () => {} };
	return ctx;
}

export function getCategoryVariable (category) {
     const { t } = useT(); 

     if(t("variable_categorii") === 'name') {
          return category.name; 
     }

     if(t("variable_categorii") === 'name_en') {
          return category.name_en; 
     }

     if(t("variable_categorii") === 'name_it') {
          return category.name_it; 
     }

     if(t("variable_categorii") === 'name_fr') {
          return category.name_fr; 
     }

     if(t("variable_categorii") === 'name_de') {
          return category.name_de; 
     }

     return category.name; 
};

export function getProductLanguageDirect(product, t) {

     if(t("variable_categorii") === 'name') {
          return product.name; 
     }

     if(t("variable_categorii") === 'name_en') {
          return product.name_en; 
     }

     if(t("variable_categorii") === 'name_it') {
          return product.name_it; 
     }

     if(t("variable_categorii") === 'name_fr') {
          return product.name_fr; 
     }

     if(t("variable_categorii") === 'name_de') {
          return product.name_de; 
     }
}

export function getProductLanguage (product) {
     const { t } = useT(); 

     if(t("variable_categorii") === 'name') {
          return product.name; 
     }

     if(t("variable_categorii") === 'name_en') {
          return product.name_en; 
     }

     if(t("variable_categorii") === 'name_it') {
          return product.name_it; 
     }

     if(t("variable_categorii") === 'name_fr') {
          return product.name_fr; 
     }

     if(t("variable_categorii") === 'name_de') {
          return product.name_de; 
     }
}

export function getProductDescription (product) {
     const { t } = useT(); 

     if(t("variable_categorii") === 'name') {
          return product.desc; 
     }

     if(t("variable_categorii") === 'name_en') {
          return product.desc_en; 
     }

     if(t("variable_categorii") === 'name_it') {
          return product.desc_it; 
     }

     if(t("variable_categorii") === 'name_fr') {
          return product.desc_fr; 
     }

     if(t("variable_categorii") === 'name_de') {
          return product.desc_de; 
     }
}

export function getProductCoin() {
     const { t } = useT(); 

     if(t("variable_categorii") === 'name') {
          return "RON"; 
     }

     if(t("variable_categorii") === 'name_en') {
          return "EUR"; 
     }

     if(t("variable_categorii") === 'name_it') {
          return "EUR"; 
     }    

     if(t("variable_categorii") === 'name_fr') {  
          return "EUR"; 
     }

     if(t("variable_categorii") === 'name_de') {  
          return "EUR"; 
     }    
}

// currency 
let cachedRate = null; 
let cacheTime = null; 
const CACHE_DURATION_MS = 60 * 60 * 1000; 

export async function getRONtoEURRate() {
     const now = Date.now();
     if (cachedRate && cacheTime && now - cacheTime < CACHE_DURATION_MS) {
          return cachedRate;
     }

     const res = await fetch(
          "https://api.frankfurter.dev/v1/latest?base=RON&symbols=EUR"
     );
     const data = await res.json();
     cachedRate = data.rates.EUR;
     cacheTime = now;
     return cachedRate;
}

export function getProductPrice(productPrice) {
     const { t } = useT();
     const [price, setPrice] = useState(productPrice);

     useEffect(() => {
          if (t("variable_categorii") === 'name_en' || t("variable_categorii") === 'name_it' || t("variable_categorii") === 'name_fr' || t("variable_categorii") === 'name_de') {
               getRONtoEURRate().then(rate => {
                    const priceEUR = (Math.ceil(productPrice * rate) - 0.01).toFixed(2);
                    setPrice(priceEUR);
               });
          } else {
               setPrice(productPrice);
          }
     }, [productPrice, t("variable_categorii")]);

     return price;
}