"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { Button } from "@open-mercato/ui/primitives/button";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { LoadingMessage, ErrorMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { useT, useLocale } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import {
  ArrowLeft,
  CheckCircle,
  XCircle,
  AlertTriangle,
  CheckCheck,
  Loader2,
  ExternalLink,
  RefreshCw,
  Users,
  Languages,
  Pencil
} from "lucide-react";
import { ActionCard, ConfidenceBadge, useActionTypeLabels, useDiscrepancyDescriptions } from "../../../../components/proposals/ActionCard.js";
import { CategoryBadge, CATEGORY_CONFIG, ALL_CATEGORIES, useCategoryLabels } from "../../../../components/proposals/CategoryBadge.js";
import { hasContactNameIssue } from "../../../../lib/contactValidation.js";
import { EditActionDialog } from "../../../../components/proposals/EditActionDialog.js";
function EmailThreadViewer({ email }) {
  const t = useT();
  if (!email) return null;
  const messages = email.threadMessages || [];
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsx("h3", { className: "font-semibold text-sm", children: t("inbox_ops.email_thread", "Email Thread") }),
    messages.length > 0 ? messages.map((msg, index) => /* @__PURE__ */ jsxs("div", { className: "border rounded-lg p-3 md:p-4 bg-card", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", children: [
          /* @__PURE__ */ jsx("div", { className: "text-sm font-medium truncate", children: msg.from?.name || msg.from?.email || t("inbox_ops.sender_unknown", "Unknown") }),
          /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground truncate", children: msg.from?.email })
        ] }),
        /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground whitespace-nowrap", children: msg.date ? new Date(msg.date).toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }) : "" })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "text-sm whitespace-pre-wrap text-foreground/80", children: msg.body })
    ] }, index)) : email.cleanedText ? /* @__PURE__ */ jsx("div", { className: "border rounded-lg p-3 md:p-4 bg-card", children: /* @__PURE__ */ jsx("div", { className: "text-sm whitespace-pre-wrap text-foreground/80", children: email.cleanedText }) }) : /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("inbox_ops.no_email_content", "No email content available") })
  ] });
}
function CategoryEditDropdown({
  currentCategory,
  onSelect,
  disabled
}) {
  const t = useT();
  const labels = useCategoryLabels();
  const [isOpen, setIsOpen] = React.useState(false);
  const dropdownRef = React.useRef(null);
  React.useEffect(() => {
    function handleClickOutside(event) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    }
    function handleEscape(event) {
      if (event.key === "Escape") setIsOpen(false);
    }
    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      document.addEventListener("keydown", handleEscape);
    }
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("keydown", handleEscape);
    };
  }, [isOpen]);
  return /* @__PURE__ */ jsxs("div", { className: "relative inline-block", ref: dropdownRef, children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
      /* @__PURE__ */ jsx(CategoryBadge, { category: currentCategory }),
      /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: "ghost",
          size: "sm",
          className: "h-6 w-6 p-0",
          onClick: () => setIsOpen(!isOpen),
          disabled,
          title: t("inbox_ops.recategorize", "Change Category"),
          children: /* @__PURE__ */ jsx(Pencil, { className: "h-3 w-3" })
        }
      )
    ] }),
    isOpen && /* @__PURE__ */ jsx("div", { className: "absolute top-full left-0 mt-1 z-dropdown w-48 rounded-md border bg-popover shadow-md", children: /* @__PURE__ */ jsx("div", { className: "p-1", children: ALL_CATEGORIES.map((cat) => {
      const config = CATEGORY_CONFIG[cat];
      const { Icon } = config;
      return /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "ghost",
          size: "sm",
          className: `flex items-center gap-2 w-full justify-start rounded-sm px-2 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground ${currentCategory === cat ? "bg-accent" : ""}`,
          onClick: () => {
            onSelect(cat);
            setIsOpen(false);
          },
          children: [
            /* @__PURE__ */ jsx(Icon, { className: "h-3.5 w-3.5" }),
            labels[cat] || cat
          ]
        },
        cat
      );
    }) }) })
  ] });
}
function ProposalDetailPage({ params }) {
  const t = useT();
  const locale = useLocale();
  const router = useRouter();
  const proposalId = params?.id;
  const [proposal, setProposal] = React.useState(null);
  const [actions, setActions] = React.useState([]);
  const [discrepancies, setDiscrepancies] = React.useState([]);
  const [email, setEmail] = React.useState(null);
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const [isProcessing, setIsProcessing] = React.useState(false);
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const { runMutation } = useGuardedMutation({
    contextId: "inbox-ops-proposal-detail"
  });
  const actionTypeLabels = useActionTypeLabels();
  const resolveDiscrepancyDescription = useDiscrepancyDescriptions();
  const [editingAction, setEditingAction] = React.useState(null);
  const [sendingReplyId, setSendingReplyId] = React.useState(null);
  const [translation, setTranslation] = React.useState(null);
  const [isTranslating, setIsTranslating] = React.useState(false);
  const [showTranslation, setShowTranslation] = React.useState(false);
  const handleEditAction = React.useCallback((action) => {
    if (action.actionType === "create_order" || action.actionType === "create_quote") {
      const kind = action.actionType === "create_order" ? "order" : "quote";
      try {
        sessionStorage.setItem(
          "inbox_ops.orderDraft",
          JSON.stringify({
            actionId: action.id,
            proposalId: action.proposalId,
            payload: action.payload
          })
        );
      } catch {
      }
      router.push(`/backend/sales/documents/create?kind=${kind}&fromInboxAction=${encodeURIComponent(action.id)}`);
      return;
    }
    if (action.actionType === "create_product") {
      try {
        sessionStorage.setItem(
          "inbox_ops.productDraft",
          JSON.stringify({
            actionId: action.id,
            proposalId: action.proposalId,
            payload: action.payload
          })
        );
      } catch {
      }
      router.push(`/backend/catalog/products/create?fromInboxAction=${encodeURIComponent(action.id)}`);
      return;
    }
    setEditingAction(action);
  }, [router]);
  const handleTranslate = React.useCallback(async () => {
    if (!proposalId) return;
    setIsTranslating(true);
    const result = await runMutation({
      operation: () => apiCall(
        `/api/inbox_ops/proposals/${proposalId}/translate`,
        { method: "POST", body: JSON.stringify({ targetLocale: locale }) }
      ),
      context: {}
    });
    if (result?.ok && result.result?.translation) {
      setTranslation(result.result.translation);
      setShowTranslation(true);
    } else {
      const detail = result?.result?.error;
      flash(detail ? `${t("inbox_ops.translate.failed", "Translation failed")}: ${detail}` : t("inbox_ops.translate.failed", "Translation failed"), "error");
    }
    setIsTranslating(false);
  }, [proposalId, locale, t, runMutation]);
  const handleCategorize = React.useCallback(async (category) => {
    if (!proposalId) return;
    const result = await runMutation({
      operation: () => apiCall(
        `/api/inbox_ops/proposals/${proposalId}/categorize`,
        { method: "POST", body: JSON.stringify({ category }) }
      ),
      context: {}
    });
    if (result?.ok && result.result?.ok) {
      setProposal((prev) => prev ? { ...prev, category: result.result.category } : prev);
    } else {
      flash(t("inbox_ops.flash.save_failed", "Failed to save"), "error");
    }
  }, [proposalId, t, runMutation]);
  const loadData = React.useCallback(async () => {
    if (!proposalId) return;
    setIsLoading(true);
    setError(null);
    setIsNotFound(false);
    try {
      const result = await apiCall(`/api/inbox_ops/proposals/${proposalId}`);
      if (result?.ok && result.result) {
        setProposal(result.result.proposal);
        setActions(result.result.actions || []);
        setDiscrepancies(result.result.discrepancies || []);
        setEmail(result.result.email);
      } else if (result?.status === 404) {
        setIsNotFound(true);
      } else {
        setError(t("inbox_ops.flash.load_failed", "Failed to load proposal"));
      }
    } catch {
      setError(t("inbox_ops.flash.load_failed", "Failed to load proposal"));
    }
    setIsLoading(false);
  }, [proposalId, t]);
  React.useEffect(() => {
    loadData();
  }, [loadData]);
  const handleAcceptAction = React.useCallback(async (actionId) => {
    setIsProcessing(true);
    const result = await runMutation({
      operation: () => apiCall(
        `/api/inbox_ops/proposals/${proposalId}/actions/${actionId}/accept`,
        { method: "POST" }
      ),
      context: {}
    });
    if (result?.ok && result.result?.ok) {
      flash(t("inbox_ops.flash.action_executed", "Action executed"), "success");
      await loadData();
    } else {
      flash(result?.result?.error || t("inbox_ops.flash.action_execute_failed", "Failed to execute action"), "error");
    }
    setIsProcessing(false);
  }, [proposalId, loadData, t, runMutation]);
  const handleRejectAction = React.useCallback(async (actionId) => {
    setIsProcessing(true);
    const result = await runMutation({
      operation: () => apiCall(
        `/api/inbox_ops/proposals/${proposalId}/actions/${actionId}/reject`,
        { method: "POST" }
      ),
      context: {}
    });
    if (result?.ok && result.result?.ok) {
      flash(t("inbox_ops.flash.action_rejected", "Action rejected"), "success");
      await loadData();
    } else {
      flash(t("inbox_ops.flash.action_reject_failed", "Failed to reject action"), "error");
    }
    setIsProcessing(false);
  }, [proposalId, loadData, runMutation]);
  const handleAcceptAll = React.useCallback(async () => {
    const pendingActions2 = actions.filter((a) => a.status === "pending");
    const pendingCount = pendingActions2.length;
    const nameIssueCount = pendingActions2.filter((a) => hasContactNameIssue(a)).length;
    const confirmText = nameIssueCount > 0 ? t("inbox_ops.action.accept_all_confirm_with_skip", "Execute {count} pending actions? {skipCount} contact actions will be skipped due to missing names.").replace("{count}", String(pendingCount)).replace("{skipCount}", String(nameIssueCount)) : t("inbox_ops.action.accept_all_confirm", "Execute {count} pending actions?").replace("{count}", String(pendingCount));
    const confirmed = await confirm({
      title: t("inbox_ops.action.accept_all", "Accept All"),
      text: confirmText
    });
    if (!confirmed) return;
    setIsProcessing(true);
    const result = await runMutation({
      operation: () => apiCall(
        `/api/inbox_ops/proposals/${proposalId}/accept-all`,
        { method: "POST" }
      ),
      context: {}
    });
    if (result?.ok && result.result?.ok) {
      const msg = result.result.failed > 0 ? t("inbox_ops.flash.accept_all_partial", "{succeeded} actions executed, {failed} failed").replace("{succeeded}", String(result.result.succeeded)).replace("{failed}", String(result.result.failed)) : t("inbox_ops.flash.accept_all_success", "{succeeded} actions executed").replace("{succeeded}", String(result.result.succeeded));
      flash(msg, "success");
      await loadData();
    } else {
      flash(t("inbox_ops.flash.accept_all_failed", "Failed to accept all actions"), "error");
    }
    setIsProcessing(false);
  }, [proposalId, actions, confirm, t, loadData, runMutation]);
  const handleRejectAll = React.useCallback(async () => {
    const confirmed = await confirm({
      title: t("inbox_ops.action.reject_all", "Reject Proposal"),
      text: t("inbox_ops.action.reject_all_confirm", "Reject all pending actions in this proposal?")
    });
    if (!confirmed) return;
    setIsProcessing(true);
    const result = await runMutation({
      operation: () => apiCall(
        `/api/inbox_ops/proposals/${proposalId}/reject`,
        { method: "POST" }
      ),
      context: {}
    });
    if (result?.ok && result.result?.ok) {
      flash(t("inbox_ops.action.proposal_rejected", "Proposal rejected"), "success");
      await loadData();
    }
    setIsProcessing(false);
  }, [proposalId, confirm, t, loadData, runMutation]);
  const handleRetryExtraction = React.useCallback(async () => {
    if (!email) return;
    setIsProcessing(true);
    const result = await runMutation({
      operation: () => apiCall(
        `/api/inbox_ops/emails/${email.id}/reprocess`,
        { method: "POST" }
      ),
      context: {}
    });
    if (result?.ok && result.result?.ok) {
      flash(t("inbox_ops.flash.reprocessing_started", "Reprocessing started"), "success");
      await loadData();
    }
    setIsProcessing(false);
  }, [email, loadData, runMutation]);
  const handleSendReply = React.useCallback(async (actionId) => {
    setSendingReplyId(actionId);
    const result = await runMutation({
      operation: () => apiCall(
        `/api/inbox_ops/proposals/${proposalId}/replies/${actionId}/send`,
        { method: "POST" }
      ),
      context: {}
    });
    if (result?.ok && result.result?.ok) {
      flash(t("inbox_ops.reply.sent_success", "Reply sent successfully"), "success");
      await loadData();
    } else {
      flash(result?.result?.error || t("inbox_ops.flash.send_reply_failed", "Failed to send reply"), "error");
    }
    setSendingReplyId(null);
  }, [proposalId, t, loadData, runMutation]);
  if (isLoading) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(LoadingMessage, { label: t("inbox_ops.loading_proposal", "Loading proposal...") }) }) });
  }
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("inbox_ops.proposal.notFound", "Proposal not found."),
        backHref: "/backend/inbox-ops",
        backLabel: t("inbox_ops.proposal.backToList", "Back to inbox")
      }
    ) }) });
  }
  if (error) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(ErrorMessage, { label: error }) }) });
  }
  const pendingActions = actions.filter((a) => a.status === "pending");
  const emailIsProcessing = email?.status === "processing";
  const emailFailed = email?.status === "failed";
  return /* @__PURE__ */ jsxs(Page, { children: [
    ConfirmDialogElement,
    editingAction && /* @__PURE__ */ jsx(
      EditActionDialog,
      {
        action: editingAction,
        actionTypeLabels,
        onClose: () => setEditingAction(null),
        onSaved: loadData
      }
    ),
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-4 py-3 md:px-6 md:py-4 border-b bg-background", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 md:gap-3 min-w-0", children: [
        /* @__PURE__ */ jsx(Link, { href: "/backend/inbox-ops", children: /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", size: "sm", children: /* @__PURE__ */ jsx(ArrowLeft, { className: "h-4 w-4" }) }) }),
        /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
          /* @__PURE__ */ jsx("h1", { className: "text-base md:text-lg font-semibold truncate", children: email?.subject || t("inbox_ops.proposal", "Proposal") }),
          /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground truncate", children: [
            email?.forwardedByName || email?.forwardedByAddress,
            " \xB7 ",
            email?.receivedAt && new Date(email.receivedAt).toLocaleString()
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 flex-shrink-0", children: [
        pendingActions.length > 0 && /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            className: "h-11 md:h-9 text-destructive border-destructive/30 hover:bg-destructive/10",
            onClick: handleRejectAll,
            disabled: isProcessing,
            children: [
              /* @__PURE__ */ jsx(XCircle, { className: "h-4 w-4 mr-1" }),
              /* @__PURE__ */ jsx("span", { className: "hidden md:inline", children: t("inbox_ops.action.reject_all", "Reject Proposal") })
            ]
          }
        ),
        pendingActions.length > 1 && /* @__PURE__ */ jsxs(Button, { type: "button", size: "sm", className: "h-11 md:h-9", onClick: handleAcceptAll, disabled: isProcessing, children: [
          isProcessing ? /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin mr-1" }) : /* @__PURE__ */ jsx(CheckCheck, { className: "h-4 w-4 mr-1" }),
          /* @__PURE__ */ jsx("span", { className: "hidden md:inline", children: t("inbox_ops.action.accept_all", "Accept All") })
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-6", children: [
      /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(EmailThreadViewer, { email }) }),
      /* @__PURE__ */ jsx("div", { className: "space-y-4", children: emailIsProcessing ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-center", children: [
        /* @__PURE__ */ jsx(Loader2, { className: "h-8 w-8 animate-spin text-primary mb-3" }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("inbox_ops.extraction_loading", "AI is analyzing this thread...") })
      ] }) : emailFailed ? /* @__PURE__ */ jsxs("div", { className: "border rounded-lg p-4 bg-status-error-bg border-status-error-border", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2", children: [
          /* @__PURE__ */ jsx(AlertTriangle, { className: "h-5 w-5 text-status-error-icon" }),
          /* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-status-error-text", children: t("inbox_ops.extraction_failed", "Extraction failed") })
        ] }),
        email?.processingError && /* @__PURE__ */ jsx("p", { className: "text-xs text-status-error-text mb-3", children: email.processingError }),
        /* @__PURE__ */ jsxs(Button, { type: "button", size: "sm", variant: "outline", onClick: handleRetryExtraction, disabled: isProcessing, children: [
          /* @__PURE__ */ jsx(RefreshCw, { className: "h-4 w-4 mr-1" }),
          t("inbox_ops.action.retry", "Retry")
        ] })
      ] }) : proposal ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsxs("div", { className: "border rounded-lg p-3 md:p-4", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mb-2", children: [
            /* @__PURE__ */ jsx("h3", { className: "font-semibold text-sm", children: t("inbox_ops.summary", "Summary") }),
            (proposal.workingLanguage || "en") !== locale && /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                variant: "ghost",
                size: "sm",
                className: "h-8 text-xs",
                onClick: showTranslation ? () => setShowTranslation(false) : handleTranslate,
                disabled: isTranslating,
                children: [
                  isTranslating ? /* @__PURE__ */ jsx(Loader2, { className: "h-3 w-3 animate-spin mr-1" }) : /* @__PURE__ */ jsx(Languages, { className: "h-3 w-3 mr-1" }),
                  showTranslation ? t("inbox_ops.translate.show_original", "Show original") : t("inbox_ops.translate.translate", "Translate")
                ]
              }
            )
          ] }),
          /* @__PURE__ */ jsx("p", { className: "text-sm text-foreground/80 mb-3", children: showTranslation && translation ? translation.summary : proposal.summary }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4 mb-3 flex-wrap", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t("inbox_ops.confidence", "Confidence") }),
              /* @__PURE__ */ jsx(ConfidenceBadge, { value: proposal.confidence })
            ] }),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground block", children: t("inbox_ops.category", "Category") }),
              /* @__PURE__ */ jsx(
                CategoryEditDropdown,
                {
                  currentCategory: proposal.category,
                  onSelect: handleCategorize,
                  disabled: isProcessing
                }
              )
            ] })
          ] }),
          proposal.possiblyIncomplete && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs text-status-warning-text bg-status-warning-bg rounded px-2 py-1 mb-3", children: [
            /* @__PURE__ */ jsx(AlertTriangle, { className: "h-3 w-3" }),
            t("inbox_ops.possibly_incomplete", "This thread appears to be a partial forward")
          ] }),
          proposal.participants.length > 0 && /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("h4", { className: "text-xs font-medium text-muted-foreground mb-1", children: t("inbox_ops.participants", "Participants") }),
            /* @__PURE__ */ jsx("div", { className: "space-y-1", children: proposal.participants.map((p, idx) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm", children: [
              /* @__PURE__ */ jsx(Users, { className: "h-3 w-3 text-muted-foreground" }),
              /* @__PURE__ */ jsx("span", { children: p.name }),
              /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground", children: [
                "(",
                p.role,
                ")"
              ] }),
              p.matchedContactId && /* @__PURE__ */ jsx(CheckCircle, { className: "h-3 w-3 text-status-success-icon" })
            ] }, idx)) })
          ] })
        ] }),
        (() => {
          const actionIds = new Set(actions.map((a) => a.id));
          const general = discrepancies.filter((d) => !d.resolved && (!d.actionId || !actionIds.has(d.actionId)));
          if (general.length === 0) return null;
          return /* @__PURE__ */ jsxs("div", { className: "border rounded-lg p-3 md:p-4 bg-status-warning-bg border-status-warning-border", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2", children: [
              /* @__PURE__ */ jsx(AlertTriangle, { className: "h-4 w-4 text-status-warning-icon" }),
              /* @__PURE__ */ jsx("h3", { className: "font-semibold text-sm text-status-warning-text", children: t("inbox_ops.discrepancies", "Issues Detected") })
            ] }),
            /* @__PURE__ */ jsx("div", { className: "space-y-1.5", children: general.map((d) => /* @__PURE__ */ jsxs("div", { className: `flex items-start gap-2 text-xs rounded px-2 py-1.5 ${d.severity === "error" ? "bg-status-error-bg text-status-error-text" : "bg-status-warning-bg text-status-warning-text"}`, children: [
              /* @__PURE__ */ jsx(AlertTriangle, { className: "h-3 w-3 mt-0.5 flex-shrink-0" }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx("span", { children: resolveDiscrepancyDescription(d.description, d.foundValue) }),
                (d.expectedValue || d.foundValue) && /* @__PURE__ */ jsxs("div", { className: "mt-0.5 text-overline opacity-80", children: [
                  d.expectedValue && /* @__PURE__ */ jsxs("span", { children: [
                    t("inbox_ops.discrepancy.expected", "Expected"),
                    ": ",
                    d.expectedValue
                  ] }),
                  d.expectedValue && d.foundValue && /* @__PURE__ */ jsx("span", { children: " \xB7 " }),
                  d.foundValue && /* @__PURE__ */ jsxs("span", { children: [
                    t("inbox_ops.discrepancy.found", "Found"),
                    ": ",
                    d.foundValue
                  ] })
                ] })
              ] })
            ] }, d.id)) })
          ] });
        })(),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("h3", { className: "font-semibold text-sm mb-2", children: t("inbox_ops.actions", "Proposed Actions") }),
          actions.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("inbox_ops.no_actions", "No actionable items detected in this thread") }) : /* @__PURE__ */ jsx("div", { className: "space-y-3", children: actions.map((action) => /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(
              ActionCard,
              {
                action,
                discrepancies,
                actionTypeLabels,
                onAccept: handleAcceptAction,
                onReject: handleRejectAction,
                onRetry: handleAcceptAction,
                onEdit: handleEditAction,
                translatedDescription: showTranslation ? translation?.actions[action.id] : void 0,
                resolveDiscrepancyDescription
              }
            ),
            action.actionType === "draft_reply" && (action.status === "executed" || action.status === "accepted") && /* @__PURE__ */ jsx("div", { className: "mt-2 pl-7", children: /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                size: "sm",
                variant: "outline",
                className: "h-11 md:h-9",
                disabled: sendingReplyId === action.id,
                onClick: () => handleSendReply(action.id),
                children: [
                  sendingReplyId === action.id ? /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin mr-1" }) : /* @__PURE__ */ jsx(ExternalLink, { className: "h-4 w-4 mr-1" }),
                  sendingReplyId === action.id ? t("inbox_ops.reply.sending", "Sending...") : t("inbox_ops.reply.send", "Send Reply")
                ]
              }
            ) })
          ] }, action.id)) })
        ] })
      ] }) : null })
    ] }) })
  ] });
}
export {
  ProposalDetailPage as default
};
//# sourceMappingURL=page.js.map
