"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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import {
  DEFAULT_SETTINGS,
  hydrateNewCustomersSettings
} from "./config.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
async function loadNewCustomers(settings) {
  const params = new URLSearchParams({
    limit: String(settings.pageSize)
  });
  if (settings.kind !== "all") {
    params.set("kind", settings.kind);
  }
  const call = await apiCall(
    `/api/customers/dashboard/widgets/new-customers?${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,
      displayName: typeof data.displayName === "string" ? data.displayName : null,
      kind: typeof data.kind === "string" ? data.kind : null,
      createdAt: typeof data.createdAt === "string" ? data.createdAt : ""
    };
  }).filter((item) => !!item && !!item.id && !!item.createdAt);
}
function resolveDetailHref(item) {
  if (!item.id || !item.kind) return null;
  if (item.kind === "company") return `/backend/customers/companies-v2/${encodeURIComponent(item.id)}`;
  if (item.kind === "person") return `/backend/customers/people-v2/${encodeURIComponent(item.id)}`;
  return null;
}
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" });
}
function formatKind(kind, t) {
  if (kind === "person") return t("customers.widgets.newCustomers.kind.person");
  if (kind === "company") return t("customers.widgets.newCustomers.kind.company");
  return t("customers.widgets.newCustomers.kind.unknown");
}
const CustomerNewCustomersWidget = ({
  mode,
  settings = DEFAULT_SETTINGS,
  onSettingsChange,
  refreshToken,
  onRefreshStateChange
}) => {
  const t = useT();
  const hydrated = React.useMemo(() => hydrateNewCustomersSettings(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 loadNewCustomers(hydrated);
      setItems(data);
    } catch (err) {
      logger.error("Failed to load new customers widget data", { err });
      setError(t("customers.widgets.newCustomers.error"));
    } finally {
      setLoading(false);
      onRefreshStateChange?.(false);
    }
  }, [hydrated, onRefreshStateChange, t]);
  React.useEffect(() => {
    refresh().catch(() => {
    });
  }, [refresh, refreshToken]);
  if (mode === "settings") {
    return /* @__PURE__ */ jsxs("div", { className: "space-y-4 text-sm", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
        /* @__PURE__ */ jsx("label", { htmlFor: "customer-new-customers-page-size", className: "text-xs font-semibold uppercase text-muted-foreground", children: t("customers.widgets.newCustomers.settings.pageSize") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "customer-new-customers-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 });
            }
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
        /* @__PURE__ */ jsx("label", { htmlFor: "customer-new-customers-kind", className: "text-xs font-semibold uppercase text-muted-foreground", children: t("customers.widgets.newCustomers.settings.kind") }),
        /* @__PURE__ */ jsxs(
          Select,
          {
            value: hydrated.kind,
            onValueChange: (value) => {
              if (value === "person" || value === "company" || value === "all") {
                onSettingsChange({ ...hydrated, kind: value });
              }
            },
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { id: "customer-new-customers-kind", size: "sm", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
              /* @__PURE__ */ jsxs(SelectContent, { children: [
                /* @__PURE__ */ jsx(SelectItem, { value: "all", children: t("customers.widgets.newCustomers.filters.all") }),
                /* @__PURE__ */ jsx(SelectItem, { value: "person", children: t("customers.widgets.newCustomers.filters.person") }),
                /* @__PURE__ */ jsx(SelectItem, { value: "company", children: t("customers.widgets.newCustomers.filters.company") })
              ] })
            ]
          }
        )
      ] })
    ] });
  }
  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.newCustomers.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.displayName ?? t("customers.widgets.common.unknown") }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: formatKind(item.kind, t) })
        ] }),
        /* @__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 = CustomerNewCustomersWidget;
export {
  widget_client_default as default
};
//# sourceMappingURL=widget.client.js.map
