import { Navigate } from "react-router-dom";
import { useI18n } from "../i18n/I18nContext";
import { can, Permission } from "../lib/permissions";
import { useAuth } from "./AuthContext";

/**
 * 需 permission.AdminAccess（admin 角色預設授予）。
 * 無此能力 → 導向 /app/today，不顯示「無權限」文案。
 */
export function RequireAdmin({ children }: { children: React.ReactNode }) {
  const { member, loading } = useAuth();
  const { t } = useI18n();

  if (loading) {
    return (
      <div className="hb-login">
        <p className="text-muted">{t("common.loading")}</p>
      </div>
    );
  }

  if (!member) {
    return <Navigate to="/login" replace />;
  }

  if (!can(member.roles, Permission.AdminAccess)) {
    return <Navigate to="/app/today" replace />;
  }

  return children;
}
