import { Navigate, useLocation } from "react-router-dom";
import { useI18n } from "../i18n/I18nContext";
import { useAuth } from "./AuthContext";

export function RequireAuth({ children }: { children: React.ReactNode }) {
  const { member, loading } = useAuth();
  const location = useLocation();
  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 state={{ from: location.pathname + location.search }} />;
  }

  // 未驗證信箱：擋下所有 /app，導向驗證頁
  if (!member.email_verified) {
    return (
      <Navigate
        to="/verify-email"
        replace
        state={{ from: location.pathname + location.search }}
      />
    );
  }

  return children;
}
