import { useEffect, useState } from "react";
import { LogoAnimation } from "@/components/portal/LogoAnimation";

/**
 * Polls /version.json and reloads the app when a new build is detected.
 * Shows a white-background loading animation while reloading.
 */
export function AutoUpdate() {
  const [updating, setUpdating] = useState(false);

  useEffect(() => {
    if (typeof window === "undefined") return;

    let current: string | null = null;
    let timer: number | undefined;
    let reloading = false;

    const triggerReload = () => {
      if (reloading) return;
      reloading = true;
      setUpdating(true);
      // Give the loader a moment to paint, then hard reload
      window.setTimeout(() => window.location.reload(), 1500);
    };

    const check = async () => {
      try {
        const res = await fetch("/version.json", { cache: "no-store" });
        if (!res.ok) return;
        const data = (await res.json()) as { version?: string };
        const v = data?.version;
        if (!v) return;
        if (current === null) {
          current = v;
          return;
        }
        if (v !== current) triggerReload();
      } catch {
        // ignore network errors
      }
    };

    const initial = window.setTimeout(check, 3000);
    timer = window.setInterval(check, 60_000);

    const onVisible = () => {
      if (document.visibilityState === "visible") check();
    };
    document.addEventListener("visibilitychange", onVisible);
    window.addEventListener("focus", check);

    return () => {
      window.clearTimeout(initial);
      if (timer) window.clearInterval(timer);
      document.removeEventListener("visibilitychange", onVisible);
      window.removeEventListener("focus", check);
    };
  }, []);

  if (!updating) return null;
  return (
    <div className="fixed inset-0 z-[9999] bg-white">
      <LogoAnimation duration={4000} />
    </div>
  );
}
