import { useState, useEffect } from "react";
import { useParams } from "@modern-js/runtime/router";
import { Outlet } from "@modern-js/runtime/router";
import { isLanguage, type Language } from "@/i18n/resolver";
import { createI18nInstance } from "@/i18n/config";
import { I18nProvider } from "@/i18n/provider";
import type i18next from "i18next";

/**
 * Locale-scoped layout. Validates the `lang` URL segment,
 * creates the i18n instance, and wraps children via <Outlet />.
 *
 * Uses useParams() (not useLoaderData()) to work in both SSR and CSR.
 */
export default function LangLayout(): JSX.Element {
  const params = useParams<{ lang: string }>();
  const lang = params.lang ?? "";
  const locale: Language | null = isLanguage(lang) ? lang : null;

  const [i18n, setI18n] = useState<typeof i18next | null>(null);

  useEffect(() => {
    if (!locale) return;
    let cancelled = false;
    void createI18nInstance({ locale }).then((instance) => {
      if (!cancelled) {
        setI18n(instance);
      }
    });
    return () => {
      cancelled = true;
    };
  }, [locale]);

  if (!locale) {
    return (
      <div>
        <h2>404 — Unknown locale: {lang}</h2>
        <p>Supported: ru, en, es, fr, it, ja, ko, zh, de</p>
      </div>
    );
  }

  if (!i18n) {
    return <div>Loading translations...</div>;
  }

  return (
    <I18nProvider i18n={i18n}>
      <Outlet />
    </I18nProvider>
  );
}
