"use client";

import React, { createContext, useContext, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { dictionaries, Language } from "./dictionaries";

interface I18nContextType {
  lang: Language;
  language: Language;
  setLang: (lang: Language) => void;
  setLanguage: (lang: Language) => void;
  t: (typeof dictionaries)["de"];
}

const I18nContext = createContext<I18nContextType | null>(null);

function isLocale(value: unknown): value is Language {
  return value === "de" || value === "en";
}

export function I18nProvider({ children }: { children: React.ReactNode }) {
  // On locale-scoped routes (/de, /en) the URL segment is the single source of
  // truth so that SSR always renders the correct language for SEO.
  const params = useParams();
  const routeLocale = isLocale(params?.locale) ? params.locale : null;

  const [lang, setLangState] = useState<Language>(routeLocale ?? "en");

  useEffect(() => {
    if (routeLocale) {
      setLangState(routeLocale);
      // Persist the choice so non-locale routes (dashboard, auth, …) follow.
      try {
        localStorage.setItem("app_lang", routeLocale);
      } catch {}
      return;
    }

    // Non-locale routes: fall back to the stored user preference.
    try {
      const saved = localStorage.getItem("app_lang") as Language | null;
      setLangState(saved === "de" || saved === "en" ? saved : "en");
    } catch {
      setLangState("en");
    }
  }, [routeLocale]);

  const setLang = (newLang: Language) => {
    setLangState(newLang);
    try {
      localStorage.setItem("app_lang", newLang);
    } catch {}
  };

  const t = dictionaries[lang] || dictionaries.en;

  return (
    <I18nContext.Provider
      value={{
        lang,
        language: lang,
        setLang,
        setLanguage: setLang,
        t,
      }}
    >
      {children}
    </I18nContext.Provider>
  );
}

export function useI18n() {
  const context = useContext(I18nContext);
  if (!context) {
    throw new Error("useI18n must be used within an I18nProvider");
  }
  return context;
}
