"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 LoginOverlay_exports = {};
__export(LoginOverlay_exports, {
  default: () => LoginOverlay_default
});
module.exports = __toCommonJS(LoginOverlay_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 LoginOverlay = (0, import_react.forwardRef)(function LoginOverlay2({ isVisible, onDone }, ref) {
  const [step, setStep] = (0, import_react.useState)("checking");
  const [existingUser, setExistingUser] = (0, import_react.useState)(null);
  const [authUrl, setAuthUrl] = (0, import_react.useState)(null);
  const [devicePrompt, setDevicePrompt] = (0, import_react.useState)(null);
  const [status, setStatus] = (0, import_react.useState)("Preparing login...");
  const [error, setError] = (0, import_react.useState)(null);
  const abortControllerRef = (0, import_react.useRef)(null);
  const isActiveRef = (0, import_react.useRef)(false);
  const safeSetStatus = (0, import_react.useCallback)((message) => {
    if (!isActiveRef.current) return;
    setStatus(message);
  }, []);
  const cancelInFlight = (0, import_react.useCallback)(() => {
    abortControllerRef.current?.abort(new Error("Authentication cancelled"));
    abortControllerRef.current = null;
  }, []);
  const runDeviceLogin = (0, import_react.useCallback)(
    async (abortController) => {
      setStep("starting");
      safeSetStatus("Starting device code login...");
      setAuthUrl(null);
      setDevicePrompt(null);
      return (0, import_host.performDeviceCodeLogin)({
        signal: abortController.signal,
        onPrompt: (prompt) => {
          if (!isActiveRef.current || abortController.signal.aborted) {
            return;
          }
          setDevicePrompt(prompt);
          setAuthUrl(prompt.verificationUrlComplete ?? prompt.verificationUrl);
          setStep("waiting");
          safeSetStatus("Open the URL below and approve login.");
        }
      });
    },
    [safeSetStatus]
  );
  const startLogin = (0, import_react.useCallback)(async () => {
    cancelInFlight();
    setError(null);
    setAuthUrl(null);
    setDevicePrompt(null);
    const abortController = new AbortController();
    abortControllerRef.current = abortController;
    try {
      const result = await runDeviceLogin(abortController);
      if (!result || !isActiveRef.current || abortController.signal.aborted) return;
      setStep("finalizing");
      safeSetStatus("Finalizing login...");
      const persisted = await (0, import_host.persistDeviceApiKeyLoginResult)(result);
      if (!isActiveRef.current || abortController.signal.aborted) return;
      onDone({
        outcome: "success",
        email: persisted.email,
        keyId: persisted.keyId,
        hasDextoApiKey: persisted.hasDextoApiKey
      });
    } catch (err) {
      if (abortController.signal.aborted) {
        return;
      }
      setStep("error");
      const errorMessage = err instanceof Error ? err.message : String(err);
      setError(errorMessage);
      safeSetStatus("Login failed");
    } finally {
      abortControllerRef.current = null;
    }
  }, [cancelInFlight, onDone, runDeviceLogin, safeSetStatus]);
  (0, import_react.useEffect)(() => {
    if (!isVisible) return;
    isActiveRef.current = true;
    setStep("checking");
    setExistingUser(null);
    setAuthUrl(null);
    setDevicePrompt(null);
    setStatus("Preparing login...");
    setError(null);
    void (async () => {
      try {
        const auth = await (0, import_host.loadAuth)();
        if (!isActiveRef.current) return;
        if (auth) {
          setExistingUser(auth.email || auth.userId || "user");
          setStep("already-authenticated");
          setStatus("You are already logged in");
          return;
        }
        await startLogin();
      } catch (err) {
        if (!isActiveRef.current) return;
        setStep("error");
        setStatus("Error checking authentication state");
        setError(err instanceof Error ? err.message : String(err));
      }
    })();
    return () => {
      isActiveRef.current = false;
      cancelInFlight();
    };
  }, [cancelInFlight, isVisible, startLogin]);
  (0, import_react.useImperativeHandle)(
    ref,
    () => ({
      handleInput: (_input, key) => {
        if (!isVisible) return false;
        if (key.escape) {
          cancelInFlight();
          onDone({ outcome: step === "already-authenticated" ? "closed" : "cancelled" });
          return true;
        }
        if (step === "already-authenticated" && key.return) {
          void startLogin();
          return true;
        }
        if (step === "error" && key.return) {
          void startLogin();
          return true;
        }
        return true;
      }
    }),
    [cancelInFlight, isVisible, onDone, startLogin, step]
  );
  if (!isVisible) return null;
  const hint = step === "already-authenticated" ? "Enter to login again \u2022 Esc to close" : step === "error" ? "Enter to retry \u2022 Esc to close" : "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: "Login to Dexto" }) }),
        existingUser && step === "already-authenticated" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "green", children: [
          "\u2705 Already logged in as: ",
          existingUser
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "Status: " }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: status })
        ] }),
        devicePrompt && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "Open this URL on any device:" }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellowBright", children: devicePrompt.verificationUrlComplete ?? devicePrompt.verificationUrl }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
            "Code: ",
            devicePrompt.userCode
          ] })
        ] }),
        authUrl && !devicePrompt && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "If your browser didn't open, use this URL:" }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellowBright", children: authUrl })
        ] }),
        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 LoginOverlay_default = LoginOverlay;
