"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { RadioGroup, Radio } from "@open-mercato/ui/primitives/radio";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { useT } from "@open-mercato/shared/lib/i18n/context";
const SAVE_CONTEXT_ID = "customers-address-format-settings";
function AddressFormatSettings() {
  const t = useT();
  const [format, setFormat] = React.useState("line_first");
  const [loading, setLoading] = React.useState(true);
  const [pending, setPending] = React.useState(null);
  const [error, setError] = React.useState(null);
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: SAVE_CONTEXT_ID,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const options = React.useMemo(
    () => [
      {
        id: "line_first",
        title: t("customers.config.addressFormat.lineFirstTitle", "Address lines first"),
        description: t(
          "customers.config.addressFormat.lineFirstDescription",
          "Collect address line 1 and 2, then postal code, city, region, and country."
        )
      },
      {
        id: "street_first",
        title: t("customers.config.addressFormat.streetFirstTitle", "Street-first (European)"),
        description: t(
          "customers.config.addressFormat.streetFirstDescription",
          "Collect street, building and flat numbers before postal code, city, region, and country."
        )
      }
    ],
    [t]
  );
  React.useEffect(() => {
    let cancelled = false;
    async function load() {
      try {
        setLoading(true);
        const call = await apiCall("/api/customers/settings/address-format");
        const payload = call.result ?? {};
        if (!call.ok) {
          const message = typeof payload?.error === "string" ? String(payload.error) : t("customers.config.addressFormat.error", "Failed to load address settings");
          if (!cancelled) setError(message);
          return;
        }
        const valueRaw = payload?.addressFormat;
        const value = typeof valueRaw === "string" ? valueRaw : null;
        if (!cancelled && (value === "line_first" || value === "street_first")) {
          setFormat(value);
        }
      } catch (err) {
        if (!cancelled) {
          const message = err instanceof Error && err.message ? err.message : t("customers.config.addressFormat.error", "Failed to load address settings");
          setError(message);
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    load().catch(() => {
    });
    return () => {
      cancelled = true;
    };
  }, [t]);
  const handleChange = React.useCallback(
    async (next) => {
      if (next === format) return;
      setPending(next);
      setError(null);
      try {
        await runMutation({
          // optimistic-lock-exempt: single-row tenant address-format preference toggle — no per-record version / concurrent record edit
          operation: async () => {
            const call = await apiCall(
              "/api/customers/settings/address-format",
              {
                method: "PUT",
                headers: { "content-type": "application/json" },
                body: JSON.stringify({ addressFormat: next })
              }
            );
            const payload = call.result ?? {};
            if (!call.ok) {
              const message = typeof payload?.error === "string" ? payload.error : t("customers.config.addressFormat.errorSave", "Failed to update address settings");
              throw new Error(message);
            }
          },
          context: {
            formId: SAVE_CONTEXT_ID,
            resourceKind: "customers.settings",
            retryLastMutation
          },
          mutationPayload: { addressFormat: next }
        });
        setFormat(next);
        flash(t("customers.config.addressFormat.success", "Address format updated"), "success");
      } catch (err) {
        const message = err instanceof Error && err.message ? err.message : t("customers.config.addressFormat.errorSave", "Failed to update address settings");
        setError(message);
        flash(message, "error");
      } finally {
        setPending(null);
      }
    },
    [format, retryLastMutation, runMutation, t]
  );
  return /* @__PURE__ */ jsxs("section", { className: "space-y-4 rounded-lg border bg-background p-4", children: [
    /* @__PURE__ */ jsxs("header", { className: "space-y-1", children: [
      /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("customers.config.addressFormat.title", "Customer address format") }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t(
        "customers.config.addressFormat.description",
        "Choose how address forms and displays should be structured across the customer module."
      ) })
    ] }),
    loading ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
      /* @__PURE__ */ jsx(Spinner, { className: "h-4 w-4" }),
      t("customers.config.addressFormat.loading", "Loading current preference\u2026")
    ] }) : /* @__PURE__ */ jsxs(
      RadioGroup,
      {
        className: "space-y-3",
        value: format,
        onValueChange: (next) => handleChange(next),
        name: "address-format",
        children: [
          options.map((option) => {
            const inputId = `address-format-${option.id}`;
            return /* @__PURE__ */ jsxs("label", { htmlFor: inputId, className: "flex cursor-pointer items-start gap-3 rounded border p-3", children: [
              /* @__PURE__ */ jsx(
                Radio,
                {
                  id: inputId,
                  className: "mt-1",
                  value: option.id,
                  disabled: pending !== null && pending !== option.id
                }
              ),
              /* @__PURE__ */ jsxs("span", { className: "space-y-1", children: [
                /* @__PURE__ */ jsx("span", { className: "block text-sm font-medium", children: option.title }),
                /* @__PURE__ */ jsx("span", { className: "block text-xs text-muted-foreground", children: option.description })
              ] })
            ] }, option.id);
          }),
          error ? /* @__PURE__ */ jsx("p", { className: "text-sm text-status-error-text", children: error }) : null,
          pending ? /* @__PURE__ */ jsxs("div", { className: "inline-flex items-center gap-2 rounded border border-dashed px-3 py-1 text-xs text-muted-foreground", children: [
            /* @__PURE__ */ jsx(Spinner, { className: "h-3 w-3" }),
            t("customers.config.addressFormat.updating", "Saving preference\u2026")
          ] }) : null
        ]
      }
    )
  ] });
}
var AddressFormatSettings_default = AddressFormatSettings;
export {
  AddressFormatSettings,
  AddressFormatSettings_default as default
};
//# sourceMappingURL=AddressFormatSettings.js.map
