var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
import { g as script, s as script$1, ad as script$2, d as script$3, ae as script$4, q as script$5, a as script$6, G as script$7 } from "./vendor-primevue-DmDWdkDd.js";
import { a2 as useFirebaseAuthStore, bh as isAbortError, bi as getComfyApiBaseUrl, _ as _sfc_main$2, m as useTelemetry, $ as useExternalLink, o as useDialogService, a1 as useFirebaseAuthActions, z as useCommandStore, l as useSubscription, dm as _sfc_main$3, dn as formatMetronomeCurrency } from "./index-BqxAUePh.js";
import { r as ref, w as watch, ci as axios, bq as defineComponent, E as computed, h as resolveDirective, c as createElementBlock, d as openBlock, j as createBlock, z as createVNode, br as unref, k as withCtx, A as createTextVNode, u as toDisplayString, e as createBaseVNode, q as createCommentVNode, l as withDirectives, s as normalizeClass } from "./vendor-other-DdEHkzYa.js";
import { u as useI18n } from "./vendor-vue-BIRc7P93.js";
import "./vendor-xterm-BF8peZ5_.js";
import "./vendor-three-_gcZkhit.js";
import "./vendor-tiptap-B76LFN34.js";
var EventType = /* @__PURE__ */ ((EventType2) => {
  EventType2["CREDIT_ADDED"] = "credit_added";
  EventType2["ACCOUNT_CREATED"] = "account_created";
  EventType2["API_USAGE_STARTED"] = "api_usage_started";
  EventType2["API_USAGE_COMPLETED"] = "api_usage_completed";
  return EventType2;
})(EventType || {});
const customerApiClient = axios.create({
  baseURL: getComfyApiBaseUrl(),
  headers: {
    "Content-Type": "application/json"
  }
});
const useCustomerEventsService = /* @__PURE__ */ __name(() => {
  const isLoading = ref(false);
  const error = ref(null);
  const { d } = useI18n();
  watch(
    () => getComfyApiBaseUrl(),
    (url) => {
      customerApiClient.defaults.baseURL = url;
    }
  );
  const handleRequestError = /* @__PURE__ */ __name((err, context, routeSpecificErrors) => {
    if (isAbortError(err)) return;
    let message;
    if (!axios.isAxiosError(err)) {
      message = `${context} failed: ${err instanceof Error ? err.message : String(err)}`;
    } else {
      const axiosError = err;
      const status = axiosError.response?.status;
      if (status && routeSpecificErrors?.[status]) {
        message = routeSpecificErrors[status];
      } else {
        message = axiosError.response?.data?.message ?? `${context} failed with status ${status}`;
      }
    }
    error.value = message;
  }, "handleRequestError");
  const executeRequest = /* @__PURE__ */ __name(async (requestCall, options) => {
    const { errorContext, routeSpecificErrors } = options;
    isLoading.value = true;
    error.value = null;
    try {
      const response = await requestCall();
      return response.data;
    } catch (err) {
      handleRequestError(err, errorContext, routeSpecificErrors);
      return null;
    } finally {
      isLoading.value = false;
    }
  }, "executeRequest");
  function formatEventType(eventType) {
    switch (eventType) {
      case "credit_added":
        return "Credits Added";
      case "account_created":
        return "Account Created";
      case "api_usage_completed":
        return "API Usage";
      default:
        return eventType;
    }
  }
  __name(formatEventType, "formatEventType");
  function formatDate(dateString) {
    const date = new Date(dateString);
    return d(date, {
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit"
    });
  }
  __name(formatDate, "formatDate");
  function formatJsonKey(key) {
    return key.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
  }
  __name(formatJsonKey, "formatJsonKey");
  function formatJsonValue(value) {
    if (typeof value === "number") {
      return value.toLocaleString();
    }
    if (typeof value === "string" && value.match(/^\d{4}-\d{2}-\d{2}/)) {
      return new Date(value).toLocaleString();
    }
    return value;
  }
  __name(formatJsonValue, "formatJsonValue");
  function getEventSeverity(eventType) {
    switch (eventType) {
      case "credit_added":
        return "success";
      case "account_created":
        return "info";
      case "api_usage_completed":
        return "warning";
      default:
        return "info";
    }
  }
  __name(getEventSeverity, "getEventSeverity");
  function hasAdditionalInfo(event) {
    const { amount, api_name, model, ...otherParams } = event.params || {};
    return Object.keys(otherParams).length > 0;
  }
  __name(hasAdditionalInfo, "hasAdditionalInfo");
  function getTooltipContent(event) {
    const { ...params } = event.params || {};
    return Object.entries(params).map(([key, value]) => {
      const formattedKey = formatJsonKey(key);
      const formattedValue = formatJsonValue(value);
      return `<strong>${formattedKey}:</strong> ${formattedValue}`;
    }).join("<br>");
  }
  __name(getTooltipContent, "getTooltipContent");
  function formatAmount(amountMicros) {
    if (!amountMicros) return "0.00";
    return (amountMicros / 100).toFixed(2);
  }
  __name(formatAmount, "formatAmount");
  async function getMyEvents({
    page = 1,
    limit = 10
  } = {}) {
    const errorContext = "Fetching customer events";
    const routeSpecificErrors = {
      400: "Invalid input, object invalid",
      404: "Not found"
    };
    const authHeaders = await useFirebaseAuthStore().getAuthHeader();
    if (!authHeaders) {
      error.value = "Authentication header is missing";
      return null;
    }
    const result = await executeRequest(
      () => customerApiClient.get("/customers/events", {
        params: { page, limit },
        headers: authHeaders
      }),
      { errorContext, routeSpecificErrors }
    );
    return result;
  }
  __name(getMyEvents, "getMyEvents");
  return {
    // State
    isLoading,
    error,
    // Methods
    getMyEvents,
    formatEventType,
    getEventSeverity,
    formatAmount,
    hasAdditionalInfo,
    formatDate,
    formatJsonKey,
    formatJsonValue,
    getTooltipContent
  };
}, "useCustomerEventsService");
const _hoisted_1$1 = {
  key: 0,
  class: "flex items-center justify-center p-8"
};
const _hoisted_2$1 = {
  key: 1,
  class: "p-4"
};
const _hoisted_3$1 = { class: "event-details" };
const _hoisted_4$1 = {
  key: 0,
  class: "font-semibold text-green-500"
};
const _hoisted_5$1 = { key: 1 };
const _hoisted_6$1 = {
  key: 2,
  class: "flex flex-col gap-1"
};
const _hoisted_7$1 = { class: "font-semibold" };
const _hoisted_8$1 = { class: "text-sm text-smoke-400" };
const _sfc_main$1 = /* @__PURE__ */ defineComponent({
  __name: "UsageLogsTable",
  setup(__props, { expose: __expose }) {
    const events = ref([]);
    const loading = ref(true);
    const error = ref(null);
    const customerEventService = useCustomerEventsService();
    const pagination = ref({
      page: 1,
      limit: 7,
      total: 0,
      totalPages: 0
    });
    const dataTableFirst = computed(
      () => (pagination.value.page - 1) * pagination.value.limit
    );
    const tooltipContentMap = computed(() => {
      const map = /* @__PURE__ */ new Map();
      events.value.forEach((event) => {
        if (customerEventService.hasAdditionalInfo(event) && event.event_id) {
          map.set(event.event_id, customerEventService.getTooltipContent(event));
        }
      });
      return map;
    });
    const loadEvents = /* @__PURE__ */ __name(async () => {
      loading.value = true;
      error.value = null;
      try {
        const response = await customerEventService.getMyEvents({
          page: pagination.value.page,
          limit: pagination.value.limit
        });
        if (response) {
          if (response.events) {
            events.value = response.events;
          }
          if (response.page) {
            pagination.value.page = response.page;
          }
          if (response.limit) {
            pagination.value.limit = response.limit;
          }
          if (response.total) {
            pagination.value.total = response.total;
          }
          if (response.totalPages) {
            pagination.value.totalPages = response.totalPages;
          }
          useTelemetry()?.checkForCompletedTopup(response.events);
        } else {
          error.value = customerEventService.error.value || "Failed to load events";
        }
      } catch (err) {
        error.value = err instanceof Error ? err.message : "Unknown error";
        console.error("Error loading events:", err);
      } finally {
        loading.value = false;
      }
    }, "loadEvents");
    const onPageChange = /* @__PURE__ */ __name((event) => {
      pagination.value.page = event.page + 1;
      loadEvents().catch((error2) => {
        console.error("Error loading events:", error2);
      });
    }, "onPageChange");
    const refresh = /* @__PURE__ */ __name(async () => {
      pagination.value.page = 1;
      await loadEvents();
    }, "refresh");
    __expose({
      refresh
    });
    return (_ctx, _cache) => {
      const _directive_tooltip = resolveDirective("tooltip");
      return openBlock(), createElementBlock("div", null, [
        loading.value ? (openBlock(), createElementBlock("div", _hoisted_1$1, [
          createVNode(unref(script))
        ])) : error.value ? (openBlock(), createElementBlock("div", _hoisted_2$1, [
          createVNode(unref(script$1), {
            severity: "error",
            closable: false
          }, {
            default: withCtx(() => [
              createTextVNode(toDisplayString(error.value), 1)
            ]),
            _: 1
          })
        ])) : (openBlock(), createBlock(unref(script$2), {
          key: 2,
          value: events.value,
          paginator: true,
          rows: pagination.value.limit,
          "total-records": pagination.value.total,
          first: dataTableFirst.value,
          lazy: true,
          class: "p-datatable-sm custom-datatable",
          onPage: onPageChange
        }, {
          default: withCtx(() => [
            createVNode(unref(script$4), {
              field: "event_type",
              header: _ctx.$t("credits.eventType")
            }, {
              body: withCtx(({ data }) => [
                createVNode(unref(script$3), {
                  value: unref(customerEventService).formatEventType(data.event_type),
                  severity: unref(customerEventService).getEventSeverity(data.event_type)
                }, null, 8, ["value", "severity"])
              ]),
              _: 1
            }, 8, ["header"]),
            createVNode(unref(script$4), {
              field: "details",
              header: _ctx.$t("credits.details")
            }, {
              body: withCtx(({ data }) => [
                createBaseVNode("div", _hoisted_3$1, [
                  data.event_type === unref(EventType).CREDIT_ADDED ? (openBlock(), createElementBlock("div", _hoisted_4$1, toDisplayString(_ctx.$t("credits.added")) + " $" + toDisplayString(unref(customerEventService).formatAmount(data.params?.amount)), 1)) : data.event_type === unref(EventType).ACCOUNT_CREATED ? (openBlock(), createElementBlock("div", _hoisted_5$1, toDisplayString(_ctx.$t("credits.accountInitialized")), 1)) : data.event_type === unref(EventType).API_USAGE_COMPLETED ? (openBlock(), createElementBlock("div", _hoisted_6$1, [
                    createBaseVNode("div", _hoisted_7$1, toDisplayString(data.params?.api_name || "API"), 1),
                    createBaseVNode("div", _hoisted_8$1, toDisplayString(_ctx.$t("credits.model")) + ": " + toDisplayString(data.params?.model || "-"), 1)
                  ])) : createCommentVNode("", true)
                ])
              ]),
              _: 1
            }, 8, ["header"]),
            createVNode(unref(script$4), {
              field: "createdAt",
              header: _ctx.$t("credits.time")
            }, {
              body: withCtx(({ data }) => [
                createTextVNode(toDisplayString(unref(customerEventService).formatDate(data.createdAt)), 1)
              ]),
              _: 1
            }, 8, ["header"]),
            createVNode(unref(script$4), {
              field: "params",
              header: _ctx.$t("credits.additionalInfo")
            }, {
              body: withCtx(({ data }) => [
                unref(customerEventService).hasAdditionalInfo(data) ? withDirectives((openBlock(), createBlock(_sfc_main$2, {
                  key: 0,
                  variant: "textonly",
                  size: "icon-sm",
                  "aria-label": _ctx.$t("credits.additionalInfo")
                }, {
                  default: withCtx(() => _cache[0] || (_cache[0] = [
                    createBaseVNode("i", { class: "pi pi-info-circle" }, null, -1)
                  ])),
                  _: 2
                }, 1032, ["aria-label"])), [
                  [
                    _directive_tooltip,
                    {
                      escape: false,
                      value: tooltipContentMap.value.get(data.event_id) || "",
                      pt: {
                        text: {
                          style: {
                            width: "max-content !important"
                          }
                        }
                      }
                    },
                    void 0,
                    { top: true }
                  ]
                ]) : createCommentVNode("", true)
              ]),
              _: 1
            }, 8, ["header"])
          ]),
          _: 1
        }, 8, ["value", "rows", "total-records", "first"]))
      ]);
    };
  }
});
const _hoisted_1 = { class: "flex h-full flex-col" };
const _hoisted_2 = { class: "mb-2 text-2xl font-bold" };
const _hoisted_3 = { class: "flex flex-col gap-2" };
const _hoisted_4 = { class: "text-sm font-medium text-muted" };
const _hoisted_5 = { class: "flex items-center justify-between" };
const _hoisted_6 = { class: "flex flex-row items-center" };
const _hoisted_7 = {
  key: 1,
  class: "text-xs text-muted"
};
const _hoisted_8 = { class: "flex items-center justify-between" };
const _hoisted_9 = {
  key: 0,
  class: "grow"
};
const _hoisted_10 = { class: "text-sm font-medium" };
const _hoisted_11 = { class: "text-xs text-muted" };
const _hoisted_12 = { class: "flex flex-row gap-2" };
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "LegacyCreditsPanel",
  setup(__props) {
    const { buildDocsUrl, docsPaths } = useExternalLink();
    const dialogService = useDialogService();
    const authStore = useFirebaseAuthStore();
    const authActions = useFirebaseAuthActions();
    const commandStore = useCommandStore();
    const { isActiveSubscription } = useSubscription();
    const loading = computed(() => authStore.loading);
    const balanceLoading = computed(() => authStore.isFetchingBalance);
    const usageLogsTableRef = ref(null);
    const formattedLastUpdateTime = computed(
      () => authStore.lastBalanceUpdateTime ? authStore.lastBalanceUpdateTime.toLocaleString() : ""
    );
    watch(
      () => authStore.lastBalanceUpdateTime,
      (newTime, oldTime) => {
        if (newTime && newTime !== oldTime && usageLogsTableRef.value) {
          usageLogsTableRef.value.refresh();
        }
      }
    );
    const handlePurchaseCreditsClick = /* @__PURE__ */ __name(() => {
      dialogService.showTopUpCreditsDialog();
    }, "handlePurchaseCreditsClick");
    const handleCreditsHistoryClick = /* @__PURE__ */ __name(async () => {
      await authActions.accessBillingPortal();
    }, "handleCreditsHistoryClick");
    const handleMessageSupport = /* @__PURE__ */ __name(async () => {
      await commandStore.execute("Comfy.ContactSupport");
    }, "handleMessageSupport");
    const handleFaqClick = /* @__PURE__ */ __name(() => {
      window.open(
        buildDocsUrl("/tutorials/api-nodes/faq", { includeLocale: true }),
        "_blank"
      );
    }, "handleFaqClick");
    const handleOpenPartnerNodesInfo = /* @__PURE__ */ __name(() => {
      window.open(
        buildDocsUrl(docsPaths.partnerNodesPricing, { includeLocale: true }),
        "_blank"
      );
    }, "handleOpenPartnerNodesInfo");
    const creditHistory = ref([]);
    return (_ctx, _cache) => {
      return openBlock(), createBlock(unref(script$7), {
        value: "Credits",
        class: "credits-container h-full"
      }, {
        default: withCtx(() => [
          createBaseVNode("div", _hoisted_1, [
            createBaseVNode("h2", _hoisted_2, toDisplayString(_ctx.$t("credits.credits")), 1),
            createVNode(unref(script$5)),
            createBaseVNode("div", _hoisted_3, [
              createBaseVNode("h3", _hoisted_4, toDisplayString(_ctx.$t("credits.yourCreditBalance")), 1),
              createBaseVNode("div", _hoisted_5, [
                createVNode(_sfc_main$3, { "text-class": "text-3xl font-bold" }),
                loading.value ? (openBlock(), createBlock(unref(script$6), {
                  key: 0,
                  width: "2rem",
                  height: "2rem"
                })) : unref(isActiveSubscription) ? (openBlock(), createBlock(_sfc_main$2, {
                  key: 1,
                  loading: loading.value,
                  onClick: handlePurchaseCreditsClick
                }, {
                  default: withCtx(() => [
                    createTextVNode(toDisplayString(_ctx.$t("credits.purchaseCredits")), 1)
                  ]),
                  _: 1
                }, 8, ["loading"])) : createCommentVNode("", true)
              ]),
              createBaseVNode("div", _hoisted_6, [
                balanceLoading.value ? (openBlock(), createBlock(unref(script$6), {
                  key: 0,
                  width: "12rem",
                  height: "1rem",
                  class: "text-xs"
                })) : formattedLastUpdateTime.value ? (openBlock(), createElementBlock("div", _hoisted_7, toDisplayString(_ctx.$t("credits.lastUpdated")) + ": " + toDisplayString(formattedLastUpdateTime.value), 1)) : createCommentVNode("", true),
                createVNode(_sfc_main$2, {
                  variant: "muted-textonly",
                  size: "icon-sm",
                  "aria-label": _ctx.$t("g.refresh"),
                  onClick: _cache[0] || (_cache[0] = () => unref(authActions).fetchBalance())
                }, {
                  default: withCtx(() => _cache[1] || (_cache[1] = [
                    createBaseVNode("i", { class: "pi pi-refresh" }, null, -1)
                  ])),
                  _: 1
                }, 8, ["aria-label"])
              ])
            ]),
            createBaseVNode("div", _hoisted_8, [
              createBaseVNode("h3", null, toDisplayString(_ctx.$t("credits.activity")), 1),
              createVNode(_sfc_main$2, {
                variant: "muted-textonly",
                loading: loading.value,
                onClick: handleCreditsHistoryClick
              }, {
                default: withCtx(() => [
                  _cache[2] || (_cache[2] = createBaseVNode("i", { class: "pi pi-arrow-up-right" }, null, -1)),
                  createTextVNode(" " + toDisplayString(_ctx.$t("credits.invoiceHistory")), 1)
                ]),
                _: 1
              }, 8, ["loading"])
            ]),
            creditHistory.value.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_9, [
              createVNode(unref(script$2), {
                value: creditHistory.value,
                "show-headers": false
              }, {
                default: withCtx(() => [
                  createVNode(unref(script$4), {
                    field: "title",
                    header: _ctx.$t("g.name")
                  }, {
                    body: withCtx(({ data }) => [
                      createBaseVNode("div", _hoisted_10, toDisplayString(data.title), 1),
                      createBaseVNode("div", _hoisted_11, toDisplayString(data.timestamp), 1)
                    ]),
                    _: 1
                  }, 8, ["header"]),
                  createVNode(unref(script$4), {
                    field: "amount",
                    header: _ctx.$t("g.amount")
                  }, {
                    body: withCtx(({ data }) => [
                      createBaseVNode("div", {
                        class: normalizeClass([
                          "text-center text-base font-medium",
                          data.isPositive ? "text-sky-500" : "text-red-400"
                        ])
                      }, toDisplayString(data.isPositive ? "+" : "-") + "$" + toDisplayString(unref(formatMetronomeCurrency)(data.amount, "usd")), 3)
                    ]),
                    _: 1
                  }, 8, ["header"])
                ]),
                _: 1
              }, 8, ["value"])
            ])) : createCommentVNode("", true),
            createVNode(unref(script$5)),
            createVNode(_sfc_main$1, {
              ref_key: "usageLogsTableRef",
              ref: usageLogsTableRef
            }, null, 512),
            createBaseVNode("div", _hoisted_12, [
              createVNode(_sfc_main$2, {
                variant: "muted-textonly",
                onClick: handleFaqClick
              }, {
                default: withCtx(() => [
                  _cache[3] || (_cache[3] = createBaseVNode("i", { class: "pi pi-question-circle" }, null, -1)),
                  createTextVNode(" " + toDisplayString(_ctx.$t("credits.faqs")), 1)
                ]),
                _: 1
              }),
              createVNode(_sfc_main$2, {
                variant: "muted-textonly",
                onClick: handleOpenPartnerNodesInfo
              }, {
                default: withCtx(() => [
                  _cache[4] || (_cache[4] = createBaseVNode("i", { class: "pi pi-question-circle" }, null, -1)),
                  createTextVNode(" " + toDisplayString(_ctx.$t("subscription.partnerNodesCredits")), 1)
                ]),
                _: 1
              }),
              createVNode(_sfc_main$2, {
                variant: "muted-textonly",
                onClick: handleMessageSupport
              }, {
                default: withCtx(() => [
                  _cache[5] || (_cache[5] = createBaseVNode("i", { class: "pi pi-comments" }, null, -1)),
                  createTextVNode(" " + toDisplayString(_ctx.$t("credits.messageSupport")), 1)
                ]),
                _: 1
              })
            ])
          ])
        ]),
        _: 1
      });
    };
  }
});
export {
  _sfc_main as default
};
//# sourceMappingURL=LegacyCreditsPanel-DdzYlNTV.js.map
