"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { Card, CardHeader, CardTitle, CardContent } from "@open-mercato/ui/primitives/card";
import { Button } from "@open-mercato/ui/primitives/button";
import { Switch } from "@open-mercato/ui/primitives/switch";
import { Input } from "@open-mercato/ui/primitives/input";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { apiCall, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { FilterBar } from "@open-mercato/ui/backend/FilterBar";
import { Bell, Cog, CreditCard, HardDrive, LayoutGrid, MessageSquare, RefreshCw, Search, Truck, Webhook } from "lucide-react";
import {
  buildIntegrationMarketplaceFilterDefs,
  getIntegrationMarketplaceCategory,
  getListQueryFromFilterValues,
  INTEGRATION_MARKETPLACE_CATEGORIES,
  normalizeIntegrationMarketplaceFilterValues
} from "./filters.js";
const CATEGORY_ICONS = {
  all: LayoutGrid,
  payment: CreditCard,
  shipping: Truck,
  data_sync: RefreshCw,
  communication: MessageSquare,
  notification: Bell,
  storage: HardDrive,
  webhook: Webhook
};
const HEALTH_BADGE_CLASS = {
  healthy: "bg-emerald-500/15 text-emerald-800 dark:text-emerald-300",
  degraded: "bg-amber-500/15 text-amber-900 dark:text-amber-300",
  unhealthy: "bg-destructive/15 text-destructive",
  unconfigured: "bg-muted text-muted-foreground"
};
function buildListQueryString(input) {
  const params = new URLSearchParams();
  if (input.q) params.set("q", input.q);
  if (input.category) params.set("category", input.category);
  if (input.bundleId) params.set("bundleId", input.bundleId);
  if (input.isEnabled !== void 0) params.set("isEnabled", String(input.isEnabled));
  if (input.healthStatus) params.set("healthStatus", input.healthStatus);
  if (input.sort) params.set("sort", input.sort);
  if (input.order) params.set("order", input.order);
  if (input.page != null && input.page > 1) params.set("page", String(input.page));
  if (input.pageSize != null && input.pageSize !== 100) params.set("pageSize", String(input.pageSize));
  const qs = params.toString();
  return qs ? `?${qs}` : "";
}
function LogSparkline({ counts, className }) {
  const max = Math.max(1, ...counts);
  const w = 72;
  const h = 22;
  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 - 3) - 1.5;
    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.2",
      strokeLinejoin: "round",
      strokeLinecap: "round",
      points,
      className: "text-muted-foreground/80"
    }
  ) });
}
function IntegrationsMarketplacePage() {
  const [data, setData] = React.useState(null);
  const [isLoading, setIsLoading] = React.useState(true);
  const [searchInput, setSearchInput] = React.useState("");
  const [debouncedSearch, setDebouncedSearch] = React.useState("");
  const [filterValues, setFilterValues] = React.useState({});
  const [sortField, setSortField] = React.useState("title");
  const [sortOrder, setSortOrder] = React.useState("asc");
  const [page, setPage] = React.useState(1);
  const [togglingIds, setTogglingIds] = React.useState(/* @__PURE__ */ new Set());
  const scopeVersion = useOrganizationScopeVersion();
  const t = useT();
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: "integrations.marketplace"
  });
  React.useEffect(() => {
    const timer = setTimeout(() => setDebouncedSearch(searchInput.trim()), 300);
    return () => clearTimeout(timer);
  }, [searchInput]);
  const selectedCategory = React.useMemo(() => getIntegrationMarketplaceCategory(filterValues), [filterValues]);
  const listQuery = React.useMemo(() => {
    const fromFilters = getListQueryFromFilterValues(filterValues);
    const category = selectedCategory !== "all" ? selectedCategory : fromFilters.category;
    return buildListQueryString({
      q: debouncedSearch || void 0,
      ...category ? { category } : {},
      ...fromFilters.bundleId ? { bundleId: fromFilters.bundleId } : {},
      ...fromFilters.isEnabled !== void 0 ? { isEnabled: fromFilters.isEnabled } : {},
      ...fromFilters.healthStatus ? { healthStatus: fromFilters.healthStatus } : {},
      sort: sortField,
      order: sortOrder,
      page,
      pageSize: 100
    });
  }, [debouncedSearch, filterValues, page, selectedCategory, sortField, sortOrder]);
  const bundleFilterOptions = React.useMemo(
    () => (data?.bundles ?? []).map((bundle) => ({ id: bundle.id, title: bundle.title })),
    [data?.bundles]
  );
  const categoryFilters = React.useMemo(
    () => buildIntegrationMarketplaceFilterDefs(t, bundleFilterOptions),
    [bundleFilterOptions, t]
  );
  const load = React.useCallback(async () => {
    setIsLoading(true);
    const fallback = { items: [], bundles: [], total: 0, page: 1, pageSize: 100, totalPages: 1 };
    const call = await apiCall(`/api/integrations${listQuery}`, void 0, { fallback });
    if (!call.ok) {
      flash(t("integrations.marketplace.loadError"), "error");
      setIsLoading(false);
      return;
    }
    setData(call.result ?? fallback);
    setIsLoading(false);
  }, [listQuery, t]);
  React.useEffect(() => {
    void load();
  }, [load, scopeVersion]);
  React.useEffect(() => {
    setPage(1);
  }, [debouncedSearch, filterValues, selectedCategory, sortField, sortOrder]);
  const handleToggle = React.useCallback(async (integrationId, enabled, updatedAt) => {
    setTogglingIds((prev) => new Set(prev).add(integrationId));
    try {
      const call = await runMutation({
        mutationPayload: { integrationId, isEnabled: enabled },
        context: {
          formId: "integrations.marketplace",
          operation: "update",
          actionId: "toggle-state",
          resourceKind: "integrations.integration",
          resourceId: integrationId,
          integrationId,
          retryLastMutation
        },
        operation: () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(updatedAt),
          () => apiCall(`/api/integrations/${encodeURIComponent(integrationId)}/state`, {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ isEnabled: enabled })
          }, { fallback: null })
        )
      });
      if (!call.ok) {
        flash(t("integrations.detail.stateError"), "error");
      } else {
        const nextUpdatedAt = call.result?.updatedAt ?? null;
        setData((prev) => {
          if (!prev) return prev;
          return {
            ...prev,
            items: prev.items.map(
              (item) => item.id === integrationId ? { ...item, isEnabled: enabled, stateUpdatedAt: nextUpdatedAt ?? item.stateUpdatedAt } : item
            )
          };
        });
      }
    } catch {
      flash(t("integrations.detail.stateError"), "error");
    } finally {
      setTogglingIds((prev) => {
        const next = new Set(prev);
        next.delete(integrationId);
        return next;
      });
    }
  }, [retryLastMutation, runMutation, t]);
  const grouped = React.useMemo(() => {
    if (!data) return { bundles: [], standalone: [] };
    const bundled = /* @__PURE__ */ new Map();
    const standalone = [];
    for (const item of data.items) {
      if (item.bundleId) {
        const list = bundled.get(item.bundleId) ?? [];
        list.push(item);
        bundled.set(item.bundleId, list);
      } else {
        standalone.push(item);
      }
    }
    const bundles = (data.bundles ?? []).filter((b) => bundled.has(b.id)).map((b) => ({ ...b, integrations: bundled.get(b.id) ?? [] }));
    return { bundles, standalone };
  }, [data]);
  const renderCategoryIcon = React.useCallback((category, className) => {
    if (!category) return null;
    const Icon = CATEGORY_ICONS[category];
    if (!Icon) return null;
    return /* @__PURE__ */ jsx(Icon, { className });
  }, []);
  const renderHealthBadge = React.useCallback((status) => {
    return /* @__PURE__ */ jsx(
      "span",
      {
        className: `inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-semibold uppercase tracking-wide ${HEALTH_BADGE_CLASS[status] ?? HEALTH_BADGE_CLASS.unconfigured}`,
        children: t(`integrations.marketplace.health.${status}`, status)
      }
    );
  }, [t]);
  if (isLoading && !data) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center py-16", children: /* @__PURE__ */ jsx(Spinner, {}) }) }) });
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { className: "space-y-6", children: /* @__PURE__ */ jsxs("section", { className: "space-y-6 rounded-lg border bg-background p-6", children: [
    /* @__PURE__ */ jsxs("header", { className: "flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("integrations.marketplace.title") }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("integrations.marketplace.description") })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
        /* @__PURE__ */ jsxs("div", { className: "relative w-full min-w-[200px] max-w-xs lg:w-64", children: [
          /* @__PURE__ */ jsx(Search, { className: "absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground pointer-events-none" }),
          /* @__PURE__ */ jsx(
            Input,
            {
              placeholder: t("integrations.marketplace.search"),
              value: searchInput,
              onChange: (e) => setSearchInput(e.target.value),
              className: "pl-8"
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
          /* @__PURE__ */ jsx("span", { className: "sr-only", children: t("integrations.marketplace.sort.label", "Sort by") }),
          /* @__PURE__ */ jsxs(
            "select",
            {
              className: "h-9 rounded-md border border-input bg-background px-2 text-sm",
              value: sortField,
              onChange: (e) => setSortField(e.target.value),
              children: [
                /* @__PURE__ */ jsx("option", { value: "title", children: t("integrations.marketplace.sort.title", "Title") }),
                /* @__PURE__ */ jsx("option", { value: "category", children: t("integrations.marketplace.sort.category", "Category") }),
                /* @__PURE__ */ jsx("option", { value: "enabledAt", children: t("integrations.marketplace.sort.enabledAt", "Enabled date") }),
                /* @__PURE__ */ jsx("option", { value: "healthStatus", children: t("integrations.marketplace.sort.health", "Health") })
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsxs(
          "select",
          {
            className: "h-9 rounded-md border border-input bg-background px-2 text-sm",
            value: sortOrder,
            onChange: (e) => setSortOrder(e.target.value),
            "aria-label": t("integrations.marketplace.sort.order", "Sort order"),
            children: [
              /* @__PURE__ */ jsx("option", { value: "asc", children: t("integrations.marketplace.sort.asc", "Ascending") }),
              /* @__PURE__ */ jsx("option", { value: "desc", children: t("integrations.marketplace.sort.desc", "Descending") })
            ]
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "lg:hidden", children: /* @__PURE__ */ jsx(
      FilterBar,
      {
        searchValue: searchInput,
        onSearchChange: setSearchInput,
        searchPlaceholder: t("integrations.marketplace.search"),
        searchAlign: "left",
        filters: categoryFilters,
        values: filterValues,
        onApply: (values) => setFilterValues(normalizeIntegrationMarketplaceFilterValues(values)),
        onClear: () => setFilterValues({})
      }
    ) }),
    /* @__PURE__ */ jsx("div", { className: "hidden lg:flex flex-wrap gap-1.5", children: INTEGRATION_MARKETPLACE_CATEGORIES.map((category) => {
      const Icon = CATEGORY_ICONS[category];
      return /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: selectedCategory === category ? "default" : "outline",
          size: "sm",
          onClick: () => setFilterValues(normalizeIntegrationMarketplaceFilterValues({ category })),
          children: [
            Icon ? /* @__PURE__ */ jsx(Icon, { className: "mr-1.5 h-3.5 w-3.5" }) : null,
            t(`integrations.marketplace.categories.${category}`)
          ]
        },
        category
      );
    }) }),
    isLoading ? /* @__PURE__ */ jsx("div", { className: "flex justify-center py-8", children: /* @__PURE__ */ jsx(Spinner, {}) }) : null,
    data && data.totalPages > 1 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2 text-sm text-muted-foreground", children: [
      /* @__PURE__ */ jsx("span", { children: data.total === 0 ? t("integrations.marketplace.pagination.empty", "No results") : t("integrations.marketplace.pagination.summary", {
        from: (data.page - 1) * data.pageSize + 1,
        to: Math.min(data.page * data.pageSize, data.total),
        total: data.total
      }) }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            disabled: data.page <= 1,
            onClick: () => setPage((p) => Math.max(1, p - 1)),
            children: t("integrations.marketplace.pagination.prev", "Previous")
          }
        ),
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            disabled: data.page >= data.totalPages,
            onClick: () => setPage((p) => p + 1),
            children: t("integrations.marketplace.pagination.next", "Next")
          }
        )
      ] })
    ] }) : null,
    grouped.bundles.map((bundle) => /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(CardTitle, { children: bundle.title }),
          bundle.description && /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-sm mt-1", children: bundle.description }),
          /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs mt-1", children: t("integrations.marketplace.integrations", { count: bundle.integrations.length }) })
        ] }),
        /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", size: "sm", children: /* @__PURE__ */ jsxs(Link, { href: `/backend/integrations/bundle/${encodeURIComponent(bundle.id)}`, children: [
          /* @__PURE__ */ jsx(Cog, { className: "mr-1.5 h-4 w-4" }),
          t("integrations.marketplace.configure")
        ] }) })
      ] }) }),
      /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3", children: bundle.integrations.map((item) => /* @__PURE__ */ jsxs(
        "div",
        {
          className: "flex flex-col gap-2 rounded-lg border p-3",
          children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
              /* @__PURE__ */ jsxs("div", { className: "min-w-0 space-y-1", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
                  renderCategoryIcon(item.category, "h-4 w-4 text-muted-foreground shrink-0"),
                  /* @__PURE__ */ jsx(
                    Link,
                    {
                      href: `/backend/integrations/${encodeURIComponent(item.id)}`,
                      className: "truncate text-sm font-medium hover:underline",
                      children: item.title
                    }
                  ),
                  renderHealthBadge(item.healthStatus)
                ] }),
                item.company || item.author || item.version ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: [item.company || item.author, item.version ? `v${item.version}` : null].filter(Boolean).join(" \xB7 ") }) : null
              ] }),
              /* @__PURE__ */ jsx(
                Switch,
                {
                  checked: item.isEnabled,
                  disabled: togglingIds.has(item.id),
                  onCheckedChange: (checked) => void handleToggle(item.id, checked, item.stateUpdatedAt),
                  className: "shrink-0"
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-end justify-between gap-2 border-t pt-2", children: [
              /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground space-y-0.5", children: [
                /* @__PURE__ */ jsx("div", { children: t("integrations.marketplace.analytics.events", { count: item.analytics.totalCount }) }),
                /* @__PURE__ */ jsx("div", { children: t("integrations.marketplace.analytics.errorRate", {
                  rate: `${Math.round(item.analytics.errorRate * 1e3) / 10}%`
                }) })
              ] }),
              /* @__PURE__ */ jsx(LogSparkline, { counts: item.analytics.dailyCounts })
            ] })
          ]
        },
        item.id
      )) }) })
    ] }, bundle.id)),
    grouped.standalone.length > 0 && /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4", children: grouped.standalone.map((item) => /* @__PURE__ */ jsxs(Card, { className: "flex flex-col", children: [
      /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-2", children: [
          renderCategoryIcon(item.category, "h-4 w-4 text-muted-foreground shrink-0"),
          /* @__PURE__ */ jsx(CardTitle, { className: "text-base", children: item.title }),
          renderHealthBadge(item.healthStatus)
        ] }),
        /* @__PURE__ */ jsx(
          Switch,
          {
            checked: item.isEnabled,
            disabled: togglingIds.has(item.id),
            onCheckedChange: (checked) => void handleToggle(item.id, checked, item.stateUpdatedAt),
            className: "shrink-0"
          }
        )
      ] }) }),
      /* @__PURE__ */ jsxs(CardContent, { className: "flex-1 space-y-2", children: [
        item.description && /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-sm", children: item.description }),
        (item.company || item.author || item.version) && /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: [item.company || item.author, item.version ? `v${item.version}` : null].filter(Boolean).join(" \xB7 ") }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-end justify-between gap-2 border-t pt-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground space-y-0.5", children: [
            /* @__PURE__ */ jsx("div", { children: t("integrations.marketplace.analytics.events", { count: item.analytics.totalCount }) }),
            /* @__PURE__ */ jsx("div", { children: t("integrations.marketplace.analytics.errorRate", {
              rate: `${Math.round(item.analytics.errorRate * 1e3) / 10}%`
            }) })
          ] }),
          /* @__PURE__ */ jsx(LogSparkline, { counts: item.analytics.dailyCounts })
        ] })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "px-6 pb-4", children: /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", size: "sm", className: "w-full", children: /* @__PURE__ */ jsxs(Link, { href: `/backend/integrations/${encodeURIComponent(item.id)}`, children: [
        /* @__PURE__ */ jsx(Cog, { className: "mr-1.5 h-4 w-4" }),
        t("integrations.marketplace.configure")
      ] }) }) })
    ] }, item.id)) }),
    grouped.bundles.length === 0 && grouped.standalone.length === 0 && !isLoading && /* @__PURE__ */ jsx("div", { className: "text-center py-12 text-muted-foreground", children: t("integrations.marketplace.noResults") })
  ] }) }) });
}
export {
  IntegrationsMarketplacePage as default
};
//# sourceMappingURL=page.js.map
