"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var LogoutOverlay_exports = {};
__export(LogoutOverlay_exports, {
  default: () => LogoutOverlay_default
});
module.exports = __toCommonJS(LogoutOverlay_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_ink = require("ink");
var import_host = require("../../host/index.js");
const LogoutOverlay = (0, import_react.forwardRef)(function LogoutOverlay2({ isVisible, onDone }, ref) {
  const [step, setStep] = (0, import_react.useState)("checking");
  const [userLabel, setUserLabel] = (0, import_react.useState)(null);
  const [usingDextoCredits, setUsingDextoCredits] = (0, import_react.useState)(false);
  const [error, setError] = (0, import_react.useState)(null);
  const provisionedApiKeyRef = (0, import_react.useRef)(null);
  const performLogout = (0, import_react.useCallback)(async () => {
    setError(null);
    setStep("logging-out");
    try {
      const auth = await (0, import_host.loadAuth)();
      if (auth?.dextoApiKey && auth.dextoApiKeySource === "provisioned") {
        provisionedApiKeyRef.current = auth.dextoApiKey;
      }
      await (0, import_host.removeAuth)();
      if (provisionedApiKeyRef.current) {
        await (0, import_host.removeDextoApiKeyFromEnv)({ expectedValue: provisionedApiKeyRef.current });
      }
      onDone({ outcome: "success", wasUsingDextoCredits: usingDextoCredits });
    } catch (err) {
      setStep("error");
      setError(err instanceof Error ? err.message : String(err));
    }
  }, [onDone, usingDextoCredits]);
  (0, import_react.useEffect)(() => {
    if (!isVisible) return;
    let cancelled = false;
    provisionedApiKeyRef.current = null;
    setStep("checking");
    setUserLabel(null);
    setUsingDextoCredits(false);
    setError(null);
    void (async () => {
      try {
        const auth = await (0, import_host.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 (0, import_host.isUsingDextoCredits)();
        if (!cancelled) setUsingDextoCredits(isUsing);
      } catch {
      }
      if (!cancelled) setStep("confirm");
    })();
    return () => {
      cancelled = true;
    };
  }, [isVisible]);
  (0, import_react.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__ */ (0, import_jsx_runtime.jsxs)(
    import_ink.Box,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: "cyan",
      paddingX: 1,
      marginTop: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { bold: true, color: "cyan", children: "Logout" }) }),
        step === "not-authenticated" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellow", children: "\u2139\uFE0F Not currently logged in" }) }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "Account: " }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: userLabel ?? "..." })
        ] }),
        usingDextoCredits && step !== "not-authenticated" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellow", children: "\u26A0\uFE0F You are configured to use Dexto Nova credits (provider: Dexto Nova)." }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.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__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "Logging out..." }) }),
        error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "red", children: [
          "Error: ",
          error
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", dimColor: true, children: hint }) })
      ]
    }
  );
});
var LogoutOverlay_default = LogoutOverlay;
