"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 { formatRelativeTime } from "@open-mercato/shared/lib/time";
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,
  hydrateNextInteractionsSettings
} from "./config.js";
import { renderDictionaryColor, renderDictionaryIcon } from "../../../lib/dictionaries.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
async function loadNextInteractions(settings) {
  const params = new URLSearchParams({
    limit: String(settings.pageSize),
    includePast: settings.includePast ? "true" : "false"
  });
  const call = await apiCall(`/api/customers/dashboard/widgets/next-interactions?${params.toString()}`);
  if (!call.ok) {
    const rawError = call.result?.error;
    const message = typeof rawError === "string" ? rawError : `Request failed with status ${call.status}`;
    throw new Error(message);
  }
  const payloadData = call.result ?? {};
  const now = typeof payloadData.now === "string" ? payloadData.now : void 0;
  const rawItems = Array.isArray(payloadData.items) ? payloadData.items : [];
  const items = rawItems.map((item) => {
    if (!item || typeof item !== "object") return null;
    const data = item;
    const id = typeof data.id === "string" ? data.id : null;
    if (!id) return null;
    return {
      id,
      displayName: typeof data.displayName === "string" ? data.displayName : null,
      kind: typeof data.kind === "string" ? data.kind : null,
      nextInteractionAt: typeof data.nextInteractionAt === "string" ? data.nextInteractionAt : null,
      nextInteractionName: typeof data.nextInteractionName === "string" ? data.nextInteractionName : null,
      nextInteractionIcon: typeof data.nextInteractionIcon === "string" ? data.nextInteractionIcon : null,
      nextInteractionColor: typeof data.nextInteractionColor === "string" ? data.nextInteractionColor : null,
      organizationId: typeof data.organizationId === "string" ? data.organizationId : null
    };
  }).filter((item) => !!item && !!item.id);
  return { items, now };
}
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 formatAbsolute(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 CustomerNextInteractionsWidget = ({
  mode,
  settings = DEFAULT_SETTINGS,
  onSettingsChange,
  refreshToken,
  onRefreshStateChange
}) => {
  const t = useT();
  const hydrated = React.useMemo(() => hydrateNextInteractionsSettings(settings), [settings]);
  const [data, setData] = 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 response = await loadNextInteractions(hydrated);
      setData(response.items);
    } catch (err) {
      logger.error("Failed to load next interactions widget data", { err });
      setError(t("customers.widgets.nextInteractions.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-next-interactions-page-size", className: "text-xs font-semibold uppercase text-muted-foreground", children: t("customers.widgets.nextInteractions.settings.pageSize") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "customer-next-interactions-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("label", { className: "flex items-center gap-2 text-xs text-muted-foreground", children: [
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "checkbox",
            checked: hydrated.includePast,
            onChange: (event) => onSettingsChange({ ...hydrated, includePast: event.target.checked })
          }
        ),
        t("customers.widgets.nextInteractions.settings.includePast")
      ] })
    ] });
  }
  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" }) }) : data.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("customers.widgets.nextInteractions.empty") }) : /* @__PURE__ */ jsx("ul", { className: "space-y-3", children: data.map((item) => {
    const href = resolveDetailHref(item);
    const absolute = formatAbsolute(item.nextInteractionAt, locale);
    const relative = formatRelativeTime(item.nextInteractionAt, { 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", { className: "flex items-start gap-3", children: [
          item.nextInteractionIcon ? /* @__PURE__ */ jsx("span", { className: "mt-0.5 inline-flex h-7 w-7 items-center justify-center rounded border border-border bg-card", children: renderDictionaryIcon(item.nextInteractionIcon, "h-4 w-4") }) : null,
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: item.displayName ?? t("customers.widgets.common.unknown") }),
            item.nextInteractionName ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: item.nextInteractionName }) : null
          ] })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-right text-xs text-muted-foreground", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("p", { children: absolute || t("customers.widgets.common.unknownDate") }),
            relative ? /* @__PURE__ */ jsx("p", { children: relative }) : null
          ] }),
          item.nextInteractionColor ? renderDictionaryColor(item.nextInteractionColor, "h-3 w-3 rounded-full border border-border") : null
        ] })
      ] }),
      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 = CustomerNextInteractionsWidget;
export {
  widget_client_default as default
};
//# sourceMappingURL=widget.client.js.map
