"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { MarkdownContent } from "@open-mercato/ui/backend/markdown/MarkdownContent";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { Button } from "@open-mercato/ui/primitives/button";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import {
  getMessageUiComponentRegistry
} from "../../../../components/utils/typeUiRegistry.js";
import { getMessageObjectType } from "../../../../lib/message-objects-registry.js";
import { getMessageTypeOrDefault } from "../../../../lib/message-types-registry.js";
function isProtectedPreflight(data) {
  return data.requiresAuth && !("id" in data);
}
function toErrorMessage(payload) {
  if (!payload) return null;
  if (typeof payload === "string") return payload;
  if (Array.isArray(payload)) {
    for (const entry of payload) {
      const nested = toErrorMessage(entry);
      if (nested) return nested;
    }
    return null;
  }
  if (typeof payload === "object") {
    const record = payload;
    return toErrorMessage(record.error) ?? toErrorMessage(record.message) ?? toErrorMessage(record.detail) ?? toErrorMessage(record.details) ?? null;
  }
  return null;
}
function formatDateTime(value) {
  if (!value) return "\u2014";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "\u2014";
  return date.toLocaleString();
}
function toObjectActions(objectActions) {
  return objectActions.map((action) => ({
    id: action.id,
    labelKey: action.labelKey,
    variant: action.variant,
    icon: action.icon,
    commandId: action.commandId,
    href: action.href,
    isTerminal: action.isTerminal,
    confirmRequired: action.confirmRequired,
    confirmMessage: action.confirmMessage
  }));
}
function mergeTokenActions(messageActions, defaultActions) {
  const deduped = /* @__PURE__ */ new Map();
  for (const action of messageActions?.actions ?? []) {
    const normalizedId = action.id.trim();
    if (!normalizedId) continue;
    deduped.set(normalizedId, { ...action, id: normalizedId });
  }
  for (const action of defaultActions ?? []) {
    const normalizedId = action.id.trim();
    if (!normalizedId || deduped.has(normalizedId)) continue;
    deduped.set(normalizedId, { ...action, id: normalizedId });
  }
  const actions = Array.from(deduped.values());
  if (actions.length === 0 && !messageActions?.expiresAt) return null;
  return {
    actions,
    primaryActionId: messageActions?.primaryActionId,
    expiresAt: messageActions?.expiresAt
  };
}
function MessageTokenPage({ params }) {
  const t = useT();
  const messageUiRegistry = React.useMemo(() => getMessageUiComponentRegistry(), []);
  const token = params?.token;
  const [loading, setLoading] = React.useState(true);
  const [data, setData] = React.useState(null);
  const [errorMessage, setErrorMessage] = React.useState(null);
  const [errorStatus, setErrorStatus] = React.useState(null);
  React.useEffect(() => {
    let mounted = true;
    async function run() {
      if (!token) return;
      setLoading(true);
      setData(null);
      setErrorMessage(null);
      setErrorStatus(null);
      try {
        const call = await apiCall(`/api/messages/token/${encodeURIComponent(token)}`);
        if (!mounted) return;
        if (!call.ok || !call.result) {
          const status = call.status;
          setErrorStatus(status);
          const fallback = status === 404 ? t("messages.token.errors.notFound", "This message link is invalid or has already been used.") : status === 409 ? t("messages.token.errors.limitExceeded", "This message link reached its usage limit.") : status === 410 ? t("messages.token.errors.expired", "This message link has expired.") : t("messages.token.errors.generic", "Unable to load this message.");
          setErrorMessage(toErrorMessage(call.result) ?? fallback);
          return;
        }
        setData(call.result);
      } catch (error) {
        if (!mounted) return;
        setErrorMessage(
          error instanceof Error ? error.message : t("messages.token.errors.generic", "Unable to load this message.")
        );
      } finally {
        if (mounted) {
          setLoading(false);
        }
      }
    }
    void run();
    return () => {
      mounted = false;
    };
  }, [t, token]);
  if (loading) {
    return /* @__PURE__ */ jsx("main", { className: "mx-auto max-w-3xl p-6", children: /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
      /* @__PURE__ */ jsx(Spinner, { className: "h-4 w-4 animate-spin" }),
      t("messages.token.loading", "Loading message...")
    ] }) });
  }
  if (errorMessage || !data) {
    return /* @__PURE__ */ jsxs("main", { className: "mx-auto max-w-3xl space-y-3 p-6", children: [
      /* @__PURE__ */ jsx("h1", { className: "text-2xl font-semibold", children: t("messages.token.pageTitle", "Message") }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: errorMessage ?? t("messages.token.errors.generic", "Unable to load this message.") }),
      errorStatus ? /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
        "HTTP ",
        errorStatus
      ] }) : null
    ] });
  }
  if (isProtectedPreflight(data)) {
    return /* @__PURE__ */ jsxs("main", { className: "mx-auto max-w-3xl space-y-4 p-6", children: [
      /* @__PURE__ */ jsx("h1", { className: "text-2xl font-semibold", children: t("messages.token.authRequired.title", "Sign in required") }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("messages.token.authRequired.description", "This message includes protected objects. Sign in to continue.") }),
      /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/login", children: t("auth.signIn", "Sign in") }) })
    ] });
  }
  const messageType = getMessageTypeOrDefault(data.type);
  const contentComponentKey = messageType.ui?.contentComponent;
  const actionsComponentKey = messageType.ui?.actionsComponent;
  const ContentComponent = contentComponentKey ? messageUiRegistry.contentComponents[contentComponentKey] ?? null : null;
  const ActionsComponent = actionsComponentKey ? messageUiRegistry.actionsComponents[actionsComponentKey] ?? null : null;
  const resolvedActionData = mergeTokenActions(data.actionData ?? null, messageType.defaultActions);
  const contentProps = {
    message: {
      id: data.id,
      type: data.type,
      subject: data.subject,
      body: data.body,
      bodyFormat: data.bodyFormat,
      priority: data.priority,
      sentAt: data.sentAt ? new Date(data.sentAt) : null,
      senderUserId: data.senderUserId,
      actionData: resolvedActionData,
      actionTaken: data.actionTaken ?? null,
      actionTakenAt: data.actionTakenAt ? new Date(data.actionTakenAt) : null
    },
    objects: data.objects.map((objectItem) => ({
      id: objectItem.id,
      entityModule: objectItem.entityModule,
      entityType: objectItem.entityType,
      entityId: objectItem.entityId,
      actionRequired: objectItem.actionRequired,
      snapshot: objectItem.snapshot ?? void 0
    })),
    attachments: []
  };
  const tokenActions = resolvedActionData?.actions ?? [];
  return /* @__PURE__ */ jsxs("main", { className: "mx-auto max-w-3xl space-y-6 p-6", children: [
    /* @__PURE__ */ jsxs("header", { className: "space-y-1", children: [
      /* @__PURE__ */ jsx("h1", { className: "text-2xl font-semibold", children: data.subject }),
      /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground", children: [
        t("messages.token.sentAt", "Sent"),
        ": ",
        formatDateTime(data.sentAt)
      ] })
    ] }),
    /* @__PURE__ */ jsx("section", { className: "rounded-xl border bg-card p-4", children: ContentComponent ? /* @__PURE__ */ jsx(ContentComponent, { ...contentProps }) : /* @__PURE__ */ jsx(
      MarkdownContent,
      {
        body: data.body,
        format: data.bodyFormat,
        className: "text-sm whitespace-pre-wrap [&>*]:mb-2 [&>*:last-child]:mb-0 [&_ul]:ml-4 [&_ul]:list-disc [&_ol]:ml-4 [&_ol]:list-decimal [&_code]:rounded [&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5 [&_pre]:rounded-md [&_pre]:bg-muted [&_pre]:p-3 [&_pre]:text-xs"
      }
    ) }),
    tokenActions.length > 0 ? /* @__PURE__ */ jsxs("section", { className: "space-y-3 rounded-xl border bg-card p-4", children: [
      /* @__PURE__ */ jsx("h2", { className: "text-base font-semibold", children: t("messages.actions.title", "Actions") }),
      ActionsComponent ? /* @__PURE__ */ jsx(
        ActionsComponent,
        {
          message: {
            id: data.id,
            type: data.type,
            actionData: resolvedActionData,
            actionTaken: data.actionTaken ?? null
          },
          onExecuteAction: async (_actionId) => {
            return;
          },
          isExecuting: false,
          executingActionId: null
        }
      ) : /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: tokenActions.map((action) => /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: action.variant ?? "default",
          disabled: true,
          children: t(action.labelKey ?? action.label, action.label)
        },
        action.id
      )) })
    ] }) : null,
    /* @__PURE__ */ jsxs("section", { className: "space-y-2 rounded-xl border bg-card p-4", children: [
      /* @__PURE__ */ jsx("h2", { className: "text-base font-semibold", children: t("messages.attachedObjects", "Attached objects") }),
      data.objects.length === 0 ? null : /* @__PURE__ */ jsx("div", { className: "space-y-2", children: data.objects.map((objectItem) => {
        const objectType = getMessageObjectType(objectItem.entityModule, objectItem.entityType);
        const objectActions = toObjectActions(objectType?.actions ?? []);
        const detailComponentKey = `${objectItem.entityModule}:${objectItem.entityType}`;
        const DetailComponent = messageUiRegistry.objectDetailComponents[detailComponentKey] ?? null;
        return DetailComponent ? /* @__PURE__ */ jsx(
          DetailComponent,
          {
            entityId: objectItem.entityId,
            entityModule: objectItem.entityModule,
            entityType: objectItem.entityType,
            snapshot: objectItem.snapshot ?? void 0,
            previewData: void 0,
            actionRequired: objectItem.actionRequired,
            actionType: objectItem.actionType ?? void 0,
            actionLabel: objectItem.actionLabel ?? void 0,
            actions: objectActions,
            actionTaken: data.actionTaken ?? null,
            actionTakenAt: data.actionTakenAt ? new Date(data.actionTakenAt) : null,
            actionTakenByUserId: data.actionTakenByUserId ?? null,
            icon: objectType?.icon,
            onAction: async () => {
              return;
            }
          },
          objectItem.id
        ) : null;
      }) })
    ] })
  ] });
}
export {
  MessageTokenPage as default
};
//# sourceMappingURL=page.js.map
