"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 InsufficientCreditsOverlay_exports = {};
__export(InsufficientCreditsOverlay_exports, {
  default: () => InsufficientCreditsOverlay_default
});
module.exports = __toCommonJS(InsufficientCreditsOverlay_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_ink = require("ink");
var import_BaseSelector = require("../base/BaseSelector.js");
var import_host = require("../../host/index.js");
const TOP_UP_OPTIONS = [
  {
    id: "top-up-25",
    label: "Top up $25",
    description: "Recommended quick recharge",
    amountUsd: 25
  },
  {
    id: "top-up-10",
    label: "Top up $10",
    description: "Small top-up",
    amountUsd: 10
  },
  {
    id: "top-up-50",
    label: "Top up $50",
    description: "Larger credit pack",
    amountUsd: 50
  },
  {
    id: "open-billing",
    label: "Open billing page",
    description: "View full billing dashboard"
  }
];
const WAITING_OPTIONS = [
  {
    id: "reopen",
    label: "Open billing page again",
    description: "Return to billing or sign in in your browser"
  },
  {
    id: "different-amount",
    label: "Choose a different amount",
    description: "Open billing with another amount prefilled"
  },
  {
    id: "done",
    label: "Close and retry manually",
    description: "Return to chat once billing is handled"
  }
];
function formatBalance(balanceUsd) {
  if (balanceUsd === null) {
    return null;
  }
  return `$${balanceUsd.toFixed(2)}`;
}
function getErrorMessage(error) {
  return error instanceof Error ? error.message : String(error);
}
const InsufficientCreditsOverlay = (0, import_react.forwardRef)(function InsufficientCreditsOverlay2({ isVisible, initialBalanceUsd, onResolved, onClose }, ref) {
  const selectorRef = (0, import_react.useRef)(null);
  const isActiveRef = (0, import_react.useRef)(false);
  const [step, setStep] = (0, import_react.useState)("select");
  const [selectedIndex, setSelectedIndex] = (0, import_react.useState)(0);
  const [balanceUsd, setBalanceUsd] = (0, import_react.useState)(initialBalanceUsd);
  const [openedBillingTarget, setOpenedBillingTarget] = (0, import_react.useState)(null);
  const [statusMessage, setStatusMessage] = (0, import_react.useState)(
    "Choose a top-up option. Dexto will open billing in your browser."
  );
  const [errorMessage, setErrorMessage] = (0, import_react.useState)(null);
  const [loadingMessage, setLoadingMessage] = (0, import_react.useState)("Working...");
  const [isLoading, setIsLoading] = (0, import_react.useState)(false);
  const options = (0, import_react.useMemo)(() => {
    return step === "select" ? TOP_UP_OPTIONS : WAITING_OPTIONS;
  }, [step]);
  const selectorTitle = step === "select" ? "Billing Options" : "Next Step";
  const resetToSelection = (0, import_react.useCallback)(() => {
    setStep("select");
    setSelectedIndex(0);
    setOpenedBillingTarget(null);
    setErrorMessage(null);
    setStatusMessage("Choose a top-up option. Dexto will open billing in your browser.");
    setIsLoading(false);
    setLoadingMessage("Working...");
  }, []);
  (0, import_react.useEffect)(() => {
    if (!isVisible) {
      isActiveRef.current = false;
      return;
    }
    isActiveRef.current = true;
    setBalanceUsd(initialBalanceUsd);
    resetToSelection();
    return () => {
      isActiveRef.current = false;
    };
  }, [initialBalanceUsd, isVisible, resetToSelection]);
  const openBillingTarget = (0, import_react.useCallback)(
    async (options2) => {
      setErrorMessage(null);
      setIsLoading(true);
      setLoadingMessage(options2.loadingMessage);
      try {
        await (0, import_host.openDextoBillingPage)({ url: options2.url });
        if (!isActiveRef.current) {
          return;
        }
        setOpenedBillingTarget(options2.url ?? null);
        setStep("waiting");
        setSelectedIndex(0);
        setStatusMessage(options2.statusMessage);
      } catch (error) {
        if (!isActiveRef.current) {
          return;
        }
        setOpenedBillingTarget(options2.url ?? null);
        setStep("waiting");
        setSelectedIndex(0);
        setErrorMessage(getErrorMessage(error));
        setStatusMessage("Billing is ready to open again once your browser is available.");
      } finally {
        if (isActiveRef.current) {
          setIsLoading(false);
        }
      }
    },
    []
  );
  const openBillingDashboard = (0, import_react.useCallback)(async () => {
    await openBillingTarget({
      loadingMessage: "Opening billing page...",
      statusMessage: "Billing opened in your browser. If needed, the site will ask you to sign in before you continue. Once payment is complete, close this prompt and retry your request here."
    });
  }, [openBillingTarget]);
  const openPrefilledBilling = (0, import_react.useCallback)(
    async (creditsUsd) => {
      const billingUrl = (0, import_host.buildDextoBillingUrl)({ creditsUsd });
      await openBillingTarget({
        url: billingUrl,
        loadingMessage: `Opening $${creditsUsd} billing page...`,
        statusMessage: `Opened a $${creditsUsd} top-up flow in your browser. If needed, the site will ask you to sign in before you continue. Once payment is complete, close this prompt and retry your request here.`
      });
    },
    [openBillingTarget]
  );
  const reopenBilling = (0, import_react.useCallback)(async () => {
    setErrorMessage(null);
    setIsLoading(true);
    setLoadingMessage("Opening billing page...");
    try {
      await (0, import_host.openDextoBillingPage)({ url: openedBillingTarget ?? void 0 });
    } catch (error) {
      if (!isActiveRef.current) {
        return;
      }
      setErrorMessage(getErrorMessage(error));
    } finally {
      if (isActiveRef.current) {
        setIsLoading(false);
      }
    }
  }, [openedBillingTarget]);
  const handleSelect = (0, import_react.useCallback)(
    (option) => {
      if (typeof option.amountUsd === "number") {
        void openPrefilledBilling(option.amountUsd);
        return;
      }
      switch (option.id) {
        case "open-billing":
          void openBillingDashboard();
          return;
        case "reopen":
          void reopenBilling();
          return;
        case "different-amount":
          resetToSelection();
          return;
        case "done":
          onResolved();
          return;
      }
    },
    [onResolved, openBillingDashboard, openPrefilledBilling, reopenBilling, resetToSelection]
  );
  const formatItem = (0, import_react.useCallback)((option, isSelected) => {
    return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: isSelected ? "yellow" : "gray", bold: isSelected, children: option.label }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: isSelected ? "white" : "gray", children: [
        " - ",
        option.description
      ] })
    ] });
  }, []);
  (0, import_react.useImperativeHandle)(
    ref,
    () => ({
      handleInput: (input, key) => {
        if (!isVisible) {
          return false;
        }
        return selectorRef.current?.handleInput(input, key) ?? false;
      }
    }),
    [isVisible]
  );
  if (!isVisible) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellow", bold: true, children: "Out of Dexto Nova credits" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", marginTop: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "This request stopped because your Dexto Nova balance ran out." }),
      formatBalance(balanceUsd) && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "gray", children: [
        "Current balance: ",
        formatBalance(balanceUsd)
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", marginTop: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: statusMessage }),
      errorMessage && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "red", children: errorMessage })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_BaseSelector.BaseSelector,
      {
        ref: selectorRef,
        items: options,
        isVisible: true,
        isLoading,
        selectedIndex,
        onSelectIndex: setSelectedIndex,
        onSelect: handleSelect,
        onClose,
        formatItem,
        title: selectorTitle,
        borderColor: "yellow",
        maxVisibleItems: 6,
        loadingMessage,
        emptyMessage: "No billing actions available"
      }
    ) })
  ] });
});
var InsufficientCreditsOverlay_default = InsufficientCreditsOverlay;
