"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { z } from "zod";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { WebhookSetupGuide } from "@open-mercato/ui/backend/WebhookSetupGuide";
import { InjectionSpot, useInjectionWidgets } from "@open-mercato/ui/backend/injection/InjectionSpot";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { FormHeader } from "@open-mercato/ui/backend/forms";
import { Card, CardHeader, CardTitle, CardContent } from "@open-mercato/ui/primitives/card";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { Button } from "@open-mercato/ui/primitives/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { Switch } from "@open-mercato/ui/primitives/switch";
import { PasswordInput } from "@open-mercato/ui/primitives/password-input";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@open-mercato/ui/primitives/tabs";
import { JsonDisplay } from "@open-mercato/ui/backend/JsonDisplay";
import { apiCall, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { raiseCrudError } from "@open-mercato/ui/backend/utils/serverErrors";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { cn } from "@open-mercato/shared/lib/utils";
import {
  LEGACY_INTEGRATION_DETAIL_TABS_SPOT_ID
} from "@open-mercato/shared/modules/integrations/types";
import { LoadingMessage, ErrorMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { LogList } from "@open-mercato/ui/backend/LogList";
import { Activity, AlertTriangle, Bell, Calendar, CheckCircle2, CreditCard, FileText, FileX, HardDrive, Key, MessageSquare, RefreshCw, Settings, Truck, Webhook, XCircle, Zap } from "lucide-react";
import { EmptyState } from "@open-mercato/ui/primitives/empty-state";
import { IntegrationScheduleTab } from "../../../../data_sync/components/IntegrationScheduleTab.js";
import {
  buildIntegrationDetailInjectedTabs,
  filterIntegrationDetailWidgetsByKind,
  resolveIntegrationDetailWidgetSpotId,
  resolveRequestedIntegrationDetailTab
} from "../detail-page-widgets.js";
import {
  refreshIntegrationDetailPanels,
  refreshIntegrationRunActivityPanels
} from "../detail-page-refresh.js";
import { isValidCredentialUrl } from "../../../lib/credentials-field-validation.js";
const UNSUPPORTED_CREDENTIAL_FIELD_TYPES = /* @__PURE__ */ new Set(["oauth", "ssh_keypair"]);
function isEditableCredentialField(field) {
  return !UNSUPPORTED_CREDENTIAL_FIELD_TYPES.has(field.type);
}
const LOG_LEVEL_STYLES = {
  info: "bg-status-info-bg text-status-info-text",
  warn: "bg-status-warning-bg text-status-warning-text",
  error: "bg-status-error-bg text-status-error-text"
};
const HEALTH_STATUS_STYLES = {
  healthy: "bg-status-success-bg text-status-success-text",
  degraded: "bg-status-warning-bg text-status-warning-text",
  unhealthy: "bg-status-error-bg text-status-error-text",
  unconfigured: "bg-status-neutral-bg text-status-neutral-text"
};
const HEALTH_STATUS_ICONS = {
  healthy: CheckCircle2,
  degraded: AlertTriangle,
  unhealthy: XCircle,
  unconfigured: AlertTriangle
};
function formatRunStatusLabel(status, t) {
  switch (status) {
    case "pending":
      return t("integrations.detail.runActivity.status.pending", "Pending");
    case "running":
      return t("integrations.detail.runActivity.status.running", "Running");
    case "completed":
      return t("integrations.detail.runActivity.status.completed", "Completed");
    case "failed":
      return t("integrations.detail.runActivity.status.failed", "Failed");
    case "cancelled":
      return t("integrations.detail.runActivity.status.cancelled", "Cancelled");
    default:
      return status;
  }
}
function RunActivityStrip({
  run,
  refreshedAt,
  isRefreshing,
  onRefresh,
  t
}) {
  if (!run) return null;
  const progress = typeof run.progressJob?.progressPercent === "number" ? run.progressJob.progressPercent : 0;
  const processed = typeof run.progressJob?.processedCount === "number" ? run.progressJob.processedCount : 0;
  const total = typeof run.progressJob?.totalCount === "number" ? run.progressJob.totalCount : null;
  const statusClass = run.status === "completed" ? "border-status-success-border bg-status-success-bg text-status-success-text" : run.status === "failed" ? "border-status-error-border bg-status-error-bg text-status-error-text" : run.status === "cancelled" ? "border-status-neutral-border bg-status-neutral-bg text-status-neutral-text" : "border-status-info-border bg-status-info-bg text-status-info-text";
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-3 rounded-lg border bg-muted/20 px-4 py-3 text-sm", children: [
    /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: cn("gap-1.5", statusClass), children: [
      /* @__PURE__ */ jsx(RefreshCw, { className: cn("h-3.5 w-3.5", run.status === "running" ? "animate-spin" : "") }),
      formatRunStatusLabel(run.status, t)
    ] }),
    /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
      t("integrations.detail.runActivity.processed", "Processed"),
      ": ",
      /* @__PURE__ */ jsxs("span", { className: "font-medium text-foreground", children: [
        processed,
        total !== null ? ` / ${total}` : ""
      ] })
    ] }),
    /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
      t("integrations.detail.runActivity.progress", "Progress"),
      ": ",
      /* @__PURE__ */ jsxs("span", { className: "font-medium text-foreground", children: [
        progress,
        "%"
      ] })
    ] }),
    refreshedAt ? /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
      t("integrations.detail.runActivity.lastRefreshed", "Last refreshed"),
      ": ",
      new Date(refreshedAt).toLocaleTimeString()
    ] }) : null,
    /* @__PURE__ */ jsxs(Button, { type: "button", variant: "outline", size: "sm", className: "ml-auto", onClick: onRefresh, disabled: isRefreshing, children: [
      isRefreshing ? /* @__PURE__ */ jsx(Spinner, { className: "mr-2 h-4 w-4" }) : /* @__PURE__ */ jsx(RefreshCw, { className: "mr-2 h-4 w-4" }),
      t("integrations.detail.runActivity.refresh", "Refresh")
    ] })
  ] });
}
function DetailLogSparkline({ counts, className }) {
  const max = Math.max(1, ...counts);
  const w = 120;
  const h = 36;
  const step = counts.length > 1 ? w / (counts.length - 1) : w;
  const points = counts.map((count, index) => {
    const x = index * step;
    const y = h - count / max * (h - 4) - 2;
    return `${x},${y}`;
  }).join(" ");
  return /* @__PURE__ */ jsx("svg", { width: w, height: h, className, "aria-hidden": true, children: /* @__PURE__ */ jsx(
    "polyline",
    {
      fill: "none",
      stroke: "currentColor",
      strokeWidth: "1.5",
      strokeLinejoin: "round",
      strokeLinecap: "round",
      points,
      className: "text-muted-foreground/80"
    }
  ) });
}
const CATEGORY_ICONS = {
  payment: CreditCard,
  shipping: Truck,
  data_sync: RefreshCw,
  communication: MessageSquare,
  notification: Bell,
  storage: HardDrive,
  webhook: Webhook
};
function resolveRouteId(value) {
  if (Array.isArray(value)) return value[0];
  return value;
}
function resolvePathnameId(pathname) {
  const parts = pathname.split("/").filter(Boolean);
  const integrationId = parts.at(-1);
  if (!integrationId || integrationId === "integrations" || integrationId === "bundle") return void 0;
  return decodeURIComponent(integrationId);
}
function buildCredentialFields(credFields) {
  return credFields.map((field) => {
    const shared = {
      id: field.key,
      label: field.label,
      description: field.helpDetails ? /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
        field.helpText ? /* @__PURE__ */ jsx("div", { children: field.helpText }) : null,
        /* @__PURE__ */ jsx(WebhookSetupGuide, { guide: field.helpDetails, buttonLabel: "Show details" })
      ] }) : field.helpText,
      placeholder: field.placeholder,
      required: field.required,
      visibleWhen: field.visibleWhen
    };
    if (field.type === "secret") {
      return {
        ...shared,
        type: "custom",
        component: ({ id, value, setValue, disabled }) => /* @__PURE__ */ jsx(
          PasswordInput,
          {
            id,
            placeholder: field.placeholder,
            value: typeof value === "string" ? value : "",
            onChange: (event) => setValue(event.target.value),
            disabled
          }
        )
      };
    }
    if (field.type === "select" && field.options) {
      return {
        ...shared,
        type: "select",
        options: field.options
      };
    }
    if (field.type === "boolean") {
      return {
        ...shared,
        type: "checkbox"
      };
    }
    return {
      ...shared,
      type: "text"
    };
  });
}
function isHealthLog(log) {
  return log.message === "Health check passed" || log.message.startsWith("Health check:");
}
function extractHealthDetails(payload) {
  if (!payload) return {};
  return Object.fromEntries(
    Object.entries(payload).filter(([key, value]) => key !== "status" && key !== "message" && value !== void 0 && value !== null)
  );
}
function formatHealthValue(value) {
  if (typeof value === "boolean") return value ? "Yes" : "No";
  if (typeof value === "string") return value;
  if (typeof value === "number") return String(value);
  if (value instanceof Date) return value.toLocaleString();
  return JSON.stringify(value);
}
function formatTypeLabel(value) {
  return value.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 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 formatLogPrimitiveValue(value) {
  if (value === null) return "None";
  if (typeof value === "boolean") return value ? "Yes" : "No";
  return String(value);
}
function isAkeneoSettingsTab(tab) {
  return tab.id.includes("sync_akeneo") || tab.label.toLowerCase().includes("akeneo");
}
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 IntegrationDetailPage({ params }) {
  const pathname = usePathname();
  const router = useRouter();
  const searchParams = useSearchParams();
  const integrationId = resolveRouteId(params?.id) ?? resolvePathnameId(pathname);
  const t = useT();
  const [detail, setDetail] = React.useState(null);
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const [credValues, setCredValues] = React.useState({});
  const [credentialsUpdatedAt, setCredentialsUpdatedAt] = React.useState(null);
  const [credentialsFormKey, setCredentialsFormKey] = React.useState(0);
  const [isSavingCredentials, setIsSavingCredentials] = React.useState(false);
  const [logs, setLogs] = React.useState([]);
  const [logLevel, setLogLevel] = React.useState("");
  const [isLoadingLogs, setIsLoadingLogs] = React.useState(false);
  const [isCheckingHealth, setIsCheckingHealth] = React.useState(false);
  const [isTogglingState, setIsTogglingState] = React.useState(false);
  const [latestHealthResult, setLatestHealthResult] = React.useState(null);
  const [activeRunDetail, setActiveRunDetail] = React.useState(null);
  const [activeRunRefreshedAt, setActiveRunRefreshedAt] = React.useState(null);
  const [isRefreshingRunActivity, setIsRefreshingRunActivity] = React.useState(false);
  const [activeTab, setActiveTab] = React.useState("credentials");
  const credentialsFormId = React.useId();
  const resolveCurrentIntegrationId = React.useCallback(() => {
    return integrationId ?? (typeof window !== "undefined" ? resolvePathnameId(window.location.pathname) : void 0);
  }, [integrationId]);
  const loadDetail = React.useCallback(async (options) => {
    const showLoading = options?.showLoading ?? true;
    const currentIntegrationId = resolveCurrentIntegrationId();
    if (!currentIntegrationId) {
      if (showLoading) setIsLoading(false);
      if (showLoading) setError(t("integrations.detail.loadError", "Failed to load integration"));
      return;
    }
    if (showLoading) setError(null);
    if (showLoading) setIsNotFound(false);
    if (showLoading) setIsLoading(true);
    try {
      const call = await apiCall(
        `/api/integrations/${encodeURIComponent(currentIntegrationId)}`,
        void 0,
        { fallback: null }
      );
      if (!call.ok || !call.result) {
        if (call.status === 404) {
          if (showLoading) setIsNotFound(true);
        } else {
          if (showLoading) setError(t("integrations.detail.loadError", "Failed to load integration"));
        }
        if (showLoading) setIsLoading(false);
        return;
      }
      setDetail(call.result);
      setError(null);
      if (showLoading) setIsLoading(false);
    } catch {
      if (showLoading) setError(t("integrations.detail.loadError", "Failed to load integration"));
      if (showLoading) setIsLoading(false);
    }
  }, [resolveCurrentIntegrationId, t]);
  const loadCredentials = React.useCallback(async () => {
    const currentIntegrationId = resolveCurrentIntegrationId();
    if (!currentIntegrationId) return;
    const call = await apiCall(
      `/api/integrations/${encodeURIComponent(currentIntegrationId)}/credentials`,
      void 0,
      { fallback: null }
    );
    if (call.ok && call.result) {
      setCredentialsUpdatedAt(call.result.updatedAt ?? null);
    }
    if (call.ok && call.result?.credentials) {
      const next = { ...call.result.credentials };
      if (currentIntegrationId === "storage_s3") {
        const authMode = next.authMode;
        if (authMode !== "access_keys" && authMode !== "ambient") {
          const hasKeys = Boolean(next.accessKeyId || next.secretAccessKey);
          next.authMode = hasKeys ? "access_keys" : "ambient";
        }
      }
      setCredValues(next);
      setCredentialsFormKey((current) => current + 1);
    }
  }, [resolveCurrentIntegrationId]);
  const loadLogs = React.useCallback(async () => {
    const currentIntegrationId = resolveCurrentIntegrationId();
    if (!currentIntegrationId) return;
    setIsLoadingLogs(true);
    const params2 = new URLSearchParams({ integrationId: currentIntegrationId, pageSize: "50" });
    if (logLevel) params2.set("level", logLevel);
    const call = await apiCall(
      `/api/integrations/logs?${params2.toString()}`,
      void 0,
      { fallback: { items: [] } }
    );
    if (call.ok && call.result) {
      setLogs(call.result.items);
    }
    setIsLoadingLogs(false);
  }, [logLevel, resolveCurrentIntegrationId]);
  const detailWidgetSpotId = React.useMemo(
    () => resolveIntegrationDetailWidgetSpotId(detail?.integration ?? null, LEGACY_INTEGRATION_DETAIL_TABS_SPOT_ID),
    [detail?.integration]
  );
  const mutationContextId = React.useMemo(
    () => `integrations.detail:${integrationId ?? "unknown"}`,
    [integrationId]
  );
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId,
    spotId: detailWidgetSpotId
  });
  const refreshDetail = React.useCallback(async () => {
    await refreshIntegrationDetailPanels({ loadDetail, loadCredentials });
  }, [loadCredentials, loadDetail]);
  const refreshLogs = React.useCallback(async () => {
    await loadLogs();
  }, [loadLogs]);
  const refreshHealthSnapshot = React.useCallback(async () => {
    await loadDetail({ showLoading: false });
  }, [loadDetail]);
  const runIdFromUrl = searchParams?.get("runId") ?? null;
  const refreshRunActivity = React.useCallback(async (options) => {
    if (!runIdFromUrl) {
      setActiveRunDetail(null);
      setActiveRunRefreshedAt(null);
      return null;
    }
    if (options?.showLoading) setIsRefreshingRunActivity(true);
    try {
      const [call] = await Promise.all([
        apiCall(
          `/api/data_sync/runs/${encodeURIComponent(runIdFromUrl)}`,
          void 0,
          { fallback: null }
        ),
        refreshIntegrationRunActivityPanels({ loadLogs, loadDetail })
      ]);
      if (call.ok && call.result) {
        setActiveRunDetail(call.result);
        setActiveRunRefreshedAt((/* @__PURE__ */ new Date()).toISOString());
        return call.result;
      }
      return null;
    } finally {
      if (options?.showLoading) setIsRefreshingRunActivity(false);
    }
  }, [loadDetail, loadLogs, runIdFromUrl]);
  const injectionContext = React.useMemo(
    () => ({
      formId: mutationContextId,
      integrationDetailWidgetSpotId: detailWidgetSpotId,
      resourceKind: "integrations.integration",
      resourceId: integrationId ?? detail?.integration.id,
      integrationId: integrationId ?? detail?.integration.id,
      integration: detail?.integration ?? null,
      detail,
      state: detail?.state ?? null,
      credentialValues: credValues,
      latestHealthResult,
      activeTab,
      setActiveTab,
      refreshDetail,
      refreshLogs,
      refreshHealthSnapshot,
      retryLastMutation
    }),
    [
      activeTab,
      credValues,
      detail,
      detailWidgetSpotId,
      integrationId,
      latestHealthResult,
      mutationContextId,
      refreshDetail,
      refreshHealthSnapshot,
      refreshLogs,
      retryLastMutation
    ]
  );
  const { widgets: detailWidgets } = useInjectionWidgets(detailWidgetSpotId, {
    context: injectionContext,
    triggerOnLoad: true
  });
  const stackedDetailWidgets = React.useMemo(
    () => filterIntegrationDetailWidgetsByKind(detailWidgets, "stack"),
    [detailWidgets]
  );
  const groupedDetailWidgets = React.useMemo(
    () => filterIntegrationDetailWidgetsByKind(detailWidgets, "group"),
    [detailWidgets]
  );
  const injectedTabs = React.useMemo(
    () => buildIntegrationDetailInjectedTabs(
      detailWidgets,
      (widget) => widget.placement?.groupLabel ? t(widget.placement.groupLabel, widget.module.metadata.title ?? widget.widgetId) : widget.module.metadata.title ?? widget.widgetId
    ),
    [detailWidgets, t]
  );
  const hasDataSyncScheduleTab = Boolean(
    detail?.integration.hub === "data_sync" && detail?.integration.providerKey && detail.integration.providerKey.trim().length > 0
  );
  const runMutationWithContext = React.useCallback(
    async ({
      operation,
      mutationPayload,
      actionId,
      tabId,
      operationType = "update"
    }) => {
      return runMutation({
        operation,
        mutationPayload,
        context: {
          ...injectionContext,
          operation: operationType,
          actionId,
          activeTab: tabId ?? activeTab
        }
      });
    },
    [activeTab, injectionContext, runMutation]
  );
  React.useEffect(() => {
    void loadDetail();
  }, [loadDetail]);
  React.useEffect(() => {
    void loadCredentials();
  }, [loadCredentials]);
  React.useEffect(() => {
    void loadLogs();
  }, [loadLogs]);
  const handleToggleState = React.useCallback(async (enabled) => {
    const currentIntegrationId = resolveCurrentIntegrationId();
    if (!currentIntegrationId) return;
    setIsTogglingState(true);
    try {
      const call = await runMutationWithContext({
        actionId: "toggle-state",
        mutationPayload: { integrationId: currentIntegrationId, isEnabled: enabled },
        operation: () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(detail?.state.updatedAt),
          () => apiCall(`/api/integrations/${encodeURIComponent(currentIntegrationId)}/state`, {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ isEnabled: enabled })
          }, { fallback: null })
        )
      });
      if (call.ok) {
        setDetail((prev) => prev ? {
          ...prev,
          state: {
            ...prev.state,
            isEnabled: enabled,
            enabledAt: enabled ? (/* @__PURE__ */ new Date()).toISOString() : prev.state.enabledAt
          }
        } : prev);
        flash(t("integrations.detail.stateUpdated"), "success");
        void refreshDetail();
      } else {
        flash(t("integrations.detail.stateError"), "error");
      }
    } catch {
      flash(t("integrations.detail.stateError"), "error");
    } finally {
      setIsTogglingState(false);
    }
  }, [detail?.state.updatedAt, refreshDetail, resolveCurrentIntegrationId, runMutationWithContext, t]);
  const handleSaveCredentials = React.useCallback(async (values) => {
    const currentIntegrationId = resolveCurrentIntegrationId();
    if (!currentIntegrationId) return;
    setIsSavingCredentials(true);
    try {
      const sanitizedValues = { ...values };
      if (currentIntegrationId === "storage_s3") {
        const authMode = sanitizedValues.authMode;
        if (authMode !== "access_keys" && authMode !== "ambient") {
          const hasKeys = Boolean(sanitizedValues.accessKeyId || sanitizedValues.secretAccessKey);
          sanitizedValues.authMode = hasKeys ? "access_keys" : "ambient";
        }
        if (sanitizedValues.authMode === "ambient") {
          delete sanitizedValues.accessKeyId;
          delete sanitizedValues.secretAccessKey;
          delete sanitizedValues.sessionToken;
        }
      }
      const call = await runMutationWithContext({
        actionId: "save-credentials",
        tabId: "credentials",
        mutationPayload: { integrationId: currentIntegrationId, credentials: sanitizedValues },
        operation: () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(credentialsUpdatedAt),
          () => apiCall(`/api/integrations/${encodeURIComponent(currentIntegrationId)}/credentials`, {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ credentials: sanitizedValues })
          }, { fallback: null })
        )
      });
      if (call.ok) {
        setCredValues(sanitizedValues);
        setCredentialsFormKey((current) => current + 1);
        flash(t("integrations.detail.credentials.saved"), "success");
        void loadCredentials();
        return;
      }
      await raiseCrudError(
        call.response,
        t("integrations.detail.credentials.saveError", "Failed to save credentials")
      );
    } finally {
      setIsSavingCredentials(false);
    }
  }, [credentialsUpdatedAt, loadCredentials, resolveCurrentIntegrationId, runMutationWithContext, t]);
  const handleVersionChange = React.useCallback(async (version) => {
    const currentIntegrationId = resolveCurrentIntegrationId();
    if (!currentIntegrationId) return;
    try {
      const call = await runMutationWithContext({
        actionId: "change-version",
        tabId: "version",
        mutationPayload: { integrationId: currentIntegrationId, apiVersion: version },
        operation: () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(detail?.state.updatedAt),
          () => apiCall(`/api/integrations/${encodeURIComponent(currentIntegrationId)}/version`, {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ apiVersion: version })
          }, { fallback: null })
        )
      });
      if (call.ok) {
        setDetail((prev) => prev ? { ...prev, state: { ...prev.state, apiVersion: version } } : prev);
        flash(t("integrations.detail.version.saved"), "success");
        void refreshDetail();
      } else {
        flash(t("integrations.detail.version.saveError"), "error");
      }
    } catch {
      flash(t("integrations.detail.version.saveError"), "error");
    }
  }, [detail?.state.updatedAt, refreshDetail, resolveCurrentIntegrationId, runMutationWithContext, t]);
  const handleHealthCheck = React.useCallback(async () => {
    const currentIntegrationId = resolveCurrentIntegrationId();
    if (!currentIntegrationId) return;
    setIsCheckingHealth(true);
    try {
      const call = await runMutationWithContext({
        actionId: "run-health-check",
        tabId: "health",
        mutationPayload: { integrationId: currentIntegrationId },
        operation: () => apiCall(
          `/api/integrations/${encodeURIComponent(currentIntegrationId)}/health`,
          { method: "POST" },
          { fallback: null }
        )
      });
      const result = call.result;
      if (call.ok && result) {
        setLatestHealthResult(result);
        setDetail((prev) => prev ? {
          ...prev,
          healthStatus: result.status,
          state: {
            ...prev.state,
            lastHealthStatus: result.status === "unconfigured" ? prev.state.lastHealthStatus : result.status,
            lastHealthCheckedAt: result.status === "unconfigured" ? prev.state.lastHealthCheckedAt : result.checkedAt,
            lastHealthLatencyMs: result.latencyMs ?? prev.state.lastHealthLatencyMs
          }
        } : prev);
        void refreshLogs();
      } else {
        flash(t("integrations.detail.health.checkError"), "error");
      }
    } catch {
      flash(t("integrations.detail.health.checkError"), "error");
    } finally {
      setIsCheckingHealth(false);
    }
  }, [refreshLogs, resolveCurrentIntegrationId, runMutationWithContext, t]);
  const hasVersions = Boolean(detail?.integration.apiVersions?.length);
  const integration = detail?.integration ?? null;
  const state = detail?.state ?? null;
  const editableCredentialFields = React.useMemo(
    () => (detail?.integration.credentials?.fields ?? detail?.bundle?.credentials?.fields ?? []).filter(isEditableCredentialField),
    [detail?.bundle?.credentials?.fields, detail?.integration.credentials?.fields]
  );
  const credentialFormFields = React.useMemo(
    () => buildCredentialFields(editableCredentialFields),
    [editableCredentialFields]
  );
  const credentialSchema = React.useMemo(() => z.object({}).passthrough().superRefine((rawValues, ctx) => {
    const values = rawValues;
    editableCredentialFields.forEach((field) => {
      if (field.visibleWhen) {
        const targetValue = values[field.visibleWhen.field];
        if (targetValue !== field.visibleWhen.equals) return;
      }
      const value = values[field.key];
      if (field.type === "boolean") {
        if (value !== void 0 && value !== null && typeof value !== "boolean") {
          ctx.addIssue({
            code: z.ZodIssueCode.custom,
            path: [field.key],
            message: t("integrations.detail.credentials.validation.boolean", "Select a valid value.")
          });
        }
        if (field.required && typeof value !== "boolean") {
          ctx.addIssue({
            code: z.ZodIssueCode.custom,
            path: [field.key],
            message: t("integrations.detail.credentials.validation.required", "{field} is required.", { field: field.label })
          });
        }
        return;
      }
      if (value !== void 0 && value !== null && typeof value !== "string") {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: [field.key],
          message: t("integrations.detail.credentials.validation.text", "Enter a valid value.")
        });
        return;
      }
      const normalizedValue = typeof value === "string" ? value : "";
      if (field.required && normalizedValue.trim().length === 0) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: [field.key],
          message: t("integrations.detail.credentials.validation.required", "{field} is required.", { field: field.label })
        });
      }
      if (normalizedValue.length > 2e4) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: [field.key],
          message: t("integrations.detail.credentials.validation.tooLong", "Value is too long.")
        });
      }
      if (field.type === "url" && normalizedValue.trim().length > 0 && !isValidCredentialUrl(normalizedValue.trim())) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: [field.key],
          message: t("integrations.detail.credentials.validation.url", "{field} must be a valid http(s) URL.", { field: field.label })
        });
      }
      if (field.type === "select" && normalizedValue && field.options && !field.options.some((option) => option.value === normalizedValue)) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: [field.key],
          message: t("integrations.detail.credentials.validation.option", "Select one of the available options.")
        });
      }
    });
  }), [editableCredentialFields, t]);
  const latestHealthLog = React.useMemo(() => logs.find(isHealthLog) ?? null, [logs]);
  const latestOperationalLog = React.useMemo(
    () => logs.find((log) => typeof log.payload?.operationalStatus === "string" || typeof log.payload?.summary === "string") ?? null,
    [logs]
  );
  const healthMessage = latestHealthResult?.message ?? (typeof latestHealthLog?.payload?.message === "string" ? latestHealthLog.payload.message : typeof latestOperationalLog?.payload?.summary === "string" ? latestOperationalLog.payload.summary : null);
  const healthDetailsSource = latestHealthResult?.details ?? extractHealthDetails(latestHealthLog?.payload ?? latestOperationalLog?.payload);
  const healthDetails = latestHealthLog?.code ? { ...healthDetailsSource, code: latestHealthLog.code } : healthDetailsSource;
  const healthDetailEntries = Object.entries(healthDetails);
  const resolvedIntegration = detail?.integration ?? null;
  const resolvedState = detail?.state ?? null;
  const displayHealthStatus = latestHealthResult?.status ?? detail?.healthStatus ?? resolvedState?.lastHealthStatus ?? "unconfigured";
  const healthStatusDescription = displayHealthStatus && displayHealthStatus !== "unconfigured" ? t(
    `integrations.detail.health.meaning.${displayHealthStatus}`,
    displayHealthStatus === "healthy" ? "The provider responded successfully using the current credentials." : displayHealthStatus === "degraded" ? "The provider responded, but reported warnings or limited functionality." : integration?.id === "gateway_stripe" ? "Stripe rejected the last check. This usually means the secret key is invalid, missing required permissions, revoked, or Stripe was temporarily unavailable." : "The last check failed. This usually means invalid credentials, missing permissions, or a provider outage."
  ) : displayHealthStatus === "unconfigured" ? t(
    "integrations.detail.health.meaning.unconfigured",
    "Credentials or a health check are not configured, or the integration has not been probed yet."
  ) : null;
  const CategoryIcon = resolvedIntegration?.category ? CATEGORY_ICONS[resolvedIntegration.category] : null;
  const HealthStatusIcon = HEALTH_STATUS_ICONS[displayHealthStatus] ?? null;
  const prioritizedInjectedTabs = resolvedIntegration?.id === "sync_akeneo" ? [...injectedTabs].sort((left, right) => {
    const leftPriority = isAkeneoSettingsTab(left) ? 1 : 0;
    const rightPriority = isAkeneoSettingsTab(right) ? 1 : 0;
    if (leftPriority !== rightPriority) return rightPriority - leftPriority;
    return 0;
  }) : injectedTabs;
  const leadingInjectedTab = resolvedIntegration?.id === "sync_akeneo" ? prioritizedInjectedTabs.find(isAkeneoSettingsTab) ?? null : null;
  const trailingInjectedTabs = leadingInjectedTab ? prioritizedInjectedTabs.filter((tab) => tab.id !== leadingInjectedTab.id) : prioritizedInjectedTabs;
  const hiddenBuiltInTabs = new Set(resolvedIntegration?.detailPage?.hiddenTabs ?? []);
  const showCredentialsTab = !hiddenBuiltInTabs.has("credentials");
  const showVersionTab = hasVersions && !hiddenBuiltInTabs.has("version");
  const showDataSyncScheduleTab = hasDataSyncScheduleTab && !hiddenBuiltInTabs.has("data-sync-schedule");
  const showHealthTab = !hiddenBuiltInTabs.has("health");
  const showLogsTab = !hiddenBuiltInTabs.has("logs");
  const visibleTabIds = [
    ...showCredentialsTab ? ["credentials"] : [],
    ...leadingInjectedTab ? [leadingInjectedTab.id] : [],
    ...showVersionTab ? ["version"] : [],
    ...showDataSyncScheduleTab ? ["data-sync-schedule"] : [],
    ...showHealthTab ? ["health"] : [],
    ...showLogsTab ? ["logs"] : [],
    ...trailingInjectedTabs.map((tab) => tab.id)
  ];
  const StateIcon = resolvedState?.isEnabled ? CheckCircle2 : XCircle;
  const stateBadgeClass = resolvedState?.isEnabled ? "border-status-success-border bg-status-success-bg text-status-success-text" : "border-status-neutral-border bg-status-neutral-bg text-status-neutral-text";
  const showCredentialActions = showCredentialsTab && activeTab === "credentials" && credentialFormFields.length > 0;
  React.useEffect(() => {
    setActiveTab(resolveRequestedIntegrationDetailTab(searchParams?.get("tab"), visibleTabIds));
  }, [searchParams, visibleTabIds]);
  const handleTabChange = React.useCallback((nextValue) => {
    const currentIntegrationId = resolveCurrentIntegrationId();
    const nextTab = resolveRequestedIntegrationDetailTab(nextValue, visibleTabIds);
    setActiveTab(nextTab);
    if (!currentIntegrationId) return;
    const basePath = `/backend/integrations/${encodeURIComponent(currentIntegrationId)}`;
    const params2 = new URLSearchParams(searchParams?.toString() ?? "");
    if (nextTab === "credentials") params2.delete("tab");
    else params2.set("tab", nextTab);
    const query = params2.toString();
    router.replace(query ? `${basePath}?${query}` : basePath);
  }, [resolveCurrentIntegrationId, router, searchParams, visibleTabIds]);
  React.useEffect(() => {
    if (!runIdFromUrl) {
      setActiveRunDetail(null);
      setActiveRunRefreshedAt(null);
      return;
    }
    if (activeTab !== "logs" && activeTab !== "health") return;
    let cancelled = false;
    let timeoutId = null;
    const poll = async () => {
      const detail2 = await refreshRunActivity();
      if (cancelled) return;
      const status = detail2?.status ?? null;
      if (status === "pending" || status === "running") {
        timeoutId = setTimeout(() => {
          void poll();
        }, 4e3);
      }
    };
    void poll();
    return () => {
      cancelled = true;
      if (timeoutId) clearTimeout(timeoutId);
    };
  }, [activeTab, refreshRunActivity, runIdFromUrl]);
  if (isLoading) return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(LoadingMessage, { label: t("integrations.detail.title") }) }) });
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("integrations.detail.notFound", "Integration not found."),
        backHref: "/backend/integrations",
        backLabel: t("integrations.detail.backToList", "Back to integrations")
      }
    ) }) });
  }
  if (error || !detail || !resolvedIntegration || !resolvedState) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(ErrorMessage, { label: error ?? t("integrations.detail.loadError") }) }) });
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsxs(PageBody, { className: "space-y-6", children: [
    /* @__PURE__ */ jsx(
      FormHeader,
      {
        backHref: "/backend/integrations",
        title: resolvedIntegration.title,
        actions: {
          cancelHref: showCredentialActions ? "/backend/integrations" : void 0,
          submit: showCredentialActions ? {
            formId: credentialsFormId,
            pending: isSavingCredentials,
            label: t("integrations.detail.credentials.save", "Save credentials"),
            pendingLabel: t("ui.forms.status.saving", "Saving...")
          } : void 0
        }
      }
    ),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      resolvedIntegration.description ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: resolvedIntegration.description }) : null,
      /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-4 text-sm text-muted-foreground", children: [
        resolvedIntegration.category ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          CategoryIcon ? /* @__PURE__ */ jsx(CategoryIcon, { className: "h-4 w-4" }) : null,
          /* @__PURE__ */ jsx("span", { children: formatTypeLabel(resolvedIntegration.category) })
        ] }) : null,
        resolvedIntegration.hub ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx("span", { className: "text-xs font-medium uppercase tracking-wide text-muted-foreground/80", children: t("integrations.detail.hub.label", "Hub") }),
          /* @__PURE__ */ jsx("span", { children: formatTypeLabel(resolvedIntegration.hub) })
        ] }) : null
      ] })
    ] }),
    /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { className: "text-base", children: t("integrations.detail.analytics.title") }) }),
      /* @__PURE__ */ jsxs(CardContent, { className: "flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-1 text-sm text-muted-foreground", children: [
          /* @__PURE__ */ jsx("p", { children: t("integrations.detail.analytics.totalEvents", { count: detail.analytics.totalCount }) }),
          /* @__PURE__ */ jsx("p", { children: t("integrations.detail.analytics.errorRate", {
            rate: `${Math.round(detail.analytics.errorRate * 1e3) / 10}%`
          }) }),
          /* @__PURE__ */ jsx("p", { children: detail.analytics.lastActivityAt ? `${t("integrations.detail.analytics.lastActivity")}: ${new Date(detail.analytics.lastActivityAt).toLocaleString()}` : t("integrations.detail.analytics.never") })
        ] }),
        /* @__PURE__ */ jsx(DetailLogSparkline, { counts: detail.analytics.dailyCounts })
      ] })
    ] }),
    /* @__PURE__ */ jsx("section", { className: "rounded-lg border bg-card p-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx("p", { className: "text-overline uppercase tracking-wide text-muted-foreground", children: t("integrations.detail.state.label", "State") }),
        /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: cn("gap-1.5 rounded-full px-3 py-1 text-xs font-medium", stateBadgeClass), children: [
          /* @__PURE__ */ jsx(StateIcon, { className: "h-3.5 w-3.5" }),
          resolvedState.isEnabled ? t("integrations.detail.state.enabled", "Enabled") : t("integrations.detail.state.disabled", "Disabled")
        ] })
      ] }),
      /* @__PURE__ */ jsx(
        Switch,
        {
          checked: resolvedState.isEnabled,
          disabled: isTogglingState,
          onCheckedChange: (checked) => void handleToggleState(checked)
        }
      )
    ] }) }),
    stackedDetailWidgets.length > 0 ? /* @__PURE__ */ jsx("section", { className: "space-y-4", children: /* @__PURE__ */ jsx(
      InjectionSpot,
      {
        spotId: detailWidgetSpotId,
        context: injectionContext,
        data: detail,
        onDataChange: (next) => setDetail(next),
        widgetsOverride: stackedDetailWidgets
      }
    ) }) : null,
    groupedDetailWidgets.length > 0 ? /* @__PURE__ */ jsx("section", { className: "grid gap-4 lg:grid-cols-2", children: groupedDetailWidgets.map((widget) => /* @__PURE__ */ jsxs(
      Card,
      {
        className: widget.placement?.column === 2 ? "lg:col-start-2" : void 0,
        children: [
          /* @__PURE__ */ jsxs(CardHeader, { children: [
            /* @__PURE__ */ jsx(CardTitle, { children: widget.placement?.groupLabel ? t(widget.placement.groupLabel, widget.module.metadata.title) : widget.module.metadata.title }),
            widget.placement?.groupDescription ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: widget.placement.groupDescription }) : null
          ] }),
          /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx(
            widget.module.Widget,
            {
              context: injectionContext,
              data: detail,
              onDataChange: (next) => setDetail(next)
            }
          ) })
        ]
      },
      widget.widgetId
    )) }) : null,
    /* @__PURE__ */ jsxs(Tabs, { value: activeTab, onValueChange: handleTabChange, className: "space-y-5", children: [
      /* @__PURE__ */ jsxs(TabsList, { className: "h-auto w-full justify-start overflow-x-auto rounded-none border-b border-border bg-transparent p-0", children: [
        showCredentialsTab ? /* @__PURE__ */ jsx(
          TabsTrigger,
          {
            value: "credentials",
            className: "mr-8 h-auto rounded-none border-b-2 border-transparent bg-transparent px-0 py-2.5 text-sm font-medium text-muted-foreground shadow-none transition-colors hover:bg-transparent hover:text-foreground aria-selected:border-accent-indigo aria-selected:bg-transparent aria-selected:text-foreground aria-selected:shadow-none last:mr-0",
            children: /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(Key, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsx("span", { children: t("integrations.detail.tabs.credentials") })
            ] })
          }
        ) : null,
        leadingInjectedTab ? /* @__PURE__ */ jsx(
          TabsTrigger,
          {
            value: leadingInjectedTab.id,
            className: "mr-8 h-auto rounded-none border-b-2 border-transparent bg-transparent px-0 py-2.5 text-sm font-medium text-muted-foreground shadow-none transition-colors hover:bg-transparent hover:text-foreground aria-selected:border-accent-indigo aria-selected:bg-transparent aria-selected:text-foreground aria-selected:shadow-none last:mr-0",
            children: /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(Settings, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsx("span", { children: leadingInjectedTab.label })
            ] })
          }
        ) : null,
        showVersionTab ? /* @__PURE__ */ jsx(
          TabsTrigger,
          {
            value: "version",
            className: "mr-8 h-auto rounded-none border-b-2 border-transparent bg-transparent px-0 py-2.5 text-sm font-medium text-muted-foreground shadow-none transition-colors hover:bg-transparent hover:text-foreground aria-selected:border-accent-indigo aria-selected:bg-transparent aria-selected:text-foreground aria-selected:shadow-none last:mr-0",
            children: /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(RefreshCw, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsx("span", { children: t("integrations.detail.tabs.version") })
            ] })
          }
        ) : null,
        showDataSyncScheduleTab ? /* @__PURE__ */ jsx(
          TabsTrigger,
          {
            value: "data-sync-schedule",
            className: "mr-8 h-auto rounded-none border-b-2 border-transparent bg-transparent px-0 py-2.5 text-sm font-medium text-muted-foreground shadow-none transition-colors hover:bg-transparent hover:text-foreground aria-selected:border-accent-indigo aria-selected:bg-transparent aria-selected:text-foreground aria-selected:shadow-none last:mr-0",
            children: /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(Calendar, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsx("span", { children: t("data_sync.integrationTab.title", "Sync schedules") })
            ] })
          }
        ) : null,
        showHealthTab ? /* @__PURE__ */ jsx(
          TabsTrigger,
          {
            value: "health",
            className: "mr-8 h-auto rounded-none border-b-2 border-transparent bg-transparent px-0 py-2.5 text-sm font-medium text-muted-foreground shadow-none transition-colors hover:bg-transparent hover:text-foreground aria-selected:border-accent-indigo aria-selected:bg-transparent aria-selected:text-foreground aria-selected:shadow-none last:mr-0",
            children: /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(Activity, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsx("span", { children: t("integrations.detail.tabs.health") })
            ] })
          }
        ) : null,
        showLogsTab ? /* @__PURE__ */ jsx(
          TabsTrigger,
          {
            value: "logs",
            className: "mr-8 h-auto rounded-none border-b-2 border-transparent bg-transparent px-0 py-2.5 text-sm font-medium text-muted-foreground shadow-none transition-colors hover:bg-transparent hover:text-foreground aria-selected:border-accent-indigo aria-selected:bg-transparent aria-selected:text-foreground aria-selected:shadow-none last:mr-0",
            children: /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(FileText, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsx("span", { children: t("integrations.detail.tabs.logs") })
            ] })
          }
        ) : null,
        trailingInjectedTabs.map((tab) => /* @__PURE__ */ jsx(
          TabsTrigger,
          {
            value: tab.id,
            className: "mr-8 h-auto rounded-none border-b-2 border-transparent bg-transparent px-0 py-2.5 text-sm font-medium text-muted-foreground shadow-none transition-colors hover:bg-transparent hover:text-foreground aria-selected:border-accent-indigo aria-selected:bg-transparent aria-selected:text-foreground aria-selected:shadow-none last:mr-0",
            children: /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(Settings, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsx("span", { children: tab.label })
            ] })
          },
          tab.id
        ))
      ] }),
      showCredentialsTab ? /* @__PURE__ */ jsx(TabsContent, { value: "credentials", className: "mt-0", children: /* @__PURE__ */ jsxs("section", { className: "space-y-4 rounded-lg border bg-card p-6", children: [
        detail.bundle ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-status-info-border bg-status-info-bg p-3 text-sm text-status-info-text", children: t("integrations.detail.credentials.bundleShared", { bundle: detail.bundle.title }) }) : null,
        credentialFormFields.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("integrations.detail.credentials.notConfigured") }) : /* @__PURE__ */ jsx(
          CrudForm,
          {
            formId: credentialsFormId,
            entityId: "integrations.integration",
            schema: credentialSchema,
            fields: credentialFormFields,
            initialValues: credValues,
            onSubmit: handleSaveCredentials,
            embedded: true,
            hideFooterActions: true
          },
          `${resolvedIntegration.id}:${credentialsFormKey}`
        )
      ] }) }) : null,
      showVersionTab ? /* @__PURE__ */ jsx(TabsContent, { value: "version", className: "mt-0 space-y-4", children: /* @__PURE__ */ jsxs(Card, { children: [
        /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: t("integrations.detail.version.select") }) }),
        /* @__PURE__ */ jsx(CardContent, { className: "space-y-3", children: resolvedIntegration.apiVersions?.map((version) => {
          const stableVersion = resolvedIntegration.apiVersions?.find((item) => item.status === "stable")?.id;
          const isSelected = (resolvedState.apiVersion ?? stableVersion) === version.id;
          return /* @__PURE__ */ jsxs(
            "div",
            {
              className: `flex cursor-pointer items-center justify-between rounded-lg border p-3 transition-colors ${isSelected ? "border-primary bg-primary/5" : "hover:bg-muted/50"}`,
              onClick: () => void handleVersionChange(version.id),
              children: [
                /* @__PURE__ */ jsxs("div", { children: [
                  /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: version.label ?? version.id }),
                  /* @__PURE__ */ jsx(
                    Badge,
                    {
                      variant: version.status === "stable" ? "default" : version.status === "deprecated" ? "destructive" : "secondary",
                      className: "ml-2",
                      children: t(`integrations.detail.version.${version.status}`)
                    }
                  ),
                  version.status === "deprecated" && version.sunsetAt ? /* @__PURE__ */ jsx("span", { className: "ml-2 text-xs text-muted-foreground", children: t("integrations.detail.version.sunsetAt", { date: new Date(version.sunsetAt).toLocaleDateString() }) }) : null
                ] }),
                isSelected ? /* @__PURE__ */ jsx(Badge, { variant: "outline", children: t("integrations.detail.version.current") }) : null
              ]
            },
            version.id
          );
        }) })
      ] }) }) : null,
      showDataSyncScheduleTab ? /* @__PURE__ */ jsx(TabsContent, { value: "data-sync-schedule", className: "mt-0", children: /* @__PURE__ */ jsx(
        IntegrationScheduleTab,
        {
          integrationId: resolvedIntegration.id,
          hasCredentials: detail.hasCredentials,
          isEnabled: resolvedState.isEnabled
        }
      ) }) : null,
      showHealthTab ? /* @__PURE__ */ jsxs(TabsContent, { value: "health", className: "mt-0 space-y-4", children: [
        /* @__PURE__ */ jsx(
          RunActivityStrip,
          {
            run: activeRunDetail,
            refreshedAt: activeRunRefreshedAt,
            isRefreshing: isRefreshingRunActivity,
            onRefresh: () => void refreshRunActivity({ showLoading: true }),
            t
          }
        ),
        /* @__PURE__ */ jsxs(Card, { className: "gap-4 py-4", children: [
          /* @__PURE__ */ jsx(CardHeader, { className: "px-5", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsx(CardTitle, { children: t("integrations.detail.health.title") }),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
              /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  variant: "outline",
                  size: "sm",
                  onClick: () => void refreshRunActivity({ showLoading: true }),
                  disabled: isRefreshingRunActivity || !runIdFromUrl,
                  children: [
                    isRefreshingRunActivity ? /* @__PURE__ */ jsx(Spinner, { className: "mr-2 h-4 w-4" }) : /* @__PURE__ */ jsx(RefreshCw, { className: "mr-2 h-4 w-4" }),
                    t("integrations.detail.runActivity.refresh", "Refresh")
                  ]
                }
              ),
              /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  variant: "outline",
                  size: "sm",
                  onClick: () => void handleHealthCheck(),
                  disabled: isCheckingHealth,
                  children: [
                    isCheckingHealth ? /* @__PURE__ */ jsx(Spinner, { className: "mr-2 h-4 w-4" }) : /* @__PURE__ */ jsx(Zap, { className: "mr-2 h-4 w-4" }),
                    isCheckingHealth ? t("integrations.detail.health.checking") : t("integrations.detail.health.check")
                  ]
                }
              )
            ] })
          ] }) }),
          /* @__PURE__ */ jsxs(CardContent, { className: "space-y-3 px-5", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-3 rounded-lg border bg-muted/20 px-4 py-3", children: [
              displayHealthStatus ? /* @__PURE__ */ jsxs(Badge, { className: `gap-1.5 ${HEALTH_STATUS_STYLES[displayHealthStatus] ?? ""}`, children: [
                HealthStatusIcon ? /* @__PURE__ */ jsx(HealthStatusIcon, { className: "h-3.5 w-3.5" }) : null,
                t(`integrations.detail.health.${displayHealthStatus}`)
              ] }) : /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
                /* @__PURE__ */ jsx(AlertTriangle, { className: "h-4 w-4" }),
                /* @__PURE__ */ jsx("span", { children: t("integrations.detail.health.unknown") })
              ] }),
              healthStatusDescription ? /* @__PURE__ */ jsx("p", { className: "min-w-0 flex-1 text-sm text-muted-foreground", children: healthStatusDescription }) : null,
              /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground md:ml-auto", children: resolvedState.lastHealthCheckedAt ? t("integrations.detail.health.lastChecked", { date: new Date(resolvedState.lastHealthCheckedAt).toLocaleString() }) : t("integrations.detail.health.neverChecked") })
            ] }),
            healthMessage || healthDetailEntries.length > 0 ? /* @__PURE__ */ jsxs("div", { className: `grid gap-3 ${healthMessage && healthDetailEntries.length > 0 ? "xl:grid-cols-[minmax(0,1.25fr)_minmax(0,1fr)]" : ""}`, children: [
              healthMessage ? /* @__PURE__ */ jsxs("div", { className: "rounded-lg border px-4 py-3", children: [
                /* @__PURE__ */ jsx("p", { className: "text-overline font-medium uppercase tracking-widest text-muted-foreground", children: t("integrations.detail.health.lastResult", "Last result") }),
                /* @__PURE__ */ jsx("p", { className: "mt-1.5 text-sm", children: healthMessage })
              ] }) : null,
              healthDetailEntries.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "rounded-lg border px-4 py-3", children: [
                /* @__PURE__ */ jsx("p", { className: "text-overline font-medium uppercase tracking-widest text-muted-foreground", children: t("integrations.detail.health.details", "Details") }),
                /* @__PURE__ */ jsx("dl", { className: "mt-2 grid gap-x-6 gap-y-2 sm:grid-cols-2", children: healthDetailEntries.map(([key, value]) => /* @__PURE__ */ jsxs("div", { children: [
                  /* @__PURE__ */ jsx("dt", { className: "text-xs font-medium text-muted-foreground", children: formatLogDetailLabel(key) }),
                  /* @__PURE__ */ jsx("dd", { className: "mt-0.5 text-sm", children: formatHealthValue(value) })
                ] }, key)) })
              ] }) : null
            ] }) : null
          ] })
        ] })
      ] }) : null,
      showLogsTab ? /* @__PURE__ */ jsxs(TabsContent, { value: "logs", className: "mt-0 space-y-4", children: [
        /* @__PURE__ */ jsx(
          RunActivityStrip,
          {
            run: activeRunDetail,
            refreshedAt: activeRunRefreshedAt,
            isRefreshing: isRefreshingRunActivity,
            onRefresh: () => void refreshRunActivity({ showLoading: true }),
            t
          }
        ),
        /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [
          /* @__PURE__ */ jsx("div", { className: "inline-flex", children: /* @__PURE__ */ jsxs(
            Select,
            {
              value: logLevel || void 0,
              onValueChange: (value) => setLogLevel(value ?? ""),
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { size: "lg", className: "min-w-40", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("integrations.detail.logs.level.all") }) }),
                /* @__PURE__ */ jsxs(SelectContent, { children: [
                  /* @__PURE__ */ jsx(SelectItem, { value: "info", children: t("integrations.detail.logs.level.info") }),
                  /* @__PURE__ */ jsx(SelectItem, { value: "warn", children: t("integrations.detail.logs.level.warn") }),
                  /* @__PURE__ */ jsx(SelectItem, { value: "error", children: t("integrations.detail.logs.level.error") })
                ] })
              ]
            }
          ) }),
          /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "sm",
              onClick: () => void refreshRunActivity({ showLoading: true }),
              disabled: isRefreshingRunActivity || !runIdFromUrl,
              children: [
                isRefreshingRunActivity ? /* @__PURE__ */ jsx(Spinner, { className: "mr-2 h-4 w-4" }) : /* @__PURE__ */ jsx(RefreshCw, { className: "mr-2 h-4 w-4" }),
                t("integrations.detail.runActivity.refresh", "Refresh")
              ]
            }
          )
        ] }),
        isLoadingLogs ? /* @__PURE__ */ jsx("div", { className: "flex justify-center py-8", children: /* @__PURE__ */ jsx(Spinner, {}) }) : /* @__PURE__ */ jsx(
          LogList,
          {
            entries: logs.map((log) => {
              const metadataEntries = [
                ["Time", new Date(log.createdAt).toLocaleString()],
                ["Level", log.level],
                ["Code", log.code ?? null],
                ["Run ID", log.runId ?? null],
                ["Entity Type", log.scopeEntityType ?? null],
                ["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: new Date(log.createdAt).toLocaleString(),
                level: log.level,
                message: log.message,
                body: /* @__PURE__ */ jsxs("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]", children: [
                  /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
                    /* @__PURE__ */ jsxs("section", { className: "space-y-3", children: [
                      /* @__PURE__ */ jsxs("div", { children: [
                        /* @__PURE__ */ jsx("p", { className: "text-xs font-medium uppercase tracking-wide text-muted-foreground", children: t("integrations.detail.logs.details.summary", "Summary") }),
                        /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm font-medium", children: log.message })
                      ] }),
                      metadataEntries.length > 0 ? /* @__PURE__ */ jsx("dl", { className: "grid gap-3 sm:grid-cols-2", 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__ */ jsxs("section", { className: "space-y-3", children: [
                      /* @__PURE__ */ jsx("p", { className: "text-xs font-medium uppercase tracking-wide text-muted-foreground", children: t("integrations.detail.logs.details.fields", "Fields") }),
                      /* @__PURE__ */ jsx("dl", { className: "grid gap-3 sm:grid-cols-2", 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
                  ] }),
                  /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
                    nestedEntries.map(([key, value]) => /* @__PURE__ */ jsx(
                      JsonDisplay,
                      {
                        data: value,
                        title: formatLogDetailLabel(key),
                        defaultExpanded: true,
                        maxInitialDepth: 1,
                        theme: "dark",
                        maxHeight: "16rem",
                        className: "p-4"
                      },
                      key
                    )),
                    log.payload && nestedEntries.length === 0 ? /* @__PURE__ */ jsx(
                      JsonDisplay,
                      {
                        data: log.payload,
                        title: t("integrations.detail.logs.details.payload", "Payload"),
                        defaultExpanded: true,
                        maxInitialDepth: 1,
                        theme: "dark",
                        maxHeight: "16rem",
                        className: "p-4"
                      }
                    ) : null,
                    !log.payload ? /* @__PURE__ */ jsx(
                      EmptyState,
                      {
                        size: "sm",
                        icon: /* @__PURE__ */ jsx(FileX, { className: "h-8 w-8", "aria-hidden": "true" }),
                        title: t("integrations.detail.logs.details.noPayload", "No structured payload was stored for this log entry.")
                      }
                    ) : null
                  ] })
                ] })
              };
            }),
            emptyMessage: t("integrations.detail.logs.empty")
          }
        )
      ] }) : null,
      injectedTabs.map((tab) => /* @__PURE__ */ jsx(TabsContent, { value: tab.id, className: "mt-0 space-y-4", children: /* @__PURE__ */ jsx(
        InjectionSpot,
        {
          spotId: detailWidgetSpotId,
          context: injectionContext,
          data: detail,
          onDataChange: (next) => setDetail(next),
          widgetsOverride: tab.widgets
        }
      ) }, tab.id))
    ] })
  ] }) });
}
export {
  IntegrationDetailPage as default
};
//# sourceMappingURL=page.js.map
