"use client";

import { createContext, useContext, useEffect, useMemo, useState } from "react";
import {
  Locale,
  MessageKey,
  resolveLocale,
  t as translate,
} from "../../lib/i18n";

type I18nContextValue = {
  locale: Locale;
  setLocale: (locale: Locale) => void;
  t: (key: MessageKey, vars?: Record<string, string | number>) => string;
};

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

export function I18nProvider({ children }: { children: React.ReactNode }) {
  const [locale, setLocale] = useState<Locale>(() => {
    if (typeof window === "undefined") return "en";
    const stored = localStorage.getItem("locale");
    if (stored === "fi" || stored === "en" || stored === "sv")
      return stored as Locale;
    return resolveLocale({
      cookieLocale: null,
      acceptLanguage: navigator.language ?? navigator.languages?.[0] ?? null,
    });
  });

  useEffect(() => {
    localStorage.setItem("locale", locale);
    document.cookie = `locale=${locale}; path=/; max-age=${60 * 60 * 24 * 365};`;
  }, [locale]);

  const value: I18nContextValue = useMemo(
    () => ({
      locale,
      setLocale,
      t: (key: MessageKey, vars?: Record<string, string | number>) =>
        translate(locale, key, vars) as string,
    }),
    [locale],
  );

  return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
}

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