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, unreachable, reload } = useAuth();
  const location = useLocation();
  const { t } = useI18n();

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

  // 連不上後端時登入狀態是未知的，不是已登出。踢回登入頁會讓使用者以為 session 掉了，
  // 而且重新登入也一樣會失敗，所以這裡給重試而不是轉址。
  if (!member && unreachable) {
    return (
      <div className="hb-login">
        <p className="text-muted">{t("auth.unreachable")}</p>
        <button type="button" className="hb-btn" onClick={() => void reload()}>
          {t("common.retry")}
        </button>
      </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;
}
