"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Button } from "@open-mercato/ui/primitives/button";
import {
  SegmentedControl,
  SegmentedControlItem
} from "@open-mercato/ui/primitives/segmented-control";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { StatusBadge } from "@open-mercato/ui/primitives/status-badge";
import { SimpleTooltip, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@open-mercato/ui/primitives/tooltip";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { formatAttachmentFileSize as formatBytes } from "@open-mercato/ui/backend/detail/AttachmentVisualPreview";
import { ErrorMessage } from "@open-mercato/ui/backend/detail";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Copy, Info, RefreshCw, Trash2 } from "lucide-react";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("configs");
const API_PATH = "/api/configs/module-telemetry";
const HOUR_MS = 60 * 60 * 1e3;
const REASON_LABEL_KEYS = {
  p95_duration: "configs.moduleTelemetry.reason.p95Duration",
  cpu: "configs.moduleTelemetry.reason.cpu",
  heap_allocations: "configs.moduleTelemetry.reason.heapAllocations",
  rss_growth: "configs.moduleTelemetry.reason.rssGrowth",
  errors: "configs.moduleTelemetry.reason.errors"
};
const REASON_FALLBACKS = {
  p95_duration: "Slow p95",
  cpu: "CPU",
  heap_allocations: "Heap",
  rss_growth: "RSS growth",
  errors: "Errors"
};
const USAGE_RANGE_PRESETS = ["today", "last_1h", "last_6h", "last_24h", "all"];
function formatMs(ms) {
  if (!Number.isFinite(ms) || ms <= 0) return "0 ms";
  if (ms >= 1e3) return `${(ms / 1e3).toFixed(ms >= 1e4 ? 1 : 2)} s`;
  return `${Math.round(ms)} ms`;
}
function formatCount(value) {
  return new Intl.NumberFormat().format(value);
}
function formatBucketInterval(ms) {
  if (!ms || !Number.isFinite(ms)) return "interval";
  if (ms >= 60 * 60 * 1e3) {
    const hours = Math.round(ms / (60 * 60 * 1e3));
    return `${hours}h`;
  }
  const minutes = Math.round(ms / (60 * 1e3));
  return `${minutes}m`;
}
function bucketIntervalLabel(buckets, fallbackMs, translate) {
  const intervals = new Set(
    buckets.map((bucket) => bucket.bucketIntervalMs).filter((value) => Number.isFinite(value) && value > 0)
  );
  if (intervals.size === 1) return formatBucketInterval(Array.from(intervals)[0]);
  return formatBucketInterval(fallbackMs);
}
function bucketCountLabel(buckets, fallbackMs, translate) {
  const intervals = new Set(
    buckets.map((bucket) => bucket.bucketIntervalMs).filter((value) => Number.isFinite(value) && value > 0)
  );
  if (intervals.size > 1) {
    return translate(
      "configs.moduleTelemetry.overview.mixedBucketCount",
      "{{count}} buckets \xB7 mixed intervals",
      { count: buckets.length }
    );
  }
  return translate(
    "configs.moduleTelemetry.overview.bucketCount",
    "{{count}} {{bucketWord}} ({{interval}} interval)",
    {
      count: buckets.length,
      bucketWord: buckets.length === 1 ? translate("configs.moduleTelemetry.overview.bucketSingular", "bucket") : translate("configs.moduleTelemetry.overview.bucketPlural", "buckets"),
      interval: bucketIntervalLabel(buckets, fallbackMs, translate)
    }
  );
}
function formatRangeBoundary(ms) {
  return new Date(ms).toLocaleString(void 0, {
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit"
  });
}
function MetricTitle({
  label,
  tooltip
}) {
  return /* @__PURE__ */ jsxs("div", { className: "inline-flex min-w-0 items-center gap-1.5 text-xs uppercase tracking-wide text-muted-foreground", children: [
    /* @__PURE__ */ jsx("span", { className: "truncate", children: label }),
    /* @__PURE__ */ jsx(SimpleTooltip, { content: tooltip, side: "top", align: "center", variant: "light", size: "lg", children: /* @__PURE__ */ jsx(
      "span",
      {
        className: "inline-flex size-4 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:text-foreground",
        "aria-label": tooltip,
        children: /* @__PURE__ */ jsx(Info, { className: "h-3.5 w-3.5", "aria-hidden": "true" })
      }
    ) })
  ] });
}
function MetricCard({
  label,
  tooltip,
  value,
  subValue
}) {
  return /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
    /* @__PURE__ */ jsx(MetricTitle, { label, tooltip }),
    /* @__PURE__ */ jsx("div", { className: "mt-2 text-2xl font-semibold", children: value }),
    subValue ? /* @__PURE__ */ jsx("div", { className: "mt-1 text-xs text-muted-foreground", children: subValue }) : null
  ] });
}
function firstBucketStartMs(buckets) {
  const starts = buckets.map((bucket) => Date.parse(bucket.bucketStart)).filter((value) => Number.isFinite(value));
  return starts.length ? Math.min(...starts) : null;
}
function firstBucketEndMs(buckets) {
  const ends = buckets.map((bucket) => Date.parse(bucket.bucketEnd)).filter((value) => Number.isFinite(value));
  return ends.length ? Math.min(...ends) : null;
}
function firstAvailableTelemetryMs(buckets, startedAtMs, nowMs) {
  const firstBucketMs = firstBucketStartMs(buckets);
  if (firstBucketMs === null) return Number.isFinite(startedAtMs) ? startedAtMs : nowMs;
  if (!Number.isFinite(startedAtMs)) return firstBucketMs;
  const firstBucketEnd = firstBucketEndMs(buckets);
  if (firstBucketEnd !== null && firstBucketEnd > startedAtMs) return startedAtMs;
  return firstBucketMs;
}
function startOfTodayMs(nowMs) {
  const date = new Date(nowMs);
  date.setHours(0, 0, 0, 0);
  return date.getTime();
}
function resolveUsageRange(preset, buckets, startedAt, nowMs = Date.now()) {
  const startedAtMs = Date.parse(startedAt);
  const availableStartMs = firstAvailableTelemetryMs(buckets, startedAtMs, nowMs);
  const rawStartMs = preset === "today" ? startOfTodayMs(nowMs) : preset === "last_1h" ? nowMs - HOUR_MS : preset === "last_6h" ? nowMs - 6 * HOUR_MS : preset === "last_24h" ? nowMs - 24 * HOUR_MS : availableStartMs;
  const boundedStartMs = preset === "all" ? rawStartMs : Math.max(rawStartMs, availableStartMs);
  return {
    preset,
    startMs: Math.min(boundedStartMs, nowMs),
    endMs: nowMs
  };
}
function bucketsInRange(buckets, range) {
  return buckets.filter((bucket) => {
    const bucketStartMs = Date.parse(bucket.bucketStart);
    const bucketEndMs = Date.parse(bucket.bucketEnd);
    if (!Number.isFinite(bucketStartMs) || !Number.isFinite(bucketEndMs)) return false;
    return bucketEndMs > range.startMs && bucketStartMs <= range.endMs;
  });
}
function activeRangeHours(buckets, bucketIntervalMs) {
  const fallbackIntervalMs = bucketIntervalMs && Number.isFinite(bucketIntervalMs) && bucketIntervalMs > 0 ? bucketIntervalMs : HOUR_MS;
  if (!buckets.length) return fallbackIntervalMs / HOUR_MS;
  const totalMs = buckets.reduce((sum, bucket) => {
    const interval = Number.isFinite(bucket.bucketIntervalMs) && bucket.bucketIntervalMs > 0 ? bucket.bucketIntervalMs : fallbackIntervalMs;
    return sum + interval;
  }, 0);
  return Math.max(fallbackIntervalMs / HOUR_MS, totalMs / HOUR_MS);
}
function formatActiveDuration(hours) {
  if (!Number.isFinite(hours) || hours <= 0) return "0m";
  if (hours < 1) return `${Math.max(Math.round(hours * 60), 1)}m`;
  if (hours < 10) return `${hours.toFixed(1)}h`;
  return `${Math.round(hours)}h`;
}
function usageRangeLabel(preset, translate) {
  if (preset === "today") return translate("configs.moduleTelemetry.range.today", "Today");
  if (preset === "last_1h") return translate("configs.moduleTelemetry.range.last1h", "Last hour");
  if (preset === "last_6h") return translate("configs.moduleTelemetry.range.last6h", "Last 6 hours");
  if (preset === "last_24h") return translate("configs.moduleTelemetry.range.last24h", "Last 24 hours");
  return translate("configs.moduleTelemetry.range.all", "All available");
}
function isUsageRangePreset(value) {
  return !!value && USAGE_RANGE_PRESETS.includes(value);
}
function readUsageRangePreset(searchParams) {
  const value = searchParams?.get("range") ?? null;
  return isUsageRangePreset(value) ? value : "today";
}
function usageStageLabel(stage, translate) {
  if (stage === "startup") return translate("configs.moduleTelemetry.stage.startup", "Startup");
  return translate("configs.moduleTelemetry.stage.running", "Running");
}
function sortStageRows(a, b) {
  if (a.stage !== b.stage) return a.stage === "startup" ? -1 : 1;
  return b.totalCpuMs - a.totalCpuMs;
}
function groupRangeModules(modules) {
  const groups = /* @__PURE__ */ new Map();
  for (const module of modules) {
    const group = groups.get(module.moduleId) ?? [];
    group.push(module);
    groups.set(module.moduleId, group);
  }
  return Array.from(groups.entries()).map(([moduleId, stages]) => {
    const candidateReasons = Array.from(new Set(stages.flatMap((stage) => stage.candidateReasons)));
    return {
      moduleId,
      stages: [...stages].sort(sortStageRows),
      candidateReasons,
      calls: stages.reduce((sum, stage) => sum + stage.calls, 0),
      totalCpuMs: stages.reduce((sum, stage) => sum + stage.totalCpuMs, 0),
      positiveRssDeltaBytes: stages.reduce((sum, stage) => sum + stage.positiveRssDeltaBytes, 0)
    };
  }).sort(
    (a, b) => b.candidateReasons.length - a.candidateReasons.length || b.totalCpuMs - a.totalCpuMs || b.positiveRssDeltaBytes - a.positiveRssDeltaBytes || b.calls - a.calls || a.moduleId.localeCompare(b.moduleId)
  );
}
function buildCandidateReasonsForModule(module, thresholds, bucketCount) {
  const divisor = Math.max(1, bucketCount);
  const reasons = [];
  if (module.p95DurationMs >= thresholds.p95DurationMs) reasons.push("p95_duration");
  if (module.totalCpuMs / divisor >= thresholds.cpuMs) reasons.push("cpu");
  if (module.positiveHeapDeltaBytes / divisor >= thresholds.positiveHeapDeltaBytes) reasons.push("heap_allocations");
  if (module.positiveRssDeltaBytes / divisor >= thresholds.positiveRssDeltaBytes) reasons.push("rss_growth");
  if (module.errors / divisor >= thresholds.errors) reasons.push("errors");
  return reasons;
}
function mergeRangeOperations(modules) {
  const operations = /* @__PURE__ */ new Map();
  for (const module of modules) {
    for (const operation of module.topOperations) {
      const key = `${operation.surface}\0${operation.operation}\0${operation.resourceId ?? ""}`;
      const existing = operations.get(key);
      if (!existing) {
        operations.set(key, { ...operation });
        continue;
      }
      existing.calls += operation.calls;
      existing.errors += operation.errors;
      existing.totalDurationMs += operation.totalDurationMs;
      existing.maxDurationMs = Math.max(existing.maxDurationMs, operation.maxDurationMs);
      existing.p95DurationMs = Math.max(existing.p95DurationMs, operation.p95DurationMs);
      existing.totalCpuUserMs += operation.totalCpuUserMs;
      existing.totalCpuSystemMs += operation.totalCpuSystemMs;
      existing.maxCpuMs = Math.max(existing.maxCpuMs, operation.maxCpuMs);
      existing.totalHeapDeltaBytes += operation.totalHeapDeltaBytes;
      existing.positiveHeapDeltaBytes += operation.positiveHeapDeltaBytes;
      existing.maxHeapDeltaBytes = Math.max(existing.maxHeapDeltaBytes, operation.maxHeapDeltaBytes);
      existing.totalRssDeltaBytes += operation.totalRssDeltaBytes;
      existing.positiveRssDeltaBytes += operation.positiveRssDeltaBytes;
      existing.maxRssDeltaBytes = Math.max(existing.maxRssDeltaBytes, operation.maxRssDeltaBytes);
      existing.firstSeenAt = existing.firstSeenAt < operation.firstSeenAt ? existing.firstSeenAt : operation.firstSeenAt;
      existing.lastSeenAt = existing.lastSeenAt > operation.lastSeenAt ? existing.lastSeenAt : operation.lastSeenAt;
    }
  }
  return Array.from(operations.values()).sort(
    (a, b) => b.totalCpuUserMs + b.totalCpuSystemMs - (a.totalCpuUserMs + a.totalCpuSystemMs) || b.totalDurationMs - a.totalDurationMs || b.calls - a.calls
  ).slice(0, 5);
}
function mergeRangeSurfaces(modules) {
  const surfaces = /* @__PURE__ */ new Map();
  for (const module of modules) {
    for (const surface of module.surfaces) {
      const existing = surfaces.get(surface.surface);
      if (!existing) {
        surfaces.set(surface.surface, { ...surface });
        continue;
      }
      existing.calls += surface.calls;
      existing.errors += surface.errors;
      existing.totalDurationMs += surface.totalDurationMs;
      existing.p95DurationMs = Math.max(existing.p95DurationMs, surface.p95DurationMs);
      existing.totalCpuMs += surface.totalCpuMs;
      existing.positiveHeapDeltaBytes += surface.positiveHeapDeltaBytes;
      existing.positiveRssDeltaBytes += surface.positiveRssDeltaBytes;
    }
  }
  return Array.from(surfaces.values()).sort((a, b) => b.totalCpuMs - a.totalCpuMs || b.totalDurationMs - a.totalDurationMs);
}
function aggregateRangeModules(buckets, thresholds) {
  const grouped = /* @__PURE__ */ new Map();
  for (const bucket of buckets) {
    for (const module of bucket.modules) {
      const key = `${module.moduleId}\0${bucket.stage}`;
      const group = grouped.get(key) ?? { moduleId: module.moduleId, stage: bucket.stage, modules: [], bucketKeys: /* @__PURE__ */ new Set() };
      group.modules.push(module);
      group.bucketKeys.add(bucket.bucketStart);
      grouped.set(key, group);
    }
  }
  return Array.from(grouped.values()).map(({ moduleId, stage, modules, bucketKeys }) => {
    const summaryBase = {
      moduleId,
      stage,
      calls: modules.reduce((sum, module) => sum + module.calls, 0),
      errors: modules.reduce((sum, module) => sum + module.errors, 0),
      totalDurationMs: modules.reduce((sum, module) => sum + module.totalDurationMs, 0),
      p95DurationMs: Math.max(...modules.map((module) => module.p95DurationMs), 0),
      totalCpuMs: modules.reduce((sum, module) => sum + module.totalCpuMs, 0),
      positiveHeapDeltaBytes: modules.reduce((sum, module) => sum + module.positiveHeapDeltaBytes, 0),
      positiveRssDeltaBytes: modules.reduce((sum, module) => sum + module.positiveRssDeltaBytes, 0),
      surfaces: mergeRangeSurfaces(modules),
      topOperations: mergeRangeOperations(modules)
    };
    return {
      ...summaryBase,
      candidateReasons: buildCandidateReasonsForModule(summaryBase, thresholds, bucketKeys.size)
    };
  }).sort(
    (a, b) => b.candidateReasons.length - a.candidateReasons.length || b.totalCpuMs - a.totalCpuMs || b.positiveRssDeltaBytes - a.positiveRssDeltaBytes || b.calls - a.calls
  );
}
function RangeOverview({
  buckets,
  modules,
  range,
  rangePreset,
  onRangePresetChange,
  bucketIntervalMs,
  translate
}) {
  const selectedHours = activeRangeHours(buckets, bucketIntervalMs);
  const activeDurationLabel = formatActiveDuration(selectedHours);
  const bucketsLabel = bucketCountLabel(buckets, bucketIntervalMs, translate);
  const totalHeapGrowthBytes = modules.reduce((sum, module) => sum + module.positiveHeapDeltaBytes, 0);
  const totalRssGrowthBytes = modules.reduce((sum, module) => sum + module.positiveRssDeltaBytes, 0);
  const totals = {
    modules: new Set(modules.map((module) => module.moduleId)).size,
    calls: modules.reduce((sum, module) => sum + module.calls, 0),
    totalCpuMs: modules.reduce((sum, module) => sum + module.totalCpuMs, 0),
    avgHeapGrowthPerHour: totalHeapGrowthBytes / selectedHours,
    avgRssGrowthPerHour: totalRssGrowthBytes / selectedHours
  };
  const growthTooltip = translate(
    "configs.moduleTelemetry.overview.growthTooltip",
    "Average positive growth per hour of measured activity in the selected range: total growth divided by the hours actually covered by tracked buckets, not the full wall-clock span. Idle stretches with no tracked calls do not dilute this rate, so it stays comparable across range presets. This is allocation pressure over time, not the current live process memory."
  );
  const heapSubValue = translate(
    "configs.moduleTelemetry.overview.growthSubValue",
    "{{total}} total over {{duration}}",
    { total: formatBytes(totalHeapGrowthBytes), duration: activeDurationLabel }
  );
  const rssSubValue = translate(
    "configs.moduleTelemetry.overview.growthSubValue",
    "{{total}} total over {{duration}}",
    { total: formatBytes(totalRssGrowthBytes), duration: activeDurationLabel }
  );
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4 rounded-lg border bg-card p-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
        /* @__PURE__ */ jsx("h3", { className: "text-base font-semibold", children: translate("configs.moduleTelemetry.overview.title", "Usage overview") }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: translate(
          "configs.moduleTelemetry.overview.description",
          "From {{from}} to now \xB7 {{buckets}}",
          {
            from: formatRangeBoundary(range.startMs),
            buckets: bucketsLabel
          }
        ) })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-2 sm:flex-row", children: /* @__PURE__ */ jsx(
        SegmentedControl,
        {
          value: rangePreset,
          onValueChange: (value) => onRangePresetChange(value),
          "aria-label": translate("configs.moduleTelemetry.range.label", "Time range"),
          size: "sm",
          className: "max-w-full flex-wrap overflow-x-auto rounded-lg",
          children: USAGE_RANGE_PRESETS.map((option) => /* @__PURE__ */ jsx(SegmentedControlItem, { value: option, children: usageRangeLabel(option, translate) }, option))
        }
      ) })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-5", children: [
      /* @__PURE__ */ jsx(
        MetricCard,
        {
          label: translate("configs.moduleTelemetry.overview.modules", "Modules"),
          tooltip: translate("configs.moduleTelemetry.overview.modulesTooltip", "Unique modules with tracked activity in the selected range. Startup and running are shown as separate rows inside each module group."),
          value: formatCount(totals.modules)
        }
      ),
      /* @__PURE__ */ jsx(
        MetricCard,
        {
          label: translate("configs.moduleTelemetry.overview.calls", "Calls"),
          tooltip: translate("configs.moduleTelemetry.overview.callsTooltip", "Total tracked operation calls in the selected range."),
          value: formatCount(totals.calls)
        }
      ),
      /* @__PURE__ */ jsx(
        MetricCard,
        {
          label: translate("configs.moduleTelemetry.overview.cpu", "CPU"),
          tooltip: translate("configs.moduleTelemetry.overview.cpuTooltip", "Total CPU time attributed to tracked module operations in the selected range."),
          value: formatMs(totals.totalCpuMs)
        }
      ),
      /* @__PURE__ */ jsx(
        MetricCard,
        {
          label: translate("configs.moduleTelemetry.overview.heapPerHour", "Heap / hour"),
          tooltip: growthTooltip,
          value: formatBytes(totals.avgHeapGrowthPerHour),
          subValue: heapSubValue
        }
      ),
      /* @__PURE__ */ jsx(
        MetricCard,
        {
          label: translate("configs.moduleTelemetry.overview.rssPerHour", "RSS / hour"),
          tooltip: growthTooltip,
          value: formatBytes(totals.avgRssGrowthPerHour),
          subValue: rssSubValue
        }
      )
    ] })
  ] });
}
function CandidateBadges({
  module,
  translate
}) {
  if (!module.candidateReasons.length) {
    return /* @__PURE__ */ jsx(StatusBadge, { variant: "neutral", dot: true, children: translate("configs.moduleTelemetry.table.normal", "Normal") });
  }
  return /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5", children: module.candidateReasons.map((reason) => /* @__PURE__ */ jsx(StatusBadge, { variant: "warning", dot: true, children: translate(REASON_LABEL_KEYS[reason] ?? `configs.moduleTelemetry.reason.${reason}`, REASON_FALLBACKS[reason] ?? reason) }, reason)) });
}
function StageBadge({
  stage,
  translate
}) {
  return /* @__PURE__ */ jsx(StatusBadge, { variant: stage === "startup" ? "info" : "neutral", dot: true, children: usageStageLabel(stage, translate) });
}
function copyRowStats(module, translate) {
  const json = JSON.stringify(module, null, 2);
  navigator.clipboard.writeText(json).then(() => {
    flash(translate("configs.moduleTelemetry.table.copySuccess", "Row stats copied to clipboard."), "success");
  }).catch((err) => {
    logger.warn("clipboard write failed", { component: "ModuleTelemetryPanel", err });
    flash(translate("configs.moduleTelemetry.table.copyError", "Failed to copy row stats."), "error");
  });
}
function TopOperationsBreakdown({
  operations,
  translate
}) {
  return /* @__PURE__ */ jsxs("div", { className: "w-[26rem] max-w-[80vw] space-y-2", children: [
    /* @__PURE__ */ jsx("div", { className: "text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: translate("configs.moduleTelemetry.table.topOperationsBreakdown", "Top operations in this range") }),
    /* @__PURE__ */ jsxs("table", { className: "w-full text-xs", children: [
      /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "text-muted-foreground", children: [
        /* @__PURE__ */ jsx("th", { className: "pb-1 pr-2 text-left font-medium", children: translate("configs.moduleTelemetry.table.topOperation", "Top operation") }),
        /* @__PURE__ */ jsx("th", { className: "pb-1 pr-2 text-right font-medium", children: translate("configs.moduleTelemetry.table.calls", "Calls") }),
        /* @__PURE__ */ jsx("th", { className: "pb-1 pr-2 text-right font-medium", children: translate("configs.moduleTelemetry.table.worstP95", "Worst p95") }),
        /* @__PURE__ */ jsx("th", { className: "pb-1 pr-2 text-right font-medium", children: translate("configs.moduleTelemetry.table.cpu", "CPU") }),
        /* @__PURE__ */ jsx("th", { className: "pb-1 pr-2 text-right font-medium", children: translate("configs.moduleTelemetry.table.heap", "Heap growth") }),
        /* @__PURE__ */ jsx("th", { className: "pb-1 text-right font-medium", children: translate("configs.moduleTelemetry.table.rss", "RSS growth") })
      ] }) }),
      /* @__PURE__ */ jsx("tbody", { children: operations.map((operation, index) => /* @__PURE__ */ jsxs("tr", { className: "border-t border-border/50", children: [
        /* @__PURE__ */ jsxs("td", { className: "py-1 pr-2 align-top", children: [
          /* @__PURE__ */ jsx("div", { className: "font-medium text-foreground", children: operation.operation }),
          /* @__PURE__ */ jsxs("div", { className: "text-muted-foreground", children: [
            operation.surface,
            operation.errors > 0 ? ` \xB7 ${translate("configs.moduleTelemetry.table.errorCount", "{{count}} errors", { count: operation.errors })}` : ""
          ] }),
          operation.concurrentCalls > 0 ? /* @__PURE__ */ jsx("div", { className: "text-muted-foreground", children: translate(
            "configs.moduleTelemetry.table.concurrentOverlap",
            "{{percent}}% overlapped other calls \u2014 CPU/heap/RSS less certain",
            { percent: Math.round(operation.concurrentCalls / Math.max(operation.calls, 1) * 100) }
          ) }) : null
        ] }),
        /* @__PURE__ */ jsx("td", { className: "py-1 pr-2 text-right align-top", children: formatCount(operation.calls) }),
        /* @__PURE__ */ jsx("td", { className: "py-1 pr-2 text-right align-top", children: formatMs(operation.p95DurationMs) }),
        /* @__PURE__ */ jsx("td", { className: "py-1 pr-2 text-right align-top", children: formatMs(operation.totalCpuUserMs + operation.totalCpuSystemMs) }),
        /* @__PURE__ */ jsx("td", { className: "py-1 pr-2 text-right align-top", children: formatBytes(operation.positiveHeapDeltaBytes) }),
        /* @__PURE__ */ jsx("td", { className: "py-1 text-right align-top", children: formatBytes(operation.positiveRssDeltaBytes) })
      ] }, `${operation.surface}\0${operation.operation}\0${index}`)) })
    ] })
  ] });
}
function RangeModuleTable({
  modules,
  translate
}) {
  if (!modules.length) {
    return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: translate("configs.moduleTelemetry.modules.empty", "No module activity has been recorded for this range yet.") });
  }
  const groups = groupRangeModules(modules);
  return /* @__PURE__ */ jsx(TooltipProvider, { delayDuration: 200, children: /* @__PURE__ */ jsx("div", { className: "overflow-x-auto", children: /* @__PURE__ */ jsxs("table", { className: "w-full min-w-[980px] text-sm", children: [
    /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "text-xs uppercase tracking-wide text-muted-foreground", children: [
      /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left", children: translate("configs.moduleTelemetry.table.module", "Module") }),
      /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left", children: translate("configs.moduleTelemetry.table.stage", "Stage") }),
      /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left", children: /* @__PURE__ */ jsx(
        MetricTitle,
        {
          label: translate("configs.moduleTelemetry.table.signals", "Signals"),
          tooltip: translate(
            "configs.moduleTelemetry.table.signalsTooltip",
            "Flags a module whose CPU, heap growth, RSS growth, or errors average at or above a heavy-usage threshold per 5-minute bucket it was active in during this range. This is a per-bucket average, not a raw range-wide total, so the same sustained workload looks the same regardless of the selected time range."
          )
        }
      ) }),
      /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right", children: translate("configs.moduleTelemetry.table.calls", "Calls") }),
      /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right", children: translate("configs.moduleTelemetry.table.worstP95", "Worst p95") }),
      /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right", children: translate("configs.moduleTelemetry.table.cpu", "CPU") }),
      /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right", children: translate("configs.moduleTelemetry.table.heap", "Heap growth") }),
      /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right", children: translate("configs.moduleTelemetry.table.rss", "RSS growth") }),
      /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left", children: translate("configs.moduleTelemetry.table.topOperation", "Top operation") }),
      /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right", children: translate("configs.moduleTelemetry.table.actions", "Actions") })
    ] }) }),
    /* @__PURE__ */ jsx("tbody", { children: groups.map((group) => /* @__PURE__ */ jsx(React.Fragment, { children: group.stages.map((module, stageIndex) => {
      const topOperation = module.topOperations[0];
      const topSurface = module.surfaces[0];
      return /* @__PURE__ */ jsxs(
        "tr",
        {
          className: stageIndex === 0 ? "border-t" : "border-t border-border/50",
          children: [
            stageIndex === 0 ? /* @__PURE__ */ jsx("td", { className: "w-56 px-3 py-3 align-top", rowSpan: group.stages.length, children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
              /* @__PURE__ */ jsx("span", { className: "font-medium", children: group.moduleId }),
              /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: translate(
                "configs.moduleTelemetry.table.stageCount",
                "{{count}} stage rows",
                { count: group.stages.length }
              ) })
            ] }) }) : null,
            /* @__PURE__ */ jsx("td", { className: "px-3 py-3 align-top", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
              /* @__PURE__ */ jsx(StageBadge, { stage: module.stage, translate }),
              /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: topSurface ? translate(
                "configs.moduleTelemetry.table.surfaceSummary",
                "{{surface}} \xB7 {{calls}} calls",
                { surface: topSurface.surface, calls: topSurface.calls }
              ) : translate("configs.moduleTelemetry.table.noSurface", "No surface data") })
            ] }) }),
            /* @__PURE__ */ jsx("td", { className: "px-3 py-3 align-top", children: /* @__PURE__ */ jsx(CandidateBadges, { module, translate }) }),
            /* @__PURE__ */ jsx("td", { className: "px-3 py-3 align-top text-right", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
              /* @__PURE__ */ jsx("span", { children: formatCount(module.calls) }),
              module.errors > 0 ? /* @__PURE__ */ jsx("span", { className: "text-xs text-destructive", children: translate("configs.moduleTelemetry.table.errorCount", "{{count}} errors", { count: module.errors }) }) : null
            ] }) }),
            /* @__PURE__ */ jsx("td", { className: "px-3 py-3 align-top text-right", children: formatMs(module.p95DurationMs) }),
            /* @__PURE__ */ jsx("td", { className: "px-3 py-3 align-top text-right", children: formatMs(module.totalCpuMs) }),
            /* @__PURE__ */ jsx("td", { className: "px-3 py-3 align-top text-right", children: formatBytes(module.positiveHeapDeltaBytes) }),
            /* @__PURE__ */ jsx("td", { className: "px-3 py-3 align-top text-right", children: formatBytes(module.positiveRssDeltaBytes) }),
            /* @__PURE__ */ jsx("td", { className: "px-3 py-3 align-top", children: topOperation ? /* @__PURE__ */ jsxs(Tooltip, { delayDuration: 200, children: [
              /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxs("div", { className: "flex cursor-default flex-col gap-1", children: [
                /* @__PURE__ */ jsx("span", { className: "font-medium underline decoration-dotted decoration-muted-foreground underline-offset-2", children: topOperation.operation }),
                /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: translate(
                  "configs.moduleTelemetry.table.topOperationMeta",
                  "{{surface}} \xB7 {{cpu}} CPU \xB7 {{calls}} calls",
                  {
                    surface: topOperation.surface,
                    cpu: formatMs(topOperation.totalCpuUserMs + topOperation.totalCpuSystemMs),
                    calls: topOperation.calls
                  }
                ) })
              ] }) }),
              /* @__PURE__ */ jsx(TooltipContent, { side: "left", align: "start", variant: "light", className: "max-w-none p-3", children: /* @__PURE__ */ jsx(TopOperationsBreakdown, { operations: module.topOperations, translate }) })
            ] }) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: translate("configs.moduleTelemetry.table.none", "None") }) }),
            /* @__PURE__ */ jsx("td", { className: "px-3 py-3 align-top text-right", children: /* @__PURE__ */ jsx(
              SimpleTooltip,
              {
                content: translate("configs.moduleTelemetry.table.copyStats", "Copy row stats for debugging"),
                side: "top",
                align: "center",
                variant: "light",
                children: /* @__PURE__ */ jsx(
                  IconButton,
                  {
                    type: "button",
                    variant: "ghost",
                    size: "sm",
                    "aria-label": translate("configs.moduleTelemetry.table.copyStats", "Copy row stats for debugging"),
                    onClick: () => copyRowStats(module, translate),
                    children: /* @__PURE__ */ jsx(Copy, { className: "h-4 w-4", "aria-hidden": "true" })
                  }
                )
              }
            ) })
          ]
        },
        `${module.moduleId}:${module.stage}`
      );
    }) }, group.moduleId)) })
  ] }) }) });
}
function RangeModuleSection({
  modules,
  range,
  bucketIntervalMs,
  bucketsLabel,
  translate
}) {
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4 rounded-lg border bg-card p-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
      /* @__PURE__ */ jsx("h3", { className: "text-base font-semibold", children: translate("configs.moduleTelemetry.modules.title", "Modules") }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: translate(
        "configs.moduleTelemetry.modules.description",
        "Aggregated module stats from {{from}} to now across {{buckets}}. Startup and running rows are separated.",
        {
          from: formatRangeBoundary(range.startMs),
          buckets: bucketsLabel
        }
      ) }),
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: translate(
        "configs.moduleTelemetry.modules.interval",
        "Startup is the first {{interval}} bucket after telemetry starts. Later buckets are running.",
        { interval: formatBucketInterval(bucketIntervalMs) }
      ) })
    ] }),
    /* @__PURE__ */ jsx(RangeModuleTable, { modules, translate })
  ] });
}
function ModuleTelemetryPanel() {
  const t = useT();
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [state, setState] = React.useState({ loading: true, error: null, report: null });
  const [clearingTelemetry, setClearingTelemetry] = React.useState(false);
  const rangeParam = searchParams.get("range");
  const [usageRangePreset, setUsageRangePreset] = React.useState(() => readUsageRangePreset(searchParams));
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: "configs-module-telemetry",
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const clearMutationContext = React.useMemo(
    () => ({
      formId: "configs-module-telemetry",
      resourceKind: "configs.moduleTelemetry",
      retryLastMutation
    }),
    [retryLastMutation]
  );
  const loadReport = React.useCallback(async () => {
    setState((current) => ({ ...current, loading: true, error: null }));
    try {
      const report2 = await readApiResultOrThrow(API_PATH, void 0, {
        errorMessage: t("configs.moduleTelemetry.loadError", "Failed to load module telemetry.")
      });
      setState({ loading: false, error: null, report: report2 });
    } catch (error) {
      const message = error instanceof Error && error.message ? error.message : t("configs.moduleTelemetry.loadError", "Failed to load module telemetry.");
      setState({ loading: false, error: message, report: null });
    }
  }, [t]);
  React.useEffect(() => {
    loadReport().catch(() => {
    });
  }, [loadReport]);
  React.useEffect(() => {
    const nextRange = readUsageRangePreset(searchParams);
    setUsageRangePreset((current) => current === nextRange ? current : nextRange);
  }, [rangeParam, searchParams]);
  const handleUsageRangeChange = React.useCallback((value) => {
    setUsageRangePreset(value);
    const params = new URLSearchParams(searchParams.toString());
    params.set("range", value);
    const query = params.toString();
    router.replace(query ? `${pathname}?${query}` : pathname, { scroll: false });
  }, [pathname, router, searchParams]);
  const handleRefresh = React.useCallback(() => {
    loadReport().catch(() => {
    });
  }, [loadReport]);
  const handleClearTelemetry = React.useCallback(async () => {
    if (clearingTelemetry) return;
    const confirmed = await confirm({
      title: t("configs.moduleTelemetry.clear.confirmTitle", "Clear all telemetry data?"),
      text: t(
        "configs.moduleTelemetry.clear.confirmText",
        "This removes current module telemetry and local process telemetry files for this development instance."
      ),
      confirmText: t("configs.moduleTelemetry.clear.confirmButton", "Clear telemetry"),
      variant: "destructive"
    });
    if (!confirmed) return;
    setClearingTelemetry(true);
    try {
      await runMutation({
        // optimistic-lock-exempt: clears in-process/dev-only telemetry buckets and
        // local process telemetry files — there is no versioned entity (no updated_at)
        // to lock against, so no expected-version header applies.
        operation: () => readApiResultOrThrow(
          API_PATH,
          { method: "DELETE" },
          {
            errorMessage: t("configs.moduleTelemetry.clear.error", "Failed to clear module telemetry."),
            allowNullResult: true
          }
        ),
        context: clearMutationContext,
        mutationPayload: {}
      });
      await loadReport();
      flash(t("configs.moduleTelemetry.clear.success", "Module telemetry data cleared."), "success");
    } catch (error) {
      const message = error instanceof Error && error.message ? error.message : t("configs.moduleTelemetry.clear.error", "Failed to clear module telemetry.");
      flash(message, "error");
    } finally {
      setClearingTelemetry(false);
    }
  }, [clearMutationContext, clearingTelemetry, confirm, loadReport, runMutation, t]);
  if (state.loading) {
    return /* @__PURE__ */ jsxs("section", { className: "space-y-3 rounded-lg border bg-background p-6", children: [
      /* @__PURE__ */ jsxs("header", { className: "space-y-1", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("configs.moduleTelemetry.title", "Module telemetry") }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("configs.moduleTelemetry.description", "Preview module-level resource attribution collected in this process.") })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
        /* @__PURE__ */ jsx(Spinner, { className: "h-4 w-4" }),
        t("configs.moduleTelemetry.loading", "Loading module telemetry\u2026")
      ] })
    ] });
  }
  if (state.error) {
    return /* @__PURE__ */ jsxs("section", { className: "space-y-3 rounded-lg border bg-background p-6", children: [
      /* @__PURE__ */ jsxs("header", { className: "space-y-1", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("configs.moduleTelemetry.title", "Module telemetry") }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("configs.moduleTelemetry.description", "Preview module-level resource attribution collected in this process.") })
      ] }),
      /* @__PURE__ */ jsx(ErrorMessage, { label: state.error }),
      /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: () => loadReport().catch(() => {
      }), children: t("configs.moduleTelemetry.retry", "Retry") })
    ] });
  }
  const report = state.report;
  if (!report) return null;
  const usageRange = resolveUsageRange(usageRangePreset, report.buckets ?? [], report.startedAt);
  const rangeBuckets = bucketsInRange(report.buckets ?? [], usageRange);
  const rangeModules = aggregateRangeModules(rangeBuckets, report.thresholds);
  const bucketsLabel = bucketCountLabel(rangeBuckets, report.bucketIntervalMs, t);
  const telemetryStartedAtMs = firstAvailableTelemetryMs(report.buckets ?? [], Date.parse(report.startedAt), Date.now());
  return /* @__PURE__ */ jsxs("section", { className: "space-y-6 rounded-lg border bg-background p-6", children: [
    /* @__PURE__ */ jsxs("header", { className: "flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("configs.moduleTelemetry.title", "Module telemetry") }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("configs.moduleTelemetry.description", "Preview module-level resource attribution collected in this process.") }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
          "configs.moduleTelemetry.generatedAt",
          "Report generated {{timestamp}}",
          { timestamp: new Date(report.generatedAt).toLocaleString() }
        ) }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
          "configs.moduleTelemetry.startedAt",
          "Collecting since {{timestamp}}",
          { timestamp: new Date(telemetryStartedAtMs).toLocaleString() }
        ) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-2", children: [
        report.canClearTelemetry ? /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "destructive-outline",
            onClick: () => {
              void handleClearTelemetry();
            },
            disabled: clearingTelemetry,
            children: [
              /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4", "aria-hidden": "true" }),
              clearingTelemetry ? t("configs.moduleTelemetry.clear.clearing", "Clearing...") : t("configs.moduleTelemetry.clear.button", "Clear all telemetry data")
            ]
          }
        ) : null,
        /* @__PURE__ */ jsxs(Button, { type: "button", variant: "outline", onClick: handleRefresh, children: [
          /* @__PURE__ */ jsx(RefreshCw, { className: "h-4 w-4", "aria-hidden": "true" }),
          t("configs.moduleTelemetry.refresh", "Refresh")
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsx(
      RangeOverview,
      {
        buckets: rangeBuckets,
        modules: rangeModules,
        range: usageRange,
        rangePreset: usageRangePreset,
        onRangePresetChange: handleUsageRangeChange,
        bucketIntervalMs: report.bucketIntervalMs,
        translate: t
      }
    ),
    /* @__PURE__ */ jsx(
      RangeModuleSection,
      {
        modules: rangeModules,
        range: usageRange,
        bucketIntervalMs: report.bucketIntervalMs,
        bucketsLabel,
        translate: t
      }
    ),
    ConfirmDialogElement
  ] });
}
var ModuleTelemetryPanel_default = ModuleTelemetryPanel;
export {
  ModuleTelemetryPanel,
  ModuleTelemetryPanel_default as default
};
//# sourceMappingURL=ModuleTelemetryPanel.js.map
