"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { Input } from "@open-mercato/ui/primitives/input";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { DEFAULT_SETTINGS, hydrateNewDealsSettings } from "./config.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
async function loadNewDeals(settings) {
  const params = new URLSearchParams({ limit: String(settings.pageSize) });
  const call = await apiCall(
    `/api/customers/dashboard/widgets/new-deals?${params.toString()}`
  );
  if (!call.ok) {
    const message = typeof call.result?.error === "string" ? call.result.error : `Request failed with status ${call.status}`;
    throw new Error(message);
  }
  const payload = call.result ?? {};
  const rawItems = Array.isArray(payload.items) ? payload.items : [];
  return rawItems.map((item) => {
    if (!item || typeof item !== "object") return null;
    const data = item;
    return {
      id: typeof data.id === "string" ? data.id : null,
      title: typeof data.title === "string" ? data.title : null,
      status: typeof data.status === "string" ? data.status : null,
      createdAt: typeof data.createdAt === "string" ? data.createdAt : ""
    };
  }).filter((item) => !!item && !!item.id && !!item.createdAt);
}
function resolveDetailHref(item) {
  if (!item.id) return null;
  return `/backend/customers/deals/${encodeURIComponent(item.id)}`;
}
function formatDate(value, locale) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  return date.toLocaleString(locale ?? void 0, { dateStyle: "medium", timeStyle: "short" });
}
const CustomerNewDealsWidget = ({
  mode,
  settings = DEFAULT_SETTINGS,
  onSettingsChange,
  refreshToken,
  onRefreshStateChange
}) => {
  const t = useT();
  const hydrated = React.useMemo(() => hydrateNewDealsSettings(settings), [settings]);
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [locale, setLocale] = React.useState(void 0);
  React.useEffect(() => {
    if (typeof navigator !== "undefined") {
      setLocale(navigator.language);
    }
  }, []);
  const refresh = React.useCallback(async () => {
    onRefreshStateChange?.(true);
    setLoading(true);
    setError(null);
    try {
      const data = await loadNewDeals(hydrated);
      setItems(data);
    } catch (err) {
      logger.error("Failed to load new deals widget data", { err });
      setError(t("customers.widgets.newDeals.error"));
    } finally {
      setLoading(false);
      onRefreshStateChange?.(false);
    }
  }, [hydrated, onRefreshStateChange, t]);
  React.useEffect(() => {
    refresh().catch(() => {
    });
  }, [refresh, refreshToken]);
  if (mode === "settings") {
    return /* @__PURE__ */ jsx("div", { className: "space-y-4 text-sm", children: /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
      /* @__PURE__ */ jsx("label", { htmlFor: "customer-new-deals-page-size", className: "text-xs font-semibold uppercase text-muted-foreground", children: t("customers.widgets.newDeals.settings.pageSize") }),
      /* @__PURE__ */ jsx(
        Input,
        {
          id: "customer-new-deals-page-size",
          type: "number",
          min: 1,
          max: 20,
          className: "w-24",
          value: hydrated.pageSize,
          onChange: (event) => {
            const next = Number(event.target.value);
            onSettingsChange({ ...hydrated, pageSize: Number.isFinite(next) ? next : hydrated.pageSize });
          }
        }
      )
    ] }) });
  }
  return /* @__PURE__ */ jsx("div", { className: "space-y-4", children: error ? /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: error }) : loading ? /* @__PURE__ */ jsx("div", { className: "flex h-32 items-center justify-center", children: /* @__PURE__ */ jsx(Spinner, { className: "h-6 w-6 text-muted-foreground" }) }) : items.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("customers.widgets.newDeals.empty") }) : /* @__PURE__ */ jsx("ul", { className: "space-y-3", children: items.map((item) => {
    const href = resolveDetailHref(item);
    const createdLabel = formatDate(item.createdAt, locale);
    return /* @__PURE__ */ jsxs("li", { className: "rounded-md border p-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: item.title ?? t("customers.widgets.newDeals.untitled") }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: item.status ?? t("customers.widgets.common.unknown") })
        ] }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: createdLabel || t("customers.widgets.common.unknownDate") })
      ] }),
      href ? /* @__PURE__ */ jsx("div", { className: "mt-2 text-xs", children: /* @__PURE__ */ jsx(Link, { className: "text-primary hover:underline", href, children: t("customers.widgets.common.viewRecord") }) }) : null
    ] }, item.id);
  }) }) });
};
var widget_client_default = CustomerNewDealsWidget;
export {
  widget_client_default as default
};
//# sourceMappingURL=widget.client.js.map
