import * as api from "@client/api/client";
import { Loader2 } from "lucide-react";
import React from "react";

type Phase = "loading" | "prompt" | "ready";

/**
 * Delays mounting children until Basic Auth is satisfied (or disabled), so hooks do not
 * fire unauthenticated writes first. The login dialog is shown during the `prompt` phase.
 */
export const BasicAuthAppGate: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const [phase, setPhase] = React.useState<Phase>("loading");

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

    void (async () => {
      try {
        const status = await api.getBasicAuthBasicStatus();
        if (cancelled) return;
        if (!status.basicAuthEnabled) {
          setPhase("ready");
          return;
        }

        const restored = await api.tryBootstrapBasicAuthFromSessionOnly(status);
        if (cancelled) return;
        if (restored) {
          setPhase("ready");
          return;
        }

        setPhase("prompt");
        await api.bootstrapBasicAuthWithPromptOnly();
        if (cancelled) return;
        setPhase("ready");
      } catch {
        if (!cancelled) setPhase("ready");
      }
    })();

    return () => {
      cancelled = true;
    };
  }, []);

  if (phase === "loading") {
    return (
      <div className="fixed inset-0 z-40 flex flex-col items-center justify-center gap-3 bg-background/95 backdrop-blur-sm">
        <Loader2
          className="h-8 w-8 animate-spin text-muted-foreground"
          aria-hidden
        />
        <p className="text-sm text-muted-foreground">
          Checking authentication…
        </p>
      </div>
    );
  }

  if (phase === "prompt") {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center gap-2 bg-background px-4 text-center text-sm text-muted-foreground">
        <p className="font-medium text-foreground">Sign in</p>
        <p>Use the dialog above to enter your username and password.</p>
        <p className="max-w-sm text-xs text-muted-foreground">
          After you sign in, open the menu (☰) → Account → &quot;Sign out /
          switch user&quot; to log in as someone else. Job lists are separate
          per login.
        </p>
      </div>
    );
  }

  return <>{children}</>;
};
