"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { hasFeature } from "@open-mercato/shared/security/features";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
const FEATURE_GATE = "communication_channels.assign";
const CHANNEL_INFO_MUTATION_CONTEXT_ID = "communication-channels-info-panel";
const UNASSIGNED_VALUE = "__unassigned__";
function ChannelInfoPanelWidget({
  data,
  context
}) {
  const t = useT();
  const channel = data?._channel ?? null;
  const contact = data?._channelContact ?? null;
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: CHANNEL_INFO_MUTATION_CONTEXT_ID,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const canReassign = hasFeature(context?.userFeatures ?? [], FEATURE_GATE);
  const [assignedUserId, setAssignedUserId] = React.useState(
    contact?.assignedUserId ?? null
  );
  const [savingAssignee, setSavingAssignee] = React.useState(false);
  const [users, setUsers] = React.useState([]);
  const [usersLoaded, setUsersLoaded] = React.useState(false);
  React.useEffect(
    () => setAssignedUserId(contact?.assignedUserId ?? null),
    [contact?.assignedUserId]
  );
  const loadUsers = React.useCallback(async () => {
    if (usersLoaded || !canReassign) return;
    const response = await apiCall("/api/auth/users?page=1&pageSize=50", {
      // Opportunistic dropdown-options fetch: a user may hold
      // `communication_channels.assign` without `auth.users.list`. Suppress the
      // global 403/401 redirect + forbidden flash so the page degrades to an
      // empty assignee list instead of bouncing the whole browser to /login.
      headers: { "x-om-forbidden-redirect": "0", "x-om-unauthorized-redirect": "0" }
    }).catch(() => null);
    if (!response || !response.ok) {
      setUsersLoaded(true);
      return;
    }
    const items = (response.result?.items ?? []).flatMap((u) => {
      if (!u?.id) return [];
      const label = typeof u.name === "string" && u.name.trim().length > 0 && u.name.trim() || typeof u.email === "string" && u.email.trim().length > 0 && u.email.trim() || u.id;
      return [{ id: u.id, label }];
    });
    setUsers(items);
    setUsersLoaded(true);
  }, [canReassign, usersLoaded]);
  const reassign = React.useCallback(
    async (nextAssignedUserId) => {
      const threadId = data?.threadId;
      if (!threadId) {
        flash(
          t(
            "communication_channels.infoPanel.noThread",
            "This message is not on a thread; reassignment unavailable."
          ),
          "error"
        );
        return;
      }
      setSavingAssignee(true);
      try {
        const response = await runMutation({
          operation: () => apiCall(
            `/api/communication_channels/threads/${encodeURIComponent(threadId)}/assign`,
            {
              method: "PUT",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({ assignedUserId: nextAssignedUserId })
            }
          ),
          context: {
            formId: CHANNEL_INFO_MUTATION_CONTEXT_ID,
            resourceKind: "communication_channels.thread",
            resourceId: threadId,
            retryLastMutation
          },
          mutationPayload: { assignedUserId: nextAssignedUserId }
        });
        if (!response.ok) {
          const body = response.result;
          flash(
            body?.error ?? t("communication_channels.infoPanel.reassignError", "Reassignment failed"),
            "error"
          );
          return;
        }
        setAssignedUserId(nextAssignedUserId);
        flash(
          t("communication_channels.infoPanel.reassignSuccess", "Conversation reassigned."),
          "success"
        );
      } catch (err) {
        flash(
          err instanceof Error ? err.message : t("communication_channels.infoPanel.reassignError", "Reassignment failed"),
          "error"
        );
      } finally {
        setSavingAssignee(false);
      }
    },
    [data?.threadId, retryLastMutation, runMutation, t]
  );
  if (!channel) return null;
  return /* @__PURE__ */ jsxs(
    "aside",
    {
      className: "rounded-md border bg-card p-4 text-sm",
      "aria-label": t("communication_channels.infoPanel.aria", "Channel info"),
      children: [
        /* @__PURE__ */ jsx("header", { className: "mb-2 text-overline text-muted-foreground", children: t("communication_channels.infoPanel.title", "Channel info") }),
        /* @__PURE__ */ jsxs("dl", { className: "grid grid-cols-2 gap-1 text-xs", children: [
          /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: t("communication_channels.infoPanel.provider", "Provider") }),
          /* @__PURE__ */ jsx("dd", { children: channel.providerKey }),
          /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: t("communication_channels.infoPanel.type", "Type") }),
          /* @__PURE__ */ jsx("dd", { children: channel.channelType }),
          /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: t("communication_channels.infoPanel.direction", "Direction") }),
          /* @__PURE__ */ jsx("dd", { children: channel.direction }),
          channel.deliveryStatus ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: t("communication_channels.infoPanel.status", "Status") }),
            /* @__PURE__ */ jsx("dd", { children: channel.deliveryStatus })
          ] }) : null,
          contact?.contactPersonId ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: t("communication_channels.infoPanel.contactPerson", "CRM contact") }),
            /* @__PURE__ */ jsx("dd", { className: "truncate", title: contact.contactPersonId, children: contact.contactPersonId })
          ] }) : null,
          contact?.subject ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: t("communication_channels.infoPanel.subject", "Subject") }),
            /* @__PURE__ */ jsx("dd", { className: "col-span-2 truncate", title: contact.subject, children: contact.subject })
          ] }) : null,
          /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: t("communication_channels.infoPanel.assignedTo", "Assigned to") }),
          /* @__PURE__ */ jsx("dd", { className: "col-span-1", children: canReassign ? /* @__PURE__ */ jsxs(
            Select,
            {
              value: assignedUserId ?? UNASSIGNED_VALUE,
              onValueChange: (value) => void reassign(value === UNASSIGNED_VALUE ? null : value),
              onOpenChange: (isOpen) => {
                if (isOpen) void loadUsers();
              },
              disabled: savingAssignee || !data?.threadId,
              children: [
                /* @__PURE__ */ jsx(
                  SelectTrigger,
                  {
                    size: "xs",
                    "aria-label": t("communication_channels.infoPanel.assignedTo", "Assigned to"),
                    children: /* @__PURE__ */ jsx(
                      SelectValue,
                      {
                        placeholder: t("communication_channels.infoPanel.unassigned", "Unassigned")
                      }
                    )
                  }
                ),
                /* @__PURE__ */ jsxs(SelectContent, { children: [
                  /* @__PURE__ */ jsx(SelectItem, { value: UNASSIGNED_VALUE, children: t("communication_channels.infoPanel.unassigned", "Unassigned") }),
                  assignedUserId && !users.some((u) => u.id === assignedUserId) ? /* @__PURE__ */ jsx(SelectItem, { value: assignedUserId, children: assignedUserId }) : null,
                  users.map((user) => /* @__PURE__ */ jsx(SelectItem, { value: user.id, children: user.label }, user.id))
                ] })
              ]
            }
          ) : /* @__PURE__ */ jsx("span", { className: "truncate", title: assignedUserId ?? "", children: assignedUserId ?? t("communication_channels.infoPanel.unassigned", "Unassigned") }) })
        ] })
      ]
    }
  );
}
export {
  ChannelInfoPanelWidget as default
};
//# sourceMappingURL=widget.client.js.map
