"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Calendar, Check, ExternalLink, ListTodo, Mail, MoreHorizontal, Phone, StickyNote, Users } from "lucide-react";
import { Avatar } from "@open-mercato/ui/primitives/avatar";
import { Button } from "@open-mercato/ui/primitives/button";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCallOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { cn } from "@open-mercato/shared/lib/utils";
import { isOpenInteractionStatus } from "../../lib/interactionStatus.js";
import { ActivityAiActions } from "./ActivityAiActions.js";
import { EmailCardActions } from "./EmailCardActions.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
const TYPE_ICONS = {
  call: Phone,
  email: Mail,
  meeting: Users,
  note: StickyNote,
  task: ListTodo
};
function formatDayLabel(value, t) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  const now = /* @__PURE__ */ new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
  const day = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
  const diffDays = Math.round((today - day) / 864e5);
  if (diffDays === 0) return t("customers.timeline.date.today", "today");
  if (diffDays === 1) return t("customers.timeline.date.yesterday", "yesterday");
  return date.toLocaleDateString(void 0, { day: "numeric", month: "short" });
}
function formatTimeLabel(value) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  return date.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit" });
}
function trimSnippet(value) {
  const normalized = value?.trim();
  if (!normalized) return null;
  if (normalized.length <= 200) return normalized;
  return `${normalized.slice(0, 197)}...`;
}
function resolveTarget(activity) {
  const participant = activity.participants?.find((item) => item.name || item.email);
  if (participant?.name) return participant.name;
  if (participant?.email) return participant.email;
  if (activity.customer?.displayName) return activity.customer.displayName;
  return null;
}
function buildEmailCardWidgetData(activity) {
  const integrations = activity._integrations;
  const emailMeta = integrations?.email ?? {};
  return {
    interactionId: activity.id,
    // The MessageChannelLink UUID stored on the interaction row.
    externalMessageId: typeof emailMeta.externalMessageId === "string" ? emailMeta.externalMessageId : null,
    // RFC2822 Message-ID (e.g. "<abc@mail.gmail.com>") for In-Reply-To / References headers.
    rfcMessageId: typeof emailMeta.rfcMessageId === "string" ? emailMeta.rfcMessageId : null,
    // entityId is the CustomerEntity id — on a person detail page this IS the personId.
    personId: activity.entityId ?? null,
    fromAddress: typeof emailMeta.fromAddress === "string" ? emailMeta.fromAddress : null,
    toAddresses: Array.isArray(emailMeta.toAddresses) ? emailMeta.toAddresses : null,
    ccAddresses: Array.isArray(emailMeta.ccAddresses) ? emailMeta.ccAddresses : null,
    subject: activity.title ?? null,
    inReplyTo: typeof emailMeta.inReplyTo === "string" ? emailMeta.inReplyTo : null,
    references: Array.isArray(emailMeta.references) ? emailMeta.references : null,
    currentVisibility: emailMeta.currentVisibility === "private" || emailMeta.currentVisibility === "shared" ? emailMeta.currentVisibility : null,
    isAuthor: typeof emailMeta.isAuthor === "boolean" ? emailMeta.isAuthor : null
  };
}
function ActivityCard({ activity, onOpen, onChanged, runMutation }) {
  const t = useT();
  const timestamp = activity.occurredAt ?? activity.scheduledAt ?? activity.createdAt;
  const TypeIcon = TYPE_ICONS[activity.interactionType] ?? StickyNote;
  const titleBase = activity.title ?? activity.body ?? activity.interactionType;
  const title = activity.duration ? `${titleBase} (${activity.duration} min)` : titleBase;
  const snippet = trimSnippet(activity.body && activity.title ? activity.body : activity.body ?? null);
  const actorLabel = activity.authorName ?? activity.authorEmail ?? t("customers.changelog.user.system", "System");
  const target = resolveTarget(activity);
  const direction = activity.interactionType === "email" ? t("customers.activityLog.direction.to", "to") : activity.interactionType === "call" || activity.interactionType === "meeting" ? t("customers.activityLog.direction.with", "with") : "";
  const showExternalLink = Boolean(activity._integrations && Object.keys(activity._integrations).length > 0);
  const [markingDone, setMarkingDone] = React.useState(false);
  const handleMarkDone = React.useCallback(async () => {
    if (markingDone) return;
    setMarkingDone(true);
    try {
      const operation = () => apiCallOrThrow("/api/customers/interactions/complete", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ id: activity.id, occurredAt: (/* @__PURE__ */ new Date()).toISOString() })
      });
      if (runMutation) {
        await runMutation(operation, {
          id: activity.id,
          status: "done",
          operation: "completeActivity"
        });
      } else {
        await operation();
      }
      flash(t("customers.activities.actions.markDoneSuccess", "Activity marked done"), "success");
      onChanged?.();
    } catch (err) {
      logger.warn("Mark done failed", { component: "ActivityCard", activityId: activity.id, err });
      flash(t("customers.activities.actions.markDoneError", "Could not mark activity as done"), "error");
    } finally {
      setMarkingDone(false);
    }
  }, [activity.id, markingDone, onChanged, runMutation, t]);
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: cn(
        "grid gap-3",
        onOpen ? "cursor-pointer" : ""
      ),
      style: { gridTemplateColumns: "64px 36px minmax(0,1fr)" },
      onClick: () => onOpen?.(activity),
      role: onOpen ? "button" : void 0,
      tabIndex: onOpen ? 0 : void 0,
      onKeyDown: onOpen ? (event) => {
        if (event.key === "Enter" || event.key === " ") {
          event.preventDefault();
          onOpen(activity);
        }
      } : void 0,
      children: [
        /* @__PURE__ */ jsxs("div", { className: "pt-1 text-xs text-muted-foreground", children: [
          /* @__PURE__ */ jsx("div", { className: "font-semibold text-foreground", children: formatDayLabel(timestamp, t) }),
          /* @__PURE__ */ jsx("div", { children: formatTimeLabel(timestamp) })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "flex size-9 items-center justify-center rounded-lg bg-muted/80", children: /* @__PURE__ */ jsx(TypeIcon, { className: "size-4 text-muted-foreground" }) }),
        /* @__PURE__ */ jsxs("div", { className: "rounded-xl border bg-card px-4 py-3 shadow-sm", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
              /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
                /* @__PURE__ */ jsx("h4", { className: "truncate text-sm font-semibold text-foreground", children: title }),
                showExternalLink ? /* @__PURE__ */ jsx(ExternalLink, { className: "size-3.5 text-muted-foreground" }) : null
              ] }),
              activity.location ? /* @__PURE__ */ jsxs("div", { className: "mt-1 flex items-center gap-1 text-xs text-muted-foreground", children: [
                /* @__PURE__ */ jsx(Calendar, { className: "size-3.5" }),
                /* @__PURE__ */ jsx("span", { className: "truncate", children: activity.location })
              ] }) : null
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
              isOpenInteractionStatus(activity.status) ? /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  variant: "default",
                  size: "sm",
                  disabled: markingDone,
                  onClick: (event) => {
                    event.stopPropagation();
                    void handleMarkDone();
                  },
                  children: [
                    /* @__PURE__ */ jsx(Check, { className: "size-3.5" }),
                    t("customers.activities.actions.markDone", "Mark done")
                  ]
                }
              ) : null,
              /* @__PURE__ */ jsx(
                IconButton,
                {
                  type: "button",
                  variant: "ghost",
                  size: "sm",
                  "aria-label": t("customers.timeline.more", "More"),
                  onClick: (event) => {
                    event.stopPropagation();
                    onOpen?.(activity);
                  },
                  children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "size-4" })
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsx("div", { className: "mt-2", children: /* @__PURE__ */ jsx(ActivityAiActions, { activityType: activity.interactionType }) }),
          activity.interactionType === "email" ? /* @__PURE__ */ jsx(
            "div",
            {
              className: "mt-1",
              onClick: (event) => event.stopPropagation(),
              onKeyDown: (event) => event.stopPropagation(),
              role: "presentation",
              children: /* @__PURE__ */ jsx(EmailCardActions, { data: buildEmailCardWidgetData(activity) })
            }
          ) : null,
          snippet ? /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm text-muted-foreground", children: snippet }) : null,
          /* @__PURE__ */ jsxs("div", { className: "mt-3 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground", children: [
            /* @__PURE__ */ jsx(Avatar, { label: actorLabel, size: "xs", variant: "monochrome" }),
            /* @__PURE__ */ jsx("span", { className: "font-medium text-foreground", children: actorLabel }),
            target && direction ? /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx("span", { children: "\xB7" }),
              /* @__PURE__ */ jsx("span", { children: direction }),
              /* @__PURE__ */ jsx("span", { className: "text-foreground", children: target })
            ] }) : null
          ] })
        ] })
      ]
    }
  );
}
var ActivityCard_default = ActivityCard;
export {
  ActivityCard,
  ActivityCard_default as default
};
//# sourceMappingURL=ActivityCard.js.map
