"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { formatRelativeTime, formatDateTime } from "@open-mercato/shared/lib/time";
import { cn } from "@open-mercato/shared/lib/utils";
import { ArrowRightLeft, Zap, MessageSquare, User, Filter, ChevronDown, Check } from "lucide-react";
const isValidContext = (ctx) => ctx !== null && typeof ctx === "object" && "kind" in ctx && "record" in ctx && (ctx.kind === "order" || ctx.kind === "quote") && typeof ctx.record === "object" && ctx.record !== null && "id" in ctx.record && typeof ctx.record.id === "string";
const KIND_ICONS = {
  status: ArrowRightLeft,
  action: Zap,
  comment: MessageSquare
};
const KIND_ICON_COLORS = {
  status: "text-foreground",
  action: "text-foreground",
  comment: "text-foreground"
};
const KIND_BG_COLORS = {
  status: "bg-muted",
  action: "bg-muted",
  comment: "bg-muted"
};
function StatusDot({ color, className }) {
  if (!color) return /* @__PURE__ */ jsx("span", { className: cn("h-2.5 w-2.5 rounded-full bg-muted-foreground/40 border border-border inline-flex", className) });
  return /* @__PURE__ */ jsx(
    "span",
    {
      className: cn("h-2.5 w-2.5 rounded-full border border-border/70 inline-flex", className),
      style: { backgroundColor: color },
      "aria-hidden": true
    }
  );
}
function StatusTransition({
  statusFrom,
  statusTo,
  statusMap
}) {
  const from = statusFrom ? statusMap[statusFrom] ?? { value: statusFrom, label: statusFrom, color: null, icon: null } : null;
  const to = statusTo ? statusMap[statusTo] ?? { value: statusTo, label: statusTo, color: null, icon: null } : null;
  return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5 flex-wrap", children: [
    from ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1 text-xs text-muted-foreground", children: [
      /* @__PURE__ */ jsx(StatusDot, { color: from.color }),
      /* @__PURE__ */ jsx("span", { children: from.label })
    ] }) : null,
    from && to ? /* @__PURE__ */ jsx(ArrowRightLeft, { className: "h-3 w-3 text-muted-foreground/60 shrink-0" }) : null,
    to ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1 text-xs font-medium text-foreground", children: [
      /* @__PURE__ */ jsx(StatusDot, { color: to.color }),
      /* @__PURE__ */ jsx("span", { children: to.label })
    ] }) : null
  ] });
}
function TimelineItem({
  entry,
  statusMap,
  isLast
}) {
  const KindIcon = KIND_ICONS[entry.kind];
  const relativeTime = formatRelativeTime(entry.occurredAt);
  const absoluteTime = formatDateTime(entry.occurredAt);
  const isStatusChange = entry.kind === "status" && entry.metadata?.statusTo;
  return /* @__PURE__ */ jsxs("div", { "data-testid": "timeline-entry", className: "relative flex gap-3", children: [
    !isLast && /* @__PURE__ */ jsx("div", { className: "absolute left-[11px] top-6 bottom-0 w-px bg-border", "aria-hidden": true }),
    /* @__PURE__ */ jsx(
      "div",
      {
        className: cn(
          "relative z-10 flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border",
          KIND_BG_COLORS[entry.kind]
        ),
        children: /* @__PURE__ */ jsx(KindIcon, { className: cn("h-3 w-3", KIND_ICON_COLORS[entry.kind]), "aria-hidden": true })
      }
    ),
    /* @__PURE__ */ jsx("div", { className: "flex-1 pb-4", children: /* @__PURE__ */ jsxs("div", { className: "group rounded-lg border bg-card p-3 space-y-1.5", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2 flex-wrap", children: [
        /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5 text-xs font-medium text-foreground", children: [
          /* @__PURE__ */ jsx(User, { className: "h-3 w-3 text-muted-foreground", "aria-hidden": true }),
          entry.actor.label
        ] }),
        /* @__PURE__ */ jsx(
          "span",
          {
            className: "text-xs text-muted-foreground",
            title: absoluteTime ?? void 0,
            children: relativeTime ?? absoluteTime
          }
        )
      ] }),
      isStatusChange ? /* @__PURE__ */ jsx(
        StatusTransition,
        {
          statusFrom: entry.metadata?.statusFrom,
          statusTo: entry.metadata?.statusTo,
          statusMap
        }
      ) : /* @__PURE__ */ jsx("div", { className: "text-sm text-foreground", children: entry.action })
    ] }) })
  ] });
}
function FilterDropdown({ filter, onChange }) {
  const t = useT();
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    function onDocClick(e) {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    }
    function onKey(e) {
      if (e.key === "Escape") setOpen(false);
    }
    document.addEventListener("mousedown", onDocClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDocClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);
  const options = [
    { value: "all", label: t("sales.documents.history.filter.all", "All") },
    { value: "status", label: t("sales.documents.history.filter.status", "Status changes") },
    { value: "action", label: t("sales.documents.history.filter.actions", "Actions") },
    { value: "comment", label: t("sales.documents.history.filter.comments", "Comments") }
  ];
  const activeLabel = options.find((o) => o.value === filter)?.label;
  return /* @__PURE__ */ jsxs("div", { className: "relative", ref, children: [
    /* @__PURE__ */ jsxs(
      "button",
      {
        type: "button",
        "aria-haspopup": "listbox",
        "aria-expanded": open,
        onClick: () => setOpen((prev) => !prev),
        className: "inline-flex items-center gap-1.5 rounded-md border border-input bg-background px-2.5 py-1 text-xs font-medium shadow-sm hover:bg-accent hover:text-accent-foreground transition-colors select-none",
        children: [
          /* @__PURE__ */ jsx(Filter, { className: "h-3 w-3", "aria-hidden": true }),
          t("sales.documents.history.filter.label", "Filters"),
          filter !== "all" && /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
            ": ",
            activeLabel
          ] }),
          /* @__PURE__ */ jsx(ChevronDown, { className: cn("h-3 w-3 transition-transform duration-150", open && "rotate-180"), "aria-hidden": true })
        ]
      }
    ),
    open && /* @__PURE__ */ jsx(
      "div",
      {
        role: "listbox",
        "aria-label": t("sales.documents.history.filter.label", "Filters"),
        className: "absolute left-0 top-full mt-1 z-dropdown w-48 rounded-md border bg-background p-1 shadow-md",
        children: options.map((opt) => /* @__PURE__ */ jsxs(
          "button",
          {
            type: "button",
            role: "option",
            "aria-selected": filter === opt.value,
            onClick: () => {
              onChange(opt.value);
              setOpen(false);
            },
            className: "flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-accent",
            children: [
              /* @__PURE__ */ jsx(Check, { className: cn("h-3.5 w-3.5 shrink-0", filter === opt.value ? "opacity-100" : "opacity-0"), "aria-hidden": true }),
              opt.label
            ]
          },
          opt.value
        ))
      }
    )
  ] });
}
const DocumentHistoryWidget = ({ context }) => {
  const t = useT();
  const [entries, setEntries] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [statusMap, setStatusMap] = React.useState({});
  const [filter, setFilter] = React.useState("all");
  React.useEffect(() => {
    const urls = [
      "/api/sales/order-statuses?pageSize=100",
      "/api/sales/shipment-statuses?pageSize=100",
      "/api/sales/payment-statuses?pageSize=100"
    ];
    const map = {};
    const merge = (items) => {
      if (!Array.isArray(items)) return;
      for (const item of items) {
        if (!item || typeof item !== "object") continue;
        const d = item;
        const value = typeof d.value === "string" ? d.value : null;
        if (!value) continue;
        map[value] = {
          value,
          label: typeof d.label === "string" && d.label.length ? d.label : value,
          color: typeof d.color === "string" && d.color.length ? d.color : null,
          icon: typeof d.icon === "string" && d.icon.length ? d.icon : null
        };
      }
    };
    Promise.all(urls.map((url) => apiCall(url))).then((responses) => {
      for (const res of responses) {
        if (res.ok && Array.isArray(res.result?.items)) merge(res.result.items);
      }
      setStatusMap(map);
    }).catch(() => {
    });
  }, []);
  React.useEffect(() => {
    if (!isValidContext(context)) {
      setLoading(false);
      setError(t("sales.documents.history.error", "Failed to load history."));
      return;
    }
    setLoading(true);
    setError(null);
    apiCall(
      `/api/sales/document-history?kind=${context.kind}&id=${context.record.id}`
    ).then((res) => {
      if (res.ok && Array.isArray(res.result?.items)) {
        setEntries(res.result.items);
      } else {
        setError(t("sales.documents.history.error", "Failed to load history."));
      }
    }).catch(() => setError(t("sales.documents.history.error", "Failed to load history."))).finally(() => setLoading(false));
  }, [context, t]);
  const filtered = React.useMemo(
    () => filter === "all" ? entries : entries.filter((e) => e.kind === filter),
    [entries, filter]
  );
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(FilterDropdown, { filter, onChange: setFilter }) }),
    loading ? /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center h-24", children: /* @__PURE__ */ jsx(Spinner, {}) }) : error ? /* @__PURE__ */ jsx("div", { className: "text-destructive text-sm", children: error }) : !filtered.length ? /* @__PURE__ */ jsx("div", { className: "text-muted-foreground text-sm py-6 text-center", children: t("sales.documents.history.empty", "No history entries yet.") }) : /* @__PURE__ */ jsx("div", { className: "relative", children: filtered.map((entry, index) => /* @__PURE__ */ jsx(
      TimelineItem,
      {
        entry,
        statusMap,
        isLast: index === filtered.length - 1
      },
      entry.id
    )) })
  ] });
};
var widget_client_default = DocumentHistoryWidget;
export {
  DocumentHistoryWidget,
  widget_client_default as default
};
//# sourceMappingURL=widget.client.js.map
