"use client";

import { useRouter } from "next/navigation";
import { useEffect, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";

import { readToken } from "@/stores/admin-token";

type ShellAuthGateProps = {
  children: ReactNode;
};

/**
 * Shell route guard. Reads the auth token from localStorage on the client and
 * redirects to the login page when no token is present.
 */
export function ShellAuthGate({ children }: ShellAuthGateProps) {
  const { t } = useTranslation("common");
  const router = useRouter();
  const [allowed, setAllowed] = useState(false);

  useEffect(() => {
    const token = readToken();
    if (!token) {
      router.replace("/admin/login");
      return;
    }
    queueMicrotask(() => {
      setAllowed(true);
    });
  }, [router]);

  if (!allowed) {
    return (
      <div className="flex min-h-[50vh] w-full flex-1 items-center justify-center text-sm text-muted-foreground">
        {t("auth.checking", { defaultValue: "Checking sign-in status…" })}
      </div>
    );
  }

  return children;
}
