// Landing for a region-scoped surface without a region: hop to the fleet's
// top-cost region (the overview's sort order — both /insight and /observe
// default there); the in-page switcher handles further hops. No snapshots
// yet → Empty instead of a redirect loop.

"use client";

import { useCallback, useState } from "react";
import { useRouter } from "next/navigation";
import { fetchOverview } from "@/lib/api-client";
import { usePolling } from "@/lib/use-polling";
import { Empty } from "@/components/ui/Empty";
import { ErrorBox } from "@/components/ui/ErrorBox";
import { Loading } from "@/components/ui/Loading";

type Phase = { kind: "loading" } | { kind: "empty" } | { kind: "error"; message: string };

export function RegionLanding(props: { basePath: string; label: string }) {
  const router = useRouter();
  const [phase, setPhase] = useState<Phase>({ kind: "loading" });

  const load = useCallback(
    async (isCurrent: () => boolean) => {
      setPhase({ kind: "loading" });
      try {
        const ov = await fetchOverview();
        if (!isCurrent()) return;
        const first = ov.regions[0]?.regionKey;
        if (first) {
          router.replace(`${props.basePath}/${first}`);
        } else {
          setPhase({ kind: "empty" });
        }
      } catch (e) {
        if (!isCurrent()) return;
        setPhase({ kind: "error", message: e instanceof Error ? e.message : String(e) });
      }
    },
    [router, props.basePath],
  );

  const { refresh } = usePolling(load);

  if (phase.kind === "error") {
    return <ErrorBox message={phase.message} onRetry={() => void refresh()} />;
  }
  if (phase.kind === "empty") {
    return <Empty>No regions yet — run an analysis first.</Empty>;
  }
  return <Loading label={`loading ${props.label}…`} />;
}
