"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useSearchParams } from "next/navigation";
import { Page, PageHeader, PageBody } from "@open-mercato/ui/backend/Page";
import { DataTable } from "@open-mercato/ui/backend/DataTable";
import { JsonDisplay } from "@open-mercato/ui/backend/JsonDisplay";
import { LoadingMessage, ErrorMessage } from "@open-mercato/ui/backend/detail";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { InjectionSpot } from "@open-mercato/ui/backend/injection/InjectionSpot";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { apiCall, apiCallOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { Button } from "@open-mercato/ui/primitives/button";
import { Card, CardContent, CardHeader, CardTitle } from "@open-mercato/ui/primitives/card";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { LogList } from "@open-mercato/ui/backend/LogList";
import { CreditCard, HandCoins, RefreshCw, Webhook } from "lucide-react";
const STATUS_STYLES = {
  pending: "bg-slate-100 text-slate-800",
  authorized: "bg-blue-100 text-blue-800",
  captured: "bg-green-100 text-green-800",
  partially_captured: "bg-emerald-100 text-emerald-800",
  refunded: "bg-amber-100 text-amber-800",
  partially_refunded: "bg-orange-100 text-orange-800",
  cancelled: "bg-zinc-200 text-zinc-900",
  failed: "bg-red-100 text-red-800",
  expired: "bg-neutral-200 text-neutral-900",
  unknown: "bg-purple-100 text-purple-800"
};
function formatDateTime(value) {
  if (!value) return "\u2014";
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) return value;
  return parsed.toLocaleString();
}
function formatAmount(value, currencyCode) {
  const amount = Number(value);
  if (Number.isNaN(amount)) return `${value} ${currencyCode}`;
  try {
    return new Intl.NumberFormat(void 0, {
      style: "currency",
      currency: currencyCode
    }).format(amount);
  } catch {
    return `${amount.toFixed(2)} ${currencyCode}`;
  }
}
function formatTypeLabel(value) {
  return value.split("_").filter(Boolean).map((part) => part[0]?.toUpperCase() + part.slice(1)).join(" ");
}
function formatLogDetailLabel(key) {
  return key.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").split(" ").filter(Boolean).map((part) => part[0]?.toUpperCase() + part.slice(1)).join(" ");
}
function isPrimitiveLogValue(value) {
  return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
}
function splitLogPayload(payload) {
  if (!payload) {
    return {
      inlineEntries: [],
      nestedEntries: []
    };
  }
  const inlineEntries = [];
  const nestedEntries = [];
  Object.entries(payload).forEach(([key, value]) => {
    if (isPrimitiveLogValue(value)) {
      inlineEntries.push([key, value]);
      return;
    }
    nestedEntries.push([key, value]);
  });
  return { inlineEntries, nestedEntries };
}
function DetailStat({ label, value }) {
  return /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-muted/30 px-4 py-3", children: [
    /* @__PURE__ */ jsx("div", { className: "text-overline font-medium uppercase tracking-wide text-muted-foreground", children: label }),
    /* @__PURE__ */ jsx("div", { className: "mt-1 text-sm font-medium", children: value })
  ] });
}
function PaymentTransactionsPage() {
  const t = useT();
  const searchParams = useSearchParams();
  const scopeVersion = useOrganizationScopeVersion();
  const [rows, setRows] = React.useState([]);
  const [page, setPage] = React.useState(1);
  const [total, setTotal] = React.useState(0);
  const [totalPages, setTotalPages] = React.useState(1);
  const [search, setSearch] = React.useState("");
  const [filterValues, setFilterValues] = React.useState({});
  const [isLoading, setIsLoading] = React.useState(true);
  const [selectedId, setSelectedId] = React.useState(null);
  const [detail, setDetail] = React.useState(null);
  const [isLoadingDetail, setIsLoadingDetail] = React.useState(false);
  const [detailError, setDetailError] = React.useState(null);
  const [isRefreshingStatus, setIsRefreshingStatus] = React.useState(false);
  const [isCapturing, setIsCapturing] = React.useState(false);
  const { runMutation } = useGuardedMutation({
    contextId: "payment_gateways:transactions-detail"
  });
  const noneLabel = t("common.none", "None");
  const requestedTransactionId = React.useMemo(() => {
    const raw = searchParams.get("transactionId");
    return raw && raw.trim().length > 0 ? raw.trim() : null;
  }, [searchParams]);
  const formatLogPrimitiveValue = React.useCallback((value) => {
    if (value === null) return noneLabel;
    if (typeof value === "boolean") return value ? t("common.yes", "Yes") : t("common.no", "No");
    return String(value);
  }, [noneLabel, t]);
  const loadRows = React.useCallback(async () => {
    setIsLoading(true);
    const params = new URLSearchParams({
      page: String(page),
      pageSize: "20"
    });
    if (search.trim()) params.set("search", search.trim());
    if (typeof filterValues.providerKey === "string" && filterValues.providerKey) {
      params.set("providerKey", filterValues.providerKey);
    }
    if (typeof filterValues.status === "string" && filterValues.status) {
      params.set("status", filterValues.status);
    }
    const fallback = { items: [], total: 0, page, pageSize: 20, totalPages: 1 };
    const call = await apiCall(`/api/payment_gateways/transactions?${params.toString()}`, void 0, { fallback });
    if (call.ok && call.result) {
      setRows(Array.isArray(call.result.items) ? call.result.items : []);
      setTotal(call.result.total ?? 0);
      setTotalPages(call.result.totalPages ?? 1);
    } else {
      flash(t("payment_gateways.transactions.error.load", "Failed to load payment transactions"), "error");
      setRows([]);
      setTotal(0);
      setTotalPages(1);
    }
    setIsLoading(false);
  }, [filterValues.providerKey, filterValues.status, page, search, t]);
  const loadDetail = React.useCallback(async (transactionId) => {
    setIsLoadingDetail(true);
    setDetailError(null);
    const call = await apiCall(`/api/payment_gateways/transactions/${encodeURIComponent(transactionId)}`, void 0, { fallback: null });
    if (call.ok && call.result) {
      setDetail(call.result);
    } else {
      setDetail(null);
      setDetailError(t("payment_gateways.transactions.error.loadDetail", "Failed to load transaction details"));
    }
    setIsLoadingDetail(false);
  }, [t]);
  React.useEffect(() => {
    void loadRows();
  }, [loadRows, scopeVersion]);
  React.useEffect(() => {
    if (!selectedId) {
      setDetail(null);
      setDetailError(null);
      return;
    }
    void loadDetail(selectedId);
  }, [loadDetail, selectedId]);
  React.useEffect(() => {
    setSelectedId((current) => current && rows.some((row) => row.id === current) ? current : null);
  }, [rows]);
  React.useEffect(() => {
    if (!requestedTransactionId) return;
    if (!rows.some((row) => row.id === requestedTransactionId)) return;
    setSelectedId(requestedTransactionId);
  }, [requestedTransactionId, rows]);
  const handleFiltersApply = React.useCallback((values) => {
    const next = {};
    Object.entries(values).forEach(([key, value]) => {
      if (typeof value === "string" && value.trim()) next[key] = value;
    });
    setFilterValues(next);
    setPage(1);
  }, []);
  const handleFiltersClear = React.useCallback(() => {
    setFilterValues({});
    setPage(1);
  }, []);
  const handleRefreshStatus = React.useCallback(async () => {
    if (!selectedId) return;
    setIsRefreshingStatus(true);
    try {
      await runMutation({
        operation: async () => {
          await apiCallOrThrow("/api/payment_gateways/status", {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ transactionId: selectedId })
          });
        },
        context: {
          entityType: "payment_gateways:gateway_transaction",
          entityId: selectedId
        },
        mutationPayload: { transactionId: selectedId }
      });
      await Promise.all([
        loadRows(),
        loadDetail(selectedId)
      ]);
      flash(t("payment_gateways.transactions.success.refreshStatus", "Transaction status refreshed"), "success");
    } catch (error) {
      const message = error instanceof Error && error.message ? error.message : t("payment_gateways.transactions.error.refreshStatus", "Failed to refresh transaction status");
      flash(message, "error");
    } finally {
      setIsRefreshingStatus(false);
    }
  }, [loadDetail, loadRows, runMutation, selectedId, t]);
  const handleCapturePayment = React.useCallback(async () => {
    if (!selectedId) return;
    setIsCapturing(true);
    try {
      await runMutation({
        operation: async () => {
          await apiCallOrThrow("/api/payment_gateways/capture", {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ transactionId: selectedId })
          });
        },
        context: {
          entityType: "payment_gateways:gateway_transaction",
          entityId: selectedId
        },
        mutationPayload: { transactionId: selectedId }
      });
      await Promise.all([
        loadRows(),
        loadDetail(selectedId)
      ]);
      flash(t("payment_gateways.transactions.success.capture", "Payment captured"), "success");
    } catch (error) {
      const message = error instanceof Error && error.message ? error.message : t("payment_gateways.transactions.error.capture", "Failed to capture payment");
      flash(message, "error");
    } finally {
      setIsCapturing(false);
    }
  }, [loadDetail, loadRows, runMutation, selectedId, t]);
  const providerOptions = React.useMemo(() => {
    const values = Array.from(new Set(rows.map((row) => row.providerKey).filter(Boolean))).sort((a, b) => a.localeCompare(b));
    return values.map((value) => ({
      label: formatTypeLabel(value),
      value
    }));
  }, [rows]);
  const filters = React.useMemo(() => [
    {
      id: "providerKey",
      type: "select",
      label: t("payment_gateways.transactions.filters.provider", "Provider"),
      options: [
        { label: t("payment_gateways.transactions.filters.allProviders", "All providers"), value: "" },
        ...providerOptions
      ]
    },
    {
      id: "status",
      type: "select",
      label: t("payment_gateways.transactions.filters.status", "Status"),
      options: [
        { label: t("payment_gateways.transactions.filters.allStatuses", "All statuses"), value: "" },
        { label: t("payment_gateways.status.pending", "Pending"), value: "pending" },
        { label: t("payment_gateways.status.authorized", "Authorized"), value: "authorized" },
        { label: t("payment_gateways.status.captured", "Captured"), value: "captured" },
        { label: t("payment_gateways.status.partially_captured", "Partially Captured"), value: "partially_captured" },
        { label: t("payment_gateways.status.refunded", "Refunded"), value: "refunded" },
        { label: t("payment_gateways.status.partially_refunded", "Partially Refunded"), value: "partially_refunded" },
        { label: t("payment_gateways.status.cancelled", "Cancelled"), value: "cancelled" },
        { label: t("payment_gateways.status.failed", "Failed"), value: "failed" },
        { label: t("payment_gateways.status.expired", "Expired"), value: "expired" },
        { label: t("payment_gateways.status.unknown", "Unknown"), value: "unknown" }
      ]
    }
  ], [providerOptions, t]);
  const columns = React.useMemo(() => [
    {
      accessorKey: "paymentId",
      header: t("payment_gateways.transactions.columns.paymentId", "Payment"),
      cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
        /* @__PURE__ */ jsx("div", { className: "font-medium", children: row.original.paymentId }),
        /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: row.original.id })
      ] }),
      meta: { maxWidth: "20rem" }
    },
    {
      accessorKey: "providerKey",
      header: t("payment_gateways.transactions.columns.provider", "Provider"),
      cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsx(CreditCard, { className: "h-4 w-4 text-muted-foreground" }),
        /* @__PURE__ */ jsx("span", { children: formatTypeLabel(row.original.providerKey) })
      ] })
    },
    {
      accessorKey: "unifiedStatus",
      header: t("payment_gateways.transactions.columns.status", "Status"),
      cell: ({ row }) => /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: STATUS_STYLES[row.original.unifiedStatus] ?? "", children: t(`payment_gateways.status.${row.original.unifiedStatus}`, formatTypeLabel(row.original.unifiedStatus)) })
    },
    {
      accessorKey: "amount",
      header: t("payment_gateways.transactions.columns.amount", "Amount"),
      cell: ({ row }) => formatAmount(row.original.amount, row.original.currencyCode)
    },
    {
      accessorKey: "providerSessionId",
      header: t("payment_gateways.transactions.columns.session", "Session"),
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "font-mono text-xs text-muted-foreground", children: row.original.providerSessionId ?? "\u2014" }),
      meta: { maxWidth: "18rem", truncate: true }
    },
    {
      accessorKey: "updatedAt",
      header: t("payment_gateways.transactions.columns.updatedAt", "Updated"),
      cell: ({ row }) => formatDateTime(row.original.updatedAt)
    }
  ], [t]);
  const selectedSummary = React.useMemo(
    () => rows.find((row) => row.id === selectedId) ?? null,
    [rows, selectedId]
  );
  const canCaptureSelected = React.useMemo(() => {
    const status = detail?.transaction.unifiedStatus ?? selectedSummary?.unifiedStatus ?? null;
    return status === "authorized";
  }, [detail?.transaction.unifiedStatus, selectedSummary?.unifiedStatus]);
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsx(
      PageHeader,
      {
        title: t("payment_gateways.transactions.title", "Payment Transactions"),
        description: t("payment_gateways.transactions.description", "Track all payment-gateway transactions, inspect webhook activity, and review provider logs from one place.")
      }
    ),
    /* @__PURE__ */ jsxs(PageBody, { className: "space-y-6", children: [
      /* @__PURE__ */ jsx(
        DataTable,
        {
          stickyActionsColumn: true,
          title: t("payment_gateways.transactions.tableTitle", "Transactions"),
          columns,
          data: rows,
          filters,
          filterValues,
          onFiltersApply: handleFiltersApply,
          onFiltersClear: handleFiltersClear,
          searchValue: search,
          onSearchChange: (value) => {
            setSearch(value);
            setPage(1);
          },
          searchPlaceholder: t("payment_gateways.transactions.searchPlaceholder", "Search by payment, transaction, session, or gateway id"),
          perspective: { tableId: "payment_gateways.transactions.list" },
          pagination: { page, pageSize: 20, total, totalPages, onPageChange: setPage },
          isLoading,
          onRowClick: (row) => setSelectedId((current) => current === row.id ? null : row.id),
          rowActions: (row) => /* @__PURE__ */ jsx(RowActions, { items: [
            {
              id: "details",
              label: selectedId === row.id ? t("payment_gateways.transactions.actions.hideDetails", "Hide details") : t("payment_gateways.transactions.actions.showDetails", "Show details"),
              onSelect: () => setSelectedId((current) => current === row.id ? null : row.id)
            }
          ] })
        }
      ),
      selectedId ? /* @__PURE__ */ jsxs(Card, { children: [
        /* @__PURE__ */ jsxs(CardHeader, { className: "gap-4 sm:flex-row sm:items-start sm:justify-between", children: [
          /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
            /* @__PURE__ */ jsx(CardTitle, { children: t("payment_gateways.transactions.detail.title", "Transaction details") }),
            selectedSummary ? /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2 text-sm text-muted-foreground", children: [
              /* @__PURE__ */ jsx("span", { children: selectedSummary.paymentId }),
              /* @__PURE__ */ jsx("span", { children: "\u2022" }),
              /* @__PURE__ */ jsx("span", { children: formatTypeLabel(selectedSummary.providerKey) }),
              /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: STATUS_STYLES[selectedSummary.unifiedStatus] ?? "", children: t(`payment_gateways.status.${selectedSummary.unifiedStatus}`, formatTypeLabel(selectedSummary.unifiedStatus)) })
            ] }) : null
          ] }),
          /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "sm",
              onClick: () => void handleRefreshStatus(),
              disabled: isRefreshingStatus || isLoadingDetail || isCapturing,
              children: [
                isRefreshingStatus ? /* @__PURE__ */ jsx(Spinner, { className: "mr-2 h-4 w-4" }) : /* @__PURE__ */ jsx(RefreshCw, { className: "mr-2 h-4 w-4" }),
                t("payment_gateways.transactions.actions.refreshStatus", "Refresh status")
              ]
            }
          ),
          canCaptureSelected ? /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              size: "sm",
              onClick: () => void handleCapturePayment(),
              disabled: isRefreshingStatus || isLoadingDetail || isCapturing,
              children: [
                isCapturing ? /* @__PURE__ */ jsx(Spinner, { className: "mr-2 h-4 w-4" }) : /* @__PURE__ */ jsx(HandCoins, { className: "mr-2 h-4 w-4" }),
                t("payment_gateways.transactions.actions.capture", "Capture payment")
              ]
            }
          ) : null
        ] }),
        /* @__PURE__ */ jsxs(CardContent, { className: "space-y-6", children: [
          isLoadingDetail ? /* @__PURE__ */ jsx(LoadingMessage, { label: t("payment_gateways.transactions.detail.loading", "Loading transaction details") }) : null,
          !isLoadingDetail && detailError ? /* @__PURE__ */ jsx(ErrorMessage, { label: detailError }) : null,
          !isLoadingDetail && !detailError && detail ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsxs("div", { className: "grid gap-4 lg:grid-cols-4", children: [
              /* @__PURE__ */ jsx(
                DetailStat,
                {
                  label: t("payment_gateways.transactions.detail.summary.status", "Status"),
                  value: /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: STATUS_STYLES[detail.transaction.unifiedStatus] ?? "", children: t(`payment_gateways.status.${detail.transaction.unifiedStatus}`, formatTypeLabel(detail.transaction.unifiedStatus)) })
                }
              ),
              /* @__PURE__ */ jsx(
                DetailStat,
                {
                  label: t("payment_gateways.transactions.detail.summary.gatewayStatus", "Gateway status"),
                  value: detail.transaction.gatewayStatus ?? noneLabel
                }
              ),
              /* @__PURE__ */ jsx(
                DetailStat,
                {
                  label: t("payment_gateways.transactions.detail.summary.amount", "Amount"),
                  value: formatAmount(detail.transaction.amount, detail.transaction.currencyCode)
                }
              ),
              /* @__PURE__ */ jsx(
                DetailStat,
                {
                  label: t("payment_gateways.transactions.detail.summary.provider", "Provider"),
                  value: formatTypeLabel(detail.transaction.providerKey)
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]", children: [
              /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
                /* @__PURE__ */ jsxs("section", { className: "space-y-3", children: [
                  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("payment_gateways.transactions.detail.identifiers", "Identifiers") }),
                  /* @__PURE__ */ jsx("dl", { className: "grid gap-3 md:grid-cols-2", children: [
                    [t("payment_gateways.transactions.columns.transactionId", "Transaction ID"), detail.transaction.id],
                    [t("payment_gateways.transactions.columns.paymentId", "Payment ID"), detail.transaction.paymentId],
                    [t("payment_gateways.transactions.columns.session", "Session ID"), detail.transaction.providerSessionId ?? "\u2014"],
                    [t("payment_gateways.transactions.columns.gatewayPaymentId", "Gateway payment ID"), detail.transaction.gatewayPaymentId ?? "\u2014"],
                    [t("payment_gateways.transactions.columns.gatewayRefundId", "Gateway refund ID"), detail.transaction.gatewayRefundId ?? "\u2014"],
                    [t("payment_gateways.transactions.columns.redirectUrl", "Redirect URL"), detail.transaction.redirectUrl ?? "\u2014"],
                    [t("payment_gateways.transactions.columns.createdAt", "Created at"), formatDateTime(detail.transaction.createdAt)],
                    [t("payment_gateways.transactions.columns.updatedAt", "Updated at"), formatDateTime(detail.transaction.updatedAt)],
                    [t("payment_gateways.transactions.columns.lastWebhookAt", "Last webhook"), formatDateTime(detail.transaction.lastWebhookAt)],
                    [t("payment_gateways.transactions.columns.lastPolledAt", "Last poll"), formatDateTime(detail.transaction.lastPolledAt)]
                  ].map(([label, value]) => /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-muted/30 px-4 py-3", children: [
                    /* @__PURE__ */ jsx("dt", { className: "text-overline font-medium uppercase tracking-wide text-muted-foreground", children: label }),
                    /* @__PURE__ */ jsx("dd", { className: "mt-1 break-all text-sm", children: value })
                  ] }, label)) })
                ] }),
                /* @__PURE__ */ jsxs("section", { className: "space-y-3", children: [
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                    /* @__PURE__ */ jsx(Webhook, { className: "h-4 w-4 text-muted-foreground" }),
                    /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("payment_gateways.transactions.detail.webhooks", "Webhook activity") })
                  ] }),
                  detail.transaction.webhookLog && detail.transaction.webhookLog.length > 0 ? /* @__PURE__ */ jsx("div", { className: "overflow-hidden rounded-lg border", children: /* @__PURE__ */ jsxs("table", { className: "w-full text-sm", children: [
                    /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "border-b bg-muted/50", children: [
                      /* @__PURE__ */ jsx("th", { className: "px-4 py-2 text-left font-medium", children: t("payment_gateways.transactions.columns.eventType", "Event") }),
                      /* @__PURE__ */ jsx("th", { className: "px-4 py-2 text-left font-medium", children: t("payment_gateways.transactions.columns.status", "Status") }),
                      /* @__PURE__ */ jsx("th", { className: "px-4 py-2 text-left font-medium", children: t("payment_gateways.transactions.columns.processed", "Processed") }),
                      /* @__PURE__ */ jsx("th", { className: "px-4 py-2 text-left font-medium", children: t("payment_gateways.transactions.columns.receivedAt", "Received") })
                    ] }) }),
                    /* @__PURE__ */ jsx("tbody", { children: detail.transaction.webhookLog.map((entry) => /* @__PURE__ */ jsxs("tr", { className: "border-b last:border-0", children: [
                      /* @__PURE__ */ jsx("td", { className: "px-4 py-2 font-medium", children: entry.eventType }),
                      /* @__PURE__ */ jsx("td", { className: "px-4 py-2", children: /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: STATUS_STYLES[entry.unifiedStatus] ?? "", children: t(`payment_gateways.status.${entry.unifiedStatus}`, formatTypeLabel(entry.unifiedStatus)) }) }),
                      /* @__PURE__ */ jsx("td", { className: "px-4 py-2", children: entry.processed ? t("common.yes", "Yes") : t("common.no", "No") }),
                      /* @__PURE__ */ jsx("td", { className: "px-4 py-2 text-muted-foreground", children: formatDateTime(entry.receivedAt) })
                    ] }, `${entry.idempotencyKey}:${entry.receivedAt}`)) })
                  ] }) }) : /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("payment_gateways.transactions.detail.webhooksEmpty", "No webhook events have been recorded for this transaction yet.") })
                ] }),
                /* @__PURE__ */ jsxs("section", { className: "space-y-3", children: [
                  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("payment_gateways.transactions.detail.logs", "Gateway logs") }),
                  /* @__PURE__ */ jsx(
                    LogList,
                    {
                      entries: detail.logs.map((log) => {
                        const metadataEntries = [
                          [t("payment_gateways.transactions.log.time", "Time"), formatDateTime(log.createdAt)],
                          [t("payment_gateways.transactions.log.level", "Level"), t(`payment_gateways.transactions.level.${log.level}`, log.level)],
                          [t("payment_gateways.transactions.log.code", "Code"), log.code ?? null],
                          [t("payment_gateways.transactions.log.runId", "Run ID"), log.runId ?? null],
                          [t("payment_gateways.transactions.log.entityType", "Entity Type"), log.scopeEntityType ?? null],
                          [t("payment_gateways.transactions.log.entityId", "Entity ID"), log.scopeEntityId ?? null]
                        ].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
                        const { inlineEntries, nestedEntries } = splitLogPayload(log.payload);
                        return {
                          id: log.id,
                          time: formatDateTime(log.createdAt),
                          level: log.level,
                          levelLabel: t(`payment_gateways.transactions.level.${log.level}`, log.level),
                          message: log.message,
                          body: /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
                            metadataEntries.length > 0 ? /* @__PURE__ */ jsx("dl", { className: "grid gap-3 sm:grid-cols-2 xl:grid-cols-3", children: metadataEntries.map(([label, value]) => /* @__PURE__ */ jsxs("div", { className: "rounded-md border bg-muted/30 px-3 py-2", children: [
                              /* @__PURE__ */ jsx("dt", { className: "text-overline font-medium uppercase tracking-wide text-muted-foreground", children: label }),
                              /* @__PURE__ */ jsx("dd", { className: "mt-1 break-all text-sm", children: value })
                            ] }, label)) }) : null,
                            inlineEntries.length > 0 ? /* @__PURE__ */ jsx("dl", { className: "grid gap-3 sm:grid-cols-2 xl:grid-cols-3", children: inlineEntries.map(([key, value]) => /* @__PURE__ */ jsxs("div", { className: "rounded-md border bg-muted/30 px-3 py-2", children: [
                              /* @__PURE__ */ jsx("dt", { className: "text-overline font-medium uppercase tracking-wide text-muted-foreground", children: formatLogDetailLabel(key) }),
                              /* @__PURE__ */ jsx("dd", { className: "mt-1 break-words text-sm", children: formatLogPrimitiveValue(value) })
                            ] }, key)) }) : null,
                            nestedEntries.map(([key, value]) => /* @__PURE__ */ jsx(
                              JsonDisplay,
                              {
                                data: value,
                                title: formatLogDetailLabel(key),
                                defaultExpanded: true,
                                maxInitialDepth: 1,
                                theme: "dark",
                                maxHeight: "16rem",
                                className: "p-4"
                              },
                              key
                            ))
                          ] })
                        };
                      }),
                      emptyMessage: t("payment_gateways.transactions.detail.logsEmpty", "No transaction-scoped logs are available yet.")
                    }
                  )
                ] })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
                /* @__PURE__ */ jsx(
                  JsonDisplay,
                  {
                    data: detail.transaction.gatewayMetadata ?? {},
                    title: t("payment_gateways.transactions.detail.gatewayMetadata", "Gateway metadata"),
                    defaultExpanded: true,
                    maxInitialDepth: 1,
                    theme: "dark",
                    maxHeight: "24rem",
                    className: "p-4"
                  }
                ),
                /* @__PURE__ */ jsx(
                  InjectionSpot,
                  {
                    spotId: "admin.page:payment-gateways/transactions:after",
                    context: { selectedPaymentId: detail.transaction.paymentId }
                  }
                )
              ] })
            ] })
          ] }) : null
        ] })
      ] }) : null
    ] })
  ] });
}
export {
  PaymentTransactionsPage as default
};
//# sourceMappingURL=page.js.map
