"use client";

import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import { BACKEND } from "./config";

export default function AuthGuard({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const [state, setState] = useState<"loading" | "allowed" | "unauthorized" | "backend_error">("loading");

  useEffect(() => {
    if (pathname === "/login") {
      setState("allowed");
      return;
    }
    let cancelled = false;
    setState("loading");
    fetch(`${BACKEND}/auth/check`, { credentials: "include" })
      .then((res) => {
        if (cancelled) return;
        if (res.status === 401) {
          setState("unauthorized");
          window.location.replace("/login");
          return;
        }
        if (!res.ok) {
          setState("backend_error");
          return;
        }
        res.json().then((data) => {
          if (cancelled) return;
          // Backend may have auth disabled (auth_enabled: false); allow access.
          setState("allowed");
        }).catch(() => setState("backend_error"));
      })
      .catch(() => {
        if (!cancelled) setState("backend_error");
      });
    return () => {
      cancelled = true;
    };
  }, [pathname]);

  if (pathname === "/login") return <>{children}</>;
  if (state === "loading") {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center">
        <div className="text-white/60">Checking authentication…</div>
      </div>
    );
  }
  if (state === "backend_error") {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center">
        <div className="text-white/80 text-center max-w-md px-4">
          <p className="font-medium">Cannot reach backend.</p>
          <p className="text-white/60 text-sm mt-2">Check that the API is running and the URL is correct. You cannot use the app until the backend responds.</p>
        </div>
      </div>
    );
  }
  if (state === "unauthorized") {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center">
        <div className="text-white/60">Redirecting to login…</div>
      </div>
    );
  }
  return <>{children}</>;
}
