import type { ReactNode } from "react";
import * as stylex from "@stylexjs/stylex";
import InlineError from "@/lib/InlineError";
import type { ConfigStatus } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { useAuthority } from "./authority";
import { styles } from "./styles";

/**
 * Guards a configuration rendering on resolved authority (D6).
 *
 * The two renderings — editable forms and file-mode definition lists — are
 * mutually exclusive answers to a question only the server can settle, so
 * neither is drawn until it has. Pending is a skeleton; a failed status query
 * is an error with a Retry, never a form drawn on a guess.
 *
 * Runtime actions do not pass through here. Pause, update now and reload
 * certificates work under every authority, so their pages render them beside
 * the gate rather than inside it.
 */
export default function AuthorityGate({ children }: { children: (status: ConfigStatus) => ReactNode }) {
	const authority = useAuthority();

	if (authority.state === "pending") {
		return (
			<p role="status" {...stylex.props(styles.pending, shared.pulse)}>
				Checking which configuration source this server obeys…
			</p>
		);
	}

	if (authority.state === "failed") {
		return (
			<div {...stylex.props(styles.blocked)}>
				<p>
					Configuration status unavailable. nxdns cannot say whether a file or the database owns this
					configuration, so nothing here can be edited until it answers.
				</p>
				<InlineError error={authority.error} onRetry={authority.retry} />
			</div>
		);
	}

	return <>{children(authority.status)}</>;
}
