"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, hydrateCustomerTodoSettings } from "./config.js";
import { resolveExampleIntegrationHref } from "../../../lib/interactionCompatibility.js";
import { resolveTodoHref } from "../../../components/detail/utils.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
async function loadTodos(settings) {
  const params = new URLSearchParams({
    limit: String(settings.pageSize)
  });
  const call = await apiCall(
    `/api/customers/dashboard/widgets/customer-todos?${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;
    const entity = data.entity ?? {};
    return {
      id: typeof data.id === "string" ? data.id : null,
      todoId: typeof data.todoId === "string" ? data.todoId : "",
      todoSource: typeof data.todoSource === "string" ? data.todoSource : "",
      todoTitle: typeof data.todoTitle === "string" ? data.todoTitle : null,
      createdAt: typeof data.createdAt === "string" ? data.createdAt : "",
      _integrations: data._integrations && typeof data._integrations === "object" ? data._integrations : void 0,
      entity: {
        id: typeof entity.id === "string" ? entity.id : null,
        displayName: typeof entity.displayName === "string" ? entity.displayName : null,
        kind: typeof entity.kind === "string" ? entity.kind : null
      }
    };
  }).filter((item) => !!item && !!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);
}
function resolveDetailHref(entity) {
  if (!entity?.id) return null;
  if (entity.kind === "company") return `/backend/customers/companies-v2/${encodeURIComponent(entity.id)}`;
  if (entity.kind === "person") return `/backend/customers/people-v2/${encodeURIComponent(entity.id)}`;
  return `/backend/customers/people-v2/${encodeURIComponent(entity.id)}`;
}
const CustomerTodosWidget = ({
  mode,
  settings = DEFAULT_SETTINGS,
  onSettingsChange,
  refreshToken,
  onRefreshStateChange
}) => {
  const t = useT();
  const hydrated = React.useMemo(() => hydrateCustomerTodoSettings(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 loadTodos(hydrated);
      setItems(data);
    } catch (err) {
      logger.error("Failed to load customer todos widget data", { err });
      setError(t("customers.widgets.todos.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-todos-page-size", className: "text-xs font-semibold uppercase text-muted-foreground", children: t("customers.widgets.todos.settings.pageSize") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "customer-todos-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__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("customers.widgets.todos.settings.help") })
    ] });
  }
  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.todos.empty") }) : /* @__PURE__ */ jsx("ul", { className: "space-y-3", children: items.map((item) => {
    const createdLabel = formatDate(item.createdAt, locale);
    const href = resolveDetailHref(item.entity);
    const exampleHref = resolveExampleIntegrationHref(item);
    const taskHref = exampleHref ?? resolveTodoHref(item.todoSource, item.todoId);
    return /* @__PURE__ */ jsxs("li", { className: "rounded-md border p-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3 text-sm font-medium", children: [
        /* @__PURE__ */ jsx("span", { children: item.entity.displayName ?? t("customers.widgets.common.unknown") }),
        /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: createdLabel || t("customers.widgets.common.unknownDate") })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "mt-1 space-y-0.5", children: [
        /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-foreground", children: item.todoTitle ?? t("customers.widgets.todos.untitled") }),
        item.todoSource ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: item.todoSource }) : null
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "mt-2 flex flex-wrap gap-3 text-xs", children: [
        href ? /* @__PURE__ */ jsx(Link, { className: "text-primary hover:underline", href, children: t("customers.widgets.common.viewRecord") }) : null,
        taskHref ? /* @__PURE__ */ jsx(Link, { className: "text-primary hover:underline", href: taskHref, children: t("customers.workPlan.customerTodos.table.actions.openTask") }) : null
      ] })
    ] }, item.id);
  }) }) });
};
var widget_client_default = CustomerTodosWidget;
export {
  widget_client_default as default
};
//# sourceMappingURL=widget.client.js.map
