"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useRouter } from "next/navigation";
import { Lock, Users } from "lucide-react";
import { EmailReplyForwardActions } from "./EmailReplyForwardActions.js";
import {
  ComposeEmailDialog
} from "./ComposeEmailDialog.js";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { useAppEvent } from "@open-mercato/ui/backend/injection/useAppEvent";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
const PERSON_EMAIL_CARD_ACTIONS_CONTEXT_ID = "customers-person-email-card-actions";
function EmailCardActions({ data }) {
  const t = useT();
  const router = useRouter();
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: PERSON_EMAIL_CARD_ACTIONS_CONTEXT_ID,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const personId = data.personId ?? null;
  const rfcMessageId = data.rfcMessageId ?? null;
  const fromAddress = data.fromAddress ?? null;
  const [mode, setMode] = React.useState(null);
  const [channels, setChannels] = React.useState(null);
  React.useEffect(() => {
    let cancelled = false;
    apiCall("/api/communication_channels/me/channels", {
      method: "GET",
      // Mount-time chrome fetch: degrade silently on an expired session.
      headers: { "x-om-forbidden-redirect": "0", "x-om-unauthorized-redirect": "0" }
    }).then((r) => {
      if (cancelled) return;
      const allItems = Array.isArray(r.result?.items) ? r.result.items : [];
      const connected = allItems.filter(
        (item) => item !== null && typeof item === "object" && item.status === "connected"
      );
      setChannels(connected);
    }).catch(() => {
      if (!cancelled) setChannels([]);
    });
    return () => {
      cancelled = true;
    };
  }, []);
  const refreshTimeline = React.useCallback(() => {
    router.refresh();
  }, [router]);
  useAppEvent("customers.email.linked", refreshTimeline, [refreshTimeline]);
  useAppEvent("messages.message.sent", refreshTimeline, [refreshTimeline]);
  if (!personId || !rfcMessageId) return null;
  if (channels === null) return null;
  const subjectBase = data.subject ?? "";
  const reSubject = subjectBase.toLowerCase().startsWith("re:") ? subjectBase : `Re: ${subjectBase}`.trim();
  const fwdSubject = subjectBase.toLowerCase().startsWith("fwd:") ? subjectBase : `Fwd: ${subjectBase}`.trim();
  const replyTo = mode == null ? null : {
    inReplyTo: rfcMessageId,
    references: Array.from(/* @__PURE__ */ new Set([...data.references ?? [], rfcMessageId])),
    to: mode === "forward" ? [] : fromAddress ? [fromAddress] : [],
    cc: mode === "replyAll" ? data.ccAddresses ?? void 0 : void 0,
    subject: mode === "forward" ? fwdSubject : reSubject
  };
  const onSend = async (values) => {
    const operation = async () => {
      const response = await apiCall(
        `/api/customers/people/${encodeURIComponent(personId)}/emails`,
        {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify(values)
        }
      );
      if (!response.ok) {
        const err = response.result;
        throw new Error(err?.error ?? t("customers.email.errors.sendFailed", "Send failed"));
      }
      return response.result?.messageId ?? null;
    };
    const messageId = await runMutation({
      operation,
      context: {
        formId: PERSON_EMAIL_CARD_ACTIONS_CONTEXT_ID,
        resourceKind: "customers.person",
        resourceId: personId,
        retryLastMutation
      },
      mutationPayload: values
    });
    flash(t("customers.email.compose.sent", "Email sent"), "success");
    return { messageId };
  };
  const noChannels = channels.length === 0;
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      EmailReplyForwardActions,
      {
        onReply: () => setMode("reply"),
        onReplyAll: () => setMode("replyAll"),
        onForward: () => setMode("forward"),
        disabled: noChannels
      }
    ),
    data.isAuthor === true && data.currentVisibility ? /* @__PURE__ */ jsx(
      IconButton,
      {
        type: "button",
        variant: "ghost",
        size: "sm",
        "aria-label": data.currentVisibility === "private" ? t("customers.email.visibility.flipToShared.label", "Share with teammates") : t("customers.email.visibility.flipToPrivate.label", "Make private"),
        title: data.currentVisibility === "private" ? t("customers.email.visibility.flipToShared.label", "Share with teammates") : t("customers.email.visibility.flipToPrivate.label", "Make private"),
        onClick: async (e) => {
          e.stopPropagation();
          const interactionId = data.interactionId;
          if (!interactionId) return;
          const next = data.currentVisibility === "private" ? "shared" : "private";
          try {
            await runMutation({
              // optimistic-lock-exempt: dedicated single-field visibility
              // action endpoint (shared/private toggle), not a full-record
              // edit. The canonical interaction edit/delete is version-locked
              // at the command layer (customers.interactions.* commands); this
              // idempotent toggle derives `next` from freshly-loaded state.
              operation: async () => {
                const r = await apiCall(
                  `/api/customers/interactions/${interactionId}/visibility`,
                  {
                    method: "PATCH",
                    headers: { "content-type": "application/json" },
                    body: JSON.stringify({ visibility: next })
                  }
                );
                if (!r.ok) {
                  const err = r.result;
                  throw new Error(
                    err?.error ?? t("customers.email.errors.flipFailed", "Visibility update failed")
                  );
                }
              },
              context: {
                formId: PERSON_EMAIL_CARD_ACTIONS_CONTEXT_ID,
                resourceKind: "customers.interaction",
                resourceId: interactionId,
                retryLastMutation
              },
              mutationPayload: { visibility: next }
            });
          } catch (err) {
            flash(
              err instanceof Error ? err.message : t("customers.email.errors.flipFailed", "Visibility update failed"),
              "error"
            );
            return;
          }
          flash(
            next === "shared" ? t("customers.email.visibility.flipToShared.success", "Email shared with teammates") : t("customers.email.visibility.flipToPrivate.success", "Email made private"),
            "success"
          );
          router.refresh();
        },
        children: data.currentVisibility === "private" ? /* @__PURE__ */ jsx(Lock, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Users, { className: "h-4 w-4" })
      }
    ) : null,
    mode != null && /* @__PURE__ */ jsx(
      ComposeEmailDialog,
      {
        open: mode != null,
        onOpenChange: (open) => setMode(open ? mode : null),
        defaultRecipient: fromAddress,
        channels,
        replyTo,
        onSend
      }
    )
  ] });
}
var EmailCardActions_default = EmailCardActions;
export {
  EmailCardActions,
  EmailCardActions_default as default
};
//# sourceMappingURL=EmailCardActions.js.map
