import { jsx, jsxs } from "react/jsx-runtime";
import {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useRef,
  useState
} from "react";
import { Box, Text } from "ink";
import {
  loadAuth,
  removeAuth,
  removeDextoApiKeyFromEnv,
  isUsingDextoCredits
} from "../../host/index.js";
const LogoutOverlay = forwardRef(function LogoutOverlay2({ isVisible, onDone }, ref) {
  const [step, setStep] = useState("checking");
  const [userLabel, setUserLabel] = useState(null);
  const [usingDextoCredits, setUsingDextoCredits] = useState(false);
  const [error, setError] = useState(null);
  const provisionedApiKeyRef = useRef(null);
  const performLogout = useCallback(async () => {
    setError(null);
    setStep("logging-out");
    try {
      const auth = await loadAuth();
      if (auth?.dextoApiKey && auth.dextoApiKeySource === "provisioned") {
        provisionedApiKeyRef.current = auth.dextoApiKey;
      }
      await removeAuth();
      if (provisionedApiKeyRef.current) {
        await removeDextoApiKeyFromEnv({ expectedValue: provisionedApiKeyRef.current });
      }
      onDone({ outcome: "success", wasUsingDextoCredits: usingDextoCredits });
    } catch (err) {
      setStep("error");
      setError(err instanceof Error ? err.message : String(err));
    }
  }, [onDone, usingDextoCredits]);
  useEffect(() => {
    if (!isVisible) return;
    let cancelled = false;
    provisionedApiKeyRef.current = null;
    setStep("checking");
    setUserLabel(null);
    setUsingDextoCredits(false);
    setError(null);
    void (async () => {
      try {
        const auth = await loadAuth();
        if (cancelled) return;
        if (!auth) {
          setStep("not-authenticated");
          return;
        }
        setUserLabel(auth.email || auth.userId || "user");
      } catch {
        if (!cancelled) {
          setStep("error");
          setError("Failed to load authentication state");
        }
        return;
      }
      try {
        const isUsing = await isUsingDextoCredits();
        if (!cancelled) setUsingDextoCredits(isUsing);
      } catch {
      }
      if (!cancelled) setStep("confirm");
    })();
    return () => {
      cancelled = true;
    };
  }, [isVisible]);
  useImperativeHandle(
    ref,
    () => ({
      handleInput: (_input, key) => {
        if (!isVisible) return false;
        if (key.escape) {
          if (step === "logging-out") return true;
          onDone({ outcome: step === "not-authenticated" ? "closed" : "cancelled" });
          return true;
        }
        if (key.return) {
          if (step === "confirm" || step === "error") {
            void performLogout();
            return true;
          }
        }
        return true;
      }
    }),
    [isVisible, onDone, performLogout, step]
  );
  if (!isVisible) return null;
  const hint = step === "confirm" ? "Enter to logout \u2022 Esc to cancel" : step === "not-authenticated" ? "Esc to close" : step === "error" ? "Enter to retry \u2022 Esc to cancel" : "Esc to cancel";
  return /* @__PURE__ */ jsxs(
    Box,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: "cyan",
      paddingX: 1,
      marginTop: 1,
      children: [
        /* @__PURE__ */ jsx(Box, { marginBottom: 1, children: /* @__PURE__ */ jsx(Text, { bold: true, color: "cyan", children: "Logout" }) }),
        step === "not-authenticated" ? /* @__PURE__ */ jsx(Box, { marginBottom: 1, children: /* @__PURE__ */ jsx(Text, { color: "yellow", children: "\u2139\uFE0F Not currently logged in" }) }) : /* @__PURE__ */ jsxs(Box, { marginBottom: 1, children: [
          /* @__PURE__ */ jsx(Text, { color: "gray", children: "Account: " }),
          /* @__PURE__ */ jsx(Text, { children: userLabel ?? "..." })
        ] }),
        usingDextoCredits && step !== "not-authenticated" && /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ jsx(Text, { color: "yellow", children: "\u26A0\uFE0F You are configured to use Dexto Nova credits (provider: Dexto Nova)." }),
          /* @__PURE__ */ jsx(Text, { color: "gray", dimColor: true, children: "After logout, you will need to run `/login` to authenticate again, or `dexto setup` to configure a different provider." })
        ] }),
        step === "logging-out" && /* @__PURE__ */ jsx(Box, { marginBottom: 1, children: /* @__PURE__ */ jsx(Text, { color: "gray", children: "Logging out..." }) }),
        error && /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ jsxs(Text, { color: "red", children: [
          "Error: ",
          error
        ] }) }),
        /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { color: "gray", dimColor: true, children: hint }) })
      ]
    }
  );
});
var LogoutOverlay_default = LogoutOverlay;
export {
  LogoutOverlay_default as default
};
