"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { MessageComposer } from "@open-mercato/ui/backend/messages";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { Button } from "@open-mercato/ui/primitives/button";
import { LoadingMessage, ErrorMessage } from "@open-mercato/ui/backend/detail";
import { InjectionSpot } from "@open-mercato/ui/backend/injection/InjectionSpot";
import {
  getMessageUiComponentRegistry
} from "./utils/typeUiRegistry.js";
import {
  MessageDetailActionsSection,
  MessageDetailAttachmentsSection,
  MessageDetailBodySection,
  MessageDetailComposerDialogs,
  MessageDetailDialogs,
  MainMessageHeader,
  MessageListComponent,
  MessageHeader,
  MessageDetailMetaSection,
  MessageDetailObjectsSection
} from "./message-detail/detail-panels.js";
import { useMessageDetails } from "./message-detail/hooks/useMessageDetails.js";
function MessageConversationDetailItem({
  messageId,
  isCollapsible,
  isExpanded,
  onToggle,
  onReply,
  onForward,
  userFeatures
}) {
  const state = useMessageDetails(messageId);
  const messageUiRegistry = React.useMemo(() => getMessageUiComponentRegistry(), []);
  if (state.isLoadingDetail) {
    return /* @__PURE__ */ jsx("section", { className: "py-3", children: /* @__PURE__ */ jsx(LoadingMessage, { label: state.t("messages.loading.detail", "Loading message...") }) });
  }
  if (!state.detail) {
    return /* @__PURE__ */ jsx("section", { className: "py-3", children: /* @__PURE__ */ jsx(ErrorMessage, { label: state.loadErrorMessage }) });
  }
  const ContentComponent = state.contentComponentKey ? messageUiRegistry.contentComponents[state.contentComponentKey] ?? null : null;
  const ActionsComponent = state.actionsComponentKey ? messageUiRegistry.actionsComponents[state.actionsComponentKey] ?? null : null;
  return /* @__PURE__ */ jsxs("section", { className: "py-3", children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
      /* @__PURE__ */ jsxs("section", { className: "space-y-2 py-2", children: [
        /* @__PURE__ */ jsx(
          MessageHeader,
          {
            detail: state.detail,
            updatingState: state.updatingState,
            isArchived: state.isArchived,
            showSubject: false,
            collapseToggle: isCollapsible ? { expanded: isExpanded, onToggle } : void 0,
            onReply: () => onReply(messageId),
            onForward: () => onForward(messageId),
            onEdit: () => state.setEditOpen(true),
            onToggleRead: () => void state.toggleRead(),
            onToggleArchive: () => void state.toggleArchive(),
            onDelete: () => state.setDeleteConfirmationOpen(true)
          }
        ),
        /* @__PURE__ */ jsx(
          MessageDetailBodySection,
          {
            detail: state.detail,
            contentProps: state.contentProps,
            ContentComponent
          }
        ),
        /* @__PURE__ */ jsx(
          InjectionSpot,
          {
            spotId: "detail:messages:message:body:after",
            context: { messageId },
            data: state.detail
          }
        ),
        /* @__PURE__ */ jsx(MessageDetailMetaSection, { detail: state.detail }),
        /* @__PURE__ */ jsx(
          InjectionSpot,
          {
            spotId: "detail:messages:message:sidebar",
            context: { messageId, userFeatures },
            data: state.detail
          }
        )
      ] }),
      /* @__PURE__ */ jsx(
        MessageDetailActionsSection,
        {
          detail: state.detail,
          messageActions: state.messageActions,
          executingActionId: state.executingActionId,
          ActionsComponent,
          onExecuteActionById: state.handleExecuteActionById,
          onExecuteAction: state.handleExecuteAction
        }
      ),
      /* @__PURE__ */ jsx(
        MessageDetailObjectsSection,
        {
          detail: state.detail,
          objectActionsByObjectId: state.objectActionsByObjectId,
          onExecuteAction: state.handleExecuteAction
        }
      ),
      /* @__PURE__ */ jsx(
        MessageDetailAttachmentsSection,
        {
          attachmentsQuery: state.attachmentsQuery,
          attachments: state.attachments
        }
      )
    ] }),
    /* @__PURE__ */ jsx(
      MessageDetailComposerDialogs,
      {
        id: messageId,
        detail: state.detail,
        attachments: state.attachments,
        editOpen: state.editOpen,
        setEditOpen: state.setEditOpen,
        onRefresh: () => state.detailQuery.refetch()
      }
    ),
    /* @__PURE__ */ jsx(
      MessageDetailDialogs,
      {
        pendingActionConfirmation: state.pendingActionConfirmation,
        setPendingActionConfirmation: state.setPendingActionConfirmation,
        executingActionId: state.executingActionId,
        handleConfirmPendingAction: state.handleConfirmPendingAction,
        handleActionConfirmDialogKeyDown: state.handleActionConfirmDialogKeyDown,
        deleteConfirmationOpen: state.deleteConfirmationOpen,
        setDeleteConfirmationOpen: state.setDeleteConfirmationOpen,
        updatingState: state.updatingState,
        handleDelete: state.handleDelete,
        handleDeleteDialogKeyDown: state.handleDeleteDialogKeyDown
      }
    )
  ] });
}
function MessageDetailPageClient({ id }) {
  const state = useMessageDetails(id);
  const [userFeatures, setUserFeatures] = React.useState([]);
  React.useEffect(() => {
    let cancelled = false;
    void (async () => {
      const res = await apiCall("/api/auth/feature-check", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ features: ["communication_channels.assign"] })
      }).catch(() => null);
      if (!cancelled && res?.ok && Array.isArray(res.result?.granted)) {
        setUserFeatures(res.result.granted);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);
  const [activeInlineComposer, setActiveInlineComposer] = React.useState(null);
  const inlineComposerContainerRef = React.useRef(null);
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  React.useEffect(() => {
    if (!activeInlineComposer) return;
    const composerContainer = inlineComposerContainerRef.current;
    if (!composerContainer) return;
    const firstFocusableElement = composerContainer.querySelector(
      'textarea, input, [contenteditable="true"]'
    );
    firstFocusableElement?.focus();
  }, [activeInlineComposer]);
  if (state.isLoadingDetail) {
    return /* @__PURE__ */ jsx(LoadingMessage, { label: state.t("messages.loading.detail", "Loading message...") });
  }
  if (!state.detail) {
    return /* @__PURE__ */ jsx(
      ErrorMessage,
      {
        label: state.loadErrorMessage,
        action: /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: state.backToList, children: state.t("messages.actions.backToList", "Back to messages") })
      }
    );
  }
  const detail = state.detail;
  const firstConversationMessageId = state.conversationItems[0]?.id ?? null;
  const latestConversationMessageId = state.conversationItems[state.conversationItems.length - 1]?.id ?? null;
  const canRunConversationActions = Boolean(firstConversationMessageId);
  const conversationArchived = Boolean(detail.conversationArchived);
  const conversationAllUnread = Boolean(detail.conversationAllUnread);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsx(
      MainMessageHeader,
      {
        subject: detail.subject,
        priority: detail.priority ?? "normal",
        canReply: !detail.isDraft && detail.typeDefinition.allowReply && Boolean(firstConversationMessageId),
        canForwardAll: !detail.isDraft && detail.typeDefinition.allowForward && Boolean(latestConversationMessageId),
        conversationArchived,
        conversationAllUnread,
        actionsDisabled: Boolean(state.activeConversationAction),
        activeActionId: state.activeConversationAction,
        onReply: () => {
          if (!firstConversationMessageId) return;
          setActiveInlineComposer({
            variant: "reply",
            messageId: firstConversationMessageId
          });
        },
        onForwardAll: () => {
          if (!latestConversationMessageId) return;
          setActiveInlineComposer({
            variant: "forward",
            messageId: latestConversationMessageId
          });
        },
        onToggleArchiveConversation: () => {
          if (!canRunConversationActions) return;
          if (conversationArchived) {
            void state.unarchiveConversation(firstConversationMessageId ?? void 0);
          } else {
            void state.archiveConversation(firstConversationMessageId ?? void 0);
          }
        },
        onToggleReadConversation: () => {
          if (!canRunConversationActions) return;
          if (conversationAllUnread) {
            void state.markConversationRead(firstConversationMessageId ?? void 0);
          } else {
            void state.markConversationUnread(firstConversationMessageId ?? void 0);
          }
        },
        onDeleteConversation: () => {
          if (!canRunConversationActions || state.activeConversationAction) return;
          void (async () => {
            const confirmed = await confirm({
              title: state.t("messages.confirm.deleteConversationTitle", "Delete conversation"),
              text: state.t("messages.confirm.deleteConversation", "Delete this conversation from your view?"),
              confirmText: state.t("messages.actions.deleteConversation", "Delete conversation"),
              cancelText: state.t("common.cancel", "Cancel"),
              variant: "destructive"
            });
            if (!confirmed) return;
            await state.deleteConversation(firstConversationMessageId ?? void 0);
          })();
        }
      }
    ),
    /* @__PURE__ */ jsx("div", { className: "divide-y border-y", children: state.conversationItems.map((item) => {
      const isForcedExpanded = item.id === state.forcedExpandedItemId;
      const isExpanded = state.isConversationItemExpanded(item.id);
      if (isExpanded) {
        return /* @__PURE__ */ jsx(
          MessageConversationDetailItem,
          {
            messageId: item.id,
            userFeatures,
            isCollapsible: !isForcedExpanded,
            isExpanded: true,
            onToggle: () => state.toggleConversationItem(item.id),
            onReply: (messageId) => {
              setActiveInlineComposer({
                variant: "reply",
                messageId
              });
            },
            onForward: (messageId) => {
              setActiveInlineComposer({
                variant: "forward",
                messageId
              });
            }
          },
          item.id
        );
      }
      return /* @__PURE__ */ jsx("section", { className: "px-1 py-1", children: /* @__PURE__ */ jsx(
        MessageListComponent,
        {
          message: state.buildConversationListItemMessage(item),
          onClick: () => state.toggleConversationItem(item.id)
        }
      ) }, item.id);
    }) }),
    activeInlineComposer ? /* @__PURE__ */ jsx("div", { ref: inlineComposerContainerRef, children: /* @__PURE__ */ jsx(
      MessageComposer,
      {
        inline: true,
        inlineBackHref: null,
        variant: activeInlineComposer.variant,
        messageId: activeInlineComposer.messageId,
        onCancel: () => {
          setActiveInlineComposer(null);
        },
        onSuccess: () => {
          setActiveInlineComposer(null);
          void state.detailQuery.refetch();
        }
      }
    ) }) : null,
    ConfirmDialogElement
  ] });
}
export {
  MessageDetailPageClient
};
//# sourceMappingURL=MessageDetailPageClient.js.map
