"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { Button } from "@open-mercato/ui/primitives/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { apiCall, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { LoadingMessage, ErrorMessage } from "@open-mercato/ui/backend/detail";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { ArrowLeft, Copy, CheckCircle } from "lucide-react";
const LANGUAGE_KEYS = ["en", "de", "es", "pl"];
function InboxSettingsPage() {
  const t = useT();
  const { runMutation } = useGuardedMutation({
    contextId: "inbox-ops-settings"
  });
  const languageOptions = LANGUAGE_KEYS.map((key) => ({
    value: key,
    label: t(`inbox_ops.settings.language_${key}`, key)
  }));
  const [settings, setSettings] = React.useState(null);
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [copied, setCopied] = React.useState(false);
  const [isSavingLanguage, setIsSavingLanguage] = React.useState(false);
  React.useEffect(() => {
    let cancelled = false;
    async function load() {
      setIsLoading(true);
      setError(null);
      try {
        const result = await apiCall("/api/inbox_ops/settings");
        if (!cancelled) {
          if (result?.ok && result.result?.settings) {
            setSettings(result.result.settings);
          } else {
            setError(t("inbox_ops.settings.load_failed", "Failed to load settings"));
          }
        }
      } catch {
        if (!cancelled) setError(t("inbox_ops.settings.load_failed", "Failed to load settings"));
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, [t]);
  const handleCopy = React.useCallback(() => {
    if (settings?.inboxAddress) {
      navigator.clipboard.writeText(settings.inboxAddress);
      setCopied(true);
      setTimeout(() => setCopied(false), 2e3);
    }
  }, [settings]);
  const handleLanguageChange = React.useCallback(async (workingLanguage) => {
    setIsSavingLanguage(true);
    const result = await runMutation({
      operation: () => withScopedApiRequestHeaders(
        buildOptimisticLockHeader(settings?.updatedAt ?? null),
        () => apiCall("/api/inbox_ops/settings", {
          method: "PATCH",
          body: JSON.stringify({ workingLanguage })
        })
      ),
      context: {}
    });
    if (result?.ok && result.result?.ok) {
      setSettings((prev) => prev ? { ...prev, workingLanguage: result.result.settings.workingLanguage, updatedAt: result.result.settings.updatedAt ?? prev.updatedAt } : prev);
      flash(t("inbox_ops.settings.language_saved", "Working language updated"), "success");
    } else if (!surfaceRecordConflict({ status: result?.status, body: result?.result }, t)) {
      flash(t("inbox_ops.settings.language_save_failed", "Failed to update working language"), "error");
    }
    setIsSavingLanguage(false);
  }, [t, runMutation, settings?.updatedAt]);
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 px-3 py-3 md:px-6 md:py-4", 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__ */ jsx("h1", { className: "text-lg font-semibold", children: t("inbox_ops.settings.title", "Inbox Settings") })
    ] }),
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx("div", { className: "max-w-lg", children: isLoading ? /* @__PURE__ */ jsx(LoadingMessage, { label: t("inbox_ops.settings.loading", "Loading settings...") }) : error ? /* @__PURE__ */ jsx(ErrorMessage, { label: error }) : settings ? /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("label", { className: "text-sm font-medium text-foreground", children: t("inbox_ops.settings.forwarding_address", "Forwarding Address") }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1", children: t("inbox_ops.settings.forwarding_hint", "Forward email threads to this address to create proposals") }),
        /* @__PURE__ */ jsxs("div", { className: "mt-2 flex items-center gap-2", children: [
          /* @__PURE__ */ jsx("div", { className: "flex-1 bg-muted rounded-lg px-4 py-3", children: /* @__PURE__ */ jsx("code", { className: "text-sm font-mono", children: settings.inboxAddress }) }),
          /* @__PURE__ */ jsxs(Button, { type: "button", variant: "outline", size: "sm", className: "h-11 md:h-9", onClick: handleCopy, children: [
            copied ? /* @__PURE__ */ jsx(CheckCircle, { className: "h-4 w-4 text-green-600" }) : /* @__PURE__ */ jsx(Copy, { className: "h-4 w-4" }),
            /* @__PURE__ */ jsx("span", { className: "ml-1", children: copied ? t("inbox_ops.settings.copied", "Copied") : t("inbox_ops.settings.copy", "Copy") })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("label", { className: "text-sm font-medium text-foreground", children: t("inbox_ops.settings.status", "Status") }),
        /* @__PURE__ */ jsx("div", { className: "mt-1", children: /* @__PURE__ */ jsx("span", { className: `inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${settings.isActive ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800"}`, children: settings.isActive ? t("inbox_ops.settings.active", "Active") : t("inbox_ops.settings.inactive", "Inactive") }) })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("label", { htmlFor: "working-language", className: "text-sm font-medium text-foreground", children: t("inbox_ops.settings.working_language", "Working Language") }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1", children: t("inbox_ops.settings.working_language_hint", "AI summaries and action descriptions will be generated in this language") }),
        /* @__PURE__ */ jsxs(
          Select,
          {
            value: settings.workingLanguage || "en",
            onValueChange: (value) => handleLanguageChange(value),
            disabled: isSavingLanguage,
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { id: "working-language", className: "mt-2 sm:w-[200px]", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
              /* @__PURE__ */ jsx(SelectContent, { children: languageOptions.map((opt) => /* @__PURE__ */ jsx(SelectItem, { value: opt.value, children: opt.label }, opt.value)) })
            ]
          }
        )
      ] })
    ] }) : /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("inbox_ops.settings.not_found", "No inbox settings found. Settings are created when a new tenant is provisioned.") }) }) })
  ] });
}
export {
  InboxSettingsPage as default
};
//# sourceMappingURL=page.js.map
