import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState
} from "react";
import { Box, Text } from "ink";
import { BaseSelector } from "../base/BaseSelector.js";
import { buildDextoBillingUrl, openDextoBillingPage } from "../../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 = forwardRef(function InsufficientCreditsOverlay2({ isVisible, initialBalanceUsd, onResolved, onClose }, ref) {
  const selectorRef = useRef(null);
  const isActiveRef = useRef(false);
  const [step, setStep] = useState("select");
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [balanceUsd, setBalanceUsd] = useState(initialBalanceUsd);
  const [openedBillingTarget, setOpenedBillingTarget] = useState(null);
  const [statusMessage, setStatusMessage] = useState(
    "Choose a top-up option. Dexto will open billing in your browser."
  );
  const [errorMessage, setErrorMessage] = useState(null);
  const [loadingMessage, setLoadingMessage] = useState("Working...");
  const [isLoading, setIsLoading] = useState(false);
  const options = useMemo(() => {
    return step === "select" ? TOP_UP_OPTIONS : WAITING_OPTIONS;
  }, [step]);
  const selectorTitle = step === "select" ? "Billing Options" : "Next Step";
  const resetToSelection = 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...");
  }, []);
  useEffect(() => {
    if (!isVisible) {
      isActiveRef.current = false;
      return;
    }
    isActiveRef.current = true;
    setBalanceUsd(initialBalanceUsd);
    resetToSelection();
    return () => {
      isActiveRef.current = false;
    };
  }, [initialBalanceUsd, isVisible, resetToSelection]);
  const openBillingTarget = useCallback(
    async (options2) => {
      setErrorMessage(null);
      setIsLoading(true);
      setLoadingMessage(options2.loadingMessage);
      try {
        await 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 = 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 = useCallback(
    async (creditsUsd) => {
      const billingUrl = 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 = useCallback(async () => {
    setErrorMessage(null);
    setIsLoading(true);
    setLoadingMessage("Opening billing page...");
    try {
      await openDextoBillingPage({ url: openedBillingTarget ?? void 0 });
    } catch (error) {
      if (!isActiveRef.current) {
        return;
      }
      setErrorMessage(getErrorMessage(error));
    } finally {
      if (isActiveRef.current) {
        setIsLoading(false);
      }
    }
  }, [openedBillingTarget]);
  const handleSelect = 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 = useCallback((option, isSelected) => {
    return /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(Text, { color: isSelected ? "yellow" : "gray", bold: isSelected, children: option.label }),
      /* @__PURE__ */ jsxs(Text, { color: isSelected ? "white" : "gray", children: [
        " - ",
        option.description
      ] })
    ] });
  }, []);
  useImperativeHandle(
    ref,
    () => ({
      handleInput: (input, key) => {
        if (!isVisible) {
          return false;
        }
        return selectorRef.current?.handleInput(input, key) ?? false;
      }
    }),
    [isVisible]
  );
  if (!isVisible) {
    return null;
  }
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
    /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { color: "yellow", bold: true, children: "Out of Dexto Nova credits" }) }),
    /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginTop: 1, children: [
      /* @__PURE__ */ jsx(Text, { color: "gray", children: "This request stopped because your Dexto Nova balance ran out." }),
      formatBalance(balanceUsd) && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
        "Current balance: ",
        formatBalance(balanceUsd)
      ] })
    ] }),
    /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginTop: 1, children: [
      /* @__PURE__ */ jsx(Text, { children: statusMessage }),
      errorMessage && /* @__PURE__ */ jsx(Text, { color: "red", children: errorMessage })
    ] }),
    /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(
      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;
export {
  InsufficientCreditsOverlay_default as default
};
