"use client";

import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import Loader from "@/components/ui/Loader";
import { getApiErrorMessage } from "@/lib/api/errors";
import { useLanguageStore } from "@/store/languageStore";

/**
 * Sign-in, loading and error, before the account form is worth rendering.
 *
 * Both records have to be in hand: the form merges them into one set of initial
 * values, so rendering on one would show empty fields that then jump.
 */
export default function AccountFormGate({
  authToken,
  isLoading,
  error,
  children,
}: {
  authToken?: string | null;
  isLoading: boolean;
  error: unknown;
  children: ReactNode;
}) {
  const { t } = useTranslation();
  const language = useLanguageStore((s) => s.language);

  if (!authToken) return <div>{t("COMMON.PLEASE_LOGIN")}</div>;
  if (isLoading) return <Loader />;
  if (error) {
    /* The API's own localized message, never `String(error)` — that printed
       «[object Object]» or an axios stack line on the account page. */
    return (
      <div role="alert" className="p-8 text-center">
        {getApiErrorMessage(error, language, t("COMMON.ERROR"))}
      </div>
    );
  }
  return <>{children}</>;
}
