"use client";

import { usePathname, useRouter } from "next/navigation";
import { useEffect } from "react";
import { session, isBlocked, isBlockedStatus } from "@/lib/auth/session";
import { usersApi } from "@/lib/api/users";

const BLOCKED_PATH = "/blocked";

/**
 * Mounted globally in the root layout. Two layers of enforcement:
 *
 *  1. A cheap, no-network check on every navigation — an already-known-blocked
 *     session is bounced immediately (no flash while the network call runs).
 *  2. A live server re-check on load and whenever the tab regains focus —
 *     catches a *mid-session* block (admin blocks the account while the user is
 *     already logged in). On a confirmed block we log the user out and redirect.
 */
export default function BlockGuard() {
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    if (pathname === BLOCKED_PATH) return;
    if (isBlocked(session.get())) {
      router.replace(BLOCKED_PATH);
    }
  }, [pathname, router]);

  useEffect(() => {
    let cancelled = false;

    const verifyStatus = async () => {
      const email = session.getEmail();
      if (!email) return;
      try {
        const user = await usersApi.getCurrent(email);
        if (cancelled || !user) return;
        if (isBlockedStatus(user.Status)) {
          session.clear();
          router.replace(BLOCKED_PATH);
        }
      } catch {
        // Network/lookup failure — leave the user where they are rather than
        // locking out a legitimate user over a transient error.
      }
    };

    verifyStatus();

    const onVisible = () => {
      if (document.visibilityState === "visible") verifyStatus();
    };
    document.addEventListener("visibilitychange", onVisible);
    return () => {
      cancelled = true;
      document.removeEventListener("visibilitychange", onVisible);
    };
  }, [router]);

  return null;
}
