"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCall, apiCallOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { createCrud } from "@open-mercato/ui/backend/utils/crud";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { ErrorMessage, LoadingMessage, TabEmptyState } from "@open-mercato/ui/backend/detail";
import { Button } from "@open-mercato/ui/primitives/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { SwitchField } from "@open-mercato/ui/primitives/switch-field";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { AddressEditor } from "@open-mercato/core/modules/customers/components/AddressEditor";
import {
  AddressView,
  formatAddressString
} from "@open-mercato/core/modules/customers/utils/addressFormat";
import { Pencil, Plus, Save, Trash2 } from "lucide-react";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("sales");
const emptyDraft = {
  name: "",
  purpose: "",
  companyName: "",
  addressLine1: "",
  addressLine2: "",
  buildingNumber: "",
  flatNumber: "",
  city: "",
  region: "",
  postalCode: "",
  country: "",
  isPrimary: false
};
function normalizeAddressDraft(draft) {
  if (!draft) return null;
  const normalized = {};
  const assign = (key, target) => {
    const value = draft[key];
    if (typeof value === "string" && value.trim().length) normalized[target] = value.trim();
    if (typeof value === "boolean") normalized[target] = value;
  };
  assign("name", "name");
  assign("purpose", "purpose");
  assign("companyName", "companyName");
  assign("addressLine1", "addressLine1");
  assign("addressLine2", "addressLine2");
  assign("buildingNumber", "buildingNumber");
  assign("flatNumber", "flatNumber");
  assign("city", "city");
  assign("region", "region");
  assign("postalCode", "postalCode");
  assign("country", "country");
  assign("isPrimary", "isPrimary");
  return Object.keys(normalized).length ? normalized : null;
}
function draftFromSnapshot(snapshot) {
  const record = snapshot ?? {};
  return {
    name: typeof record.name === "string" ? record.name : "",
    purpose: typeof record.purpose === "string" ? record.purpose : "",
    companyName: typeof record.companyName === "string" ? record.companyName : "",
    addressLine1: typeof record.addressLine1 === "string" ? record.addressLine1 : "",
    addressLine2: typeof record.addressLine2 === "string" ? record.addressLine2 : "",
    buildingNumber: typeof record.buildingNumber === "string" ? record.buildingNumber : "",
    flatNumber: typeof record.flatNumber === "string" ? record.flatNumber : "",
    city: typeof record.city === "string" ? record.city : "",
    region: typeof record.region === "string" ? record.region : "",
    postalCode: typeof record.postalCode === "string" ? record.postalCode : "",
    country: typeof record.country === "string" ? record.country : "",
    isPrimary: record.isPrimary === true
  };
}
function deepEqual(a, b) {
  return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
}
function readStringField(item, keys) {
  for (const key of keys) {
    const value = item[key];
    if (typeof value === "string") return value;
  }
  return null;
}
function mapApiAddress(item, format) {
  const id = typeof item.id === "string" ? item.id : null;
  if (!id) return null;
  const read = (keys) => readStringField(item, keys);
  const value = {
    addressLine1: read(["address_line1", "addressLine1"]),
    addressLine2: read(["address_line2", "addressLine2"]),
    buildingNumber: read(["building_number", "buildingNumber"]),
    flatNumber: read(["flat_number", "flatNumber"]),
    city: read(["city"]),
    region: read(["region"]),
    postalCode: read(["postal_code", "postalCode"]),
    country: read(["country"]),
    companyName: read(["company_name", "companyName"])
  };
  const name = (read(["name"]) ?? "").trim();
  const purpose = (read(["purpose"]) ?? "").trim();
  const summary = formatAddressString(value, format);
  const label = name || summary || id;
  return { id, label, summary, value, name: name || null, purpose: purpose || null };
}
function mergeAddressOption(options, selected) {
  if (!selected) return options;
  if (options.some((option) => option.id === selected.id)) return options;
  return [selected, ...options];
}
function draftFromDocumentAddress(entry) {
  return {
    name: entry.name ?? "",
    purpose: entry.purpose ?? "",
    companyName: entry.companyName ?? entry.value.companyName ?? "",
    addressLine1: entry.value.addressLine1 ?? "",
    addressLine2: entry.value.addressLine2 ?? "",
    buildingNumber: entry.value.buildingNumber ?? "",
    flatNumber: entry.value.flatNumber ?? "",
    city: entry.value.city ?? "",
    region: entry.value.region ?? "",
    postalCode: entry.value.postalCode ?? "",
    country: entry.value.country ?? "",
    isPrimary: false
  };
}
function SalesDocumentAddressesSection({
  documentId,
  kind,
  customerId,
  shippingAddressId,
  billingAddressId,
  shippingAddressSnapshot,
  billingAddressSnapshot,
  lockedReason,
  onUpdated
}) {
  const t = useT();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const [addressOptions, setAddressOptions] = React.useState([]);
  const [addressesLoading, setAddressesLoading] = React.useState(false);
  const [addressesError, setAddressesError] = React.useState(null);
  const [addressFormat, setAddressFormat] = React.useState("line_first");
  const [useCustomShipping, setUseCustomShipping] = React.useState(!!shippingAddressSnapshot);
  const [useCustomBilling, setUseCustomBilling] = React.useState(
    billingAddressSnapshot ? true : !!shippingAddressSnapshot
  );
  const [sameAsShipping, setSameAsShipping] = React.useState(() => {
    if (shippingAddressSnapshot || billingAddressSnapshot) {
      return deepEqual(shippingAddressSnapshot, billingAddressSnapshot);
    }
    if (!billingAddressId) return true;
    return shippingAddressId === billingAddressId;
  });
  const [shippingAddressIdState, setShippingAddressId] = React.useState(shippingAddressId ?? null);
  const [billingAddressIdState, setBillingAddressId] = React.useState(
    billingAddressId ?? shippingAddressId ?? null
  );
  const [shippingDraft, setShippingDraft] = React.useState(
    draftFromSnapshot(shippingAddressSnapshot)
  );
  const [billingDraft, setBillingDraft] = React.useState(
    draftFromSnapshot(billingAddressSnapshot ?? (sameAsShipping ? shippingAddressSnapshot : null))
  );
  const [saveShippingAddress, setSaveShippingAddress] = React.useState(false);
  const [saveBillingAddress, setSaveBillingAddress] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [documentAddresses, setDocumentAddresses] = React.useState([]);
  const [documentAddressesLoading, setDocumentAddressesLoading] = React.useState(false);
  const [documentAddressesError, setDocumentAddressesError] = React.useState(null);
  const [additionalFormOpen, setAdditionalFormOpen] = React.useState(false);
  const [additionalUseCustom, setAdditionalUseCustom] = React.useState(false);
  const [additionalSelectedId, setAdditionalSelectedId] = React.useState("");
  const [additionalDraft, setAdditionalDraft] = React.useState(emptyDraft);
  const [additionalSaving, setAdditionalSaving] = React.useState(false);
  const [deletingAddressIds, setDeletingAddressIds] = React.useState(/* @__PURE__ */ new Set());
  const locked = Boolean(lockedReason);
  const [editingAddressId, setEditingAddressId] = React.useState(null);
  const [editingDraft, setEditingDraft] = React.useState(emptyDraft);
  const [editingSaving, setEditingSaving] = React.useState(false);
  const mutationContextId = React.useMemo(
    () => `sales-document-addresses:${kind}:${documentId}`,
    [documentId, kind]
  );
  const resourceKind = React.useMemo(() => kind === "order" ? "sales.order" : "sales.quote", [kind]);
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const mutationContext = React.useMemo(
    () => ({
      formId: mutationContextId,
      resourceKind,
      resourceId: documentId,
      kind,
      retryLastMutation
    }),
    [documentId, kind, mutationContextId, resourceKind, retryLastMutation]
  );
  const runGuardedMutation = React.useCallback(
    async (operation, mutationPayload) => runMutation({
      operation,
      mutationPayload,
      context: mutationContext
    }),
    [mutationContext, runMutation]
  );
  const customerRequired = !customerId;
  const addressOptionsMap = React.useMemo(() => {
    const map = /* @__PURE__ */ new Map();
    addressOptions.forEach((entry) => map.set(entry.id, entry));
    return map;
  }, [addressOptions]);
  const resolveAddressSummary = React.useCallback(
    (value) => {
      const summary = formatAddressString(value, addressFormat);
      if (summary) return summary;
      return value.addressLine1 ?? value.addressLine2 ?? value.city ?? value.region ?? value.postalCode ?? value.country ?? "";
    },
    [addressFormat]
  );
  React.useEffect(() => {
    setDocumentAddresses(
      (prev) => prev.map((entry) => ({
        ...entry,
        summary: resolveAddressSummary(entry.value)
      }))
    );
  }, [resolveAddressSummary]);
  React.useEffect(() => {
    if (editingAddressId && !documentAddresses.some((entry) => entry.id === editingAddressId)) {
      setEditingAddressId(null);
      setEditingDraft(emptyDraft);
      setEditingSaving(false);
    }
  }, [documentAddresses, editingAddressId]);
  const loadDocumentAddresses = React.useCallback(async () => {
    if (!documentId) return;
    setDocumentAddressesLoading(true);
    try {
      setDocumentAddressesError(null);
      const params = new URLSearchParams({ documentId, documentKind: kind });
      const call = await apiCall(
        `/api/sales/document-addresses?${params.toString()}`
      );
      if (call.ok && Array.isArray(call.result?.items)) {
        const mapped = call.result.items.map((item) => {
          const id = typeof item.id === "string" ? item.id : null;
          if (!id) return null;
          const read = (keys) => readStringField(item, keys);
          const value = {
            addressLine1: read(["address_line1", "addressLine1"]),
            addressLine2: read(["address_line2", "addressLine2"]),
            buildingNumber: read(["building_number", "buildingNumber"]),
            flatNumber: read(["flat_number", "flatNumber"]),
            city: read(["city"]),
            region: read(["region"]),
            postalCode: read(["postal_code", "postalCode"]),
            country: read(["country"]),
            companyName: read(["company_name", "companyName"])
          };
          return {
            id,
            value,
            summary: resolveAddressSummary(value),
            customerAddressId: read(["customer_address_id", "customerAddressId"]),
            name: read(["name"]),
            purpose: read(["purpose"]),
            companyName: value.companyName ?? null
          };
        }).filter((entry) => entry !== null);
        setDocumentAddresses(mapped);
      } else {
        setDocumentAddresses([]);
      }
    } catch (err) {
      logger.error("sales.documents.addresses.document.load", { err });
      const message = t("sales.documents.detail.addresses.loadError", "Failed to load addresses.");
      flash(message, "error");
      setDocumentAddressesError(message);
      setDocumentAddresses([]);
    } finally {
      setDocumentAddressesLoading(false);
    }
  }, [documentId, kind, resolveAddressSummary, t]);
  React.useEffect(() => {
    const shippingCustom = !!shippingAddressSnapshot;
    const billingCustom = !!billingAddressSnapshot;
    const nextSame = shippingAddressSnapshot || billingAddressSnapshot ? deepEqual(shippingAddressSnapshot, billingAddressSnapshot) : !billingAddressId || billingAddressId === shippingAddressId;
    setUseCustomShipping(shippingCustom);
    setUseCustomBilling(nextSame ? shippingCustom : billingCustom);
    setSameAsShipping(nextSame);
    setShippingDraft(draftFromSnapshot(shippingAddressSnapshot));
    setBillingDraft(
      draftFromSnapshot(
        nextSame ? billingAddressSnapshot ?? shippingAddressSnapshot ?? null : billingAddressSnapshot ?? null
      )
    );
    setShippingAddressId(shippingAddressId ?? null);
    setBillingAddressId(nextSame ? shippingAddressId ?? billingAddressId ?? null : billingAddressId ?? null);
    setSaveShippingAddress(false);
    setSaveBillingAddress(false);
  }, [billingAddressId, billingAddressSnapshot, documentId, shippingAddressId, shippingAddressSnapshot]);
  React.useEffect(() => {
    loadDocumentAddresses().catch(() => {
    });
  }, [loadDocumentAddresses]);
  React.useEffect(() => {
    if (!sameAsShipping) return;
    const nextUseCustomBilling = useCustomShipping;
    if (useCustomBilling !== nextUseCustomBilling) {
      setUseCustomBilling(nextUseCustomBilling);
    }
    if (useCustomShipping) {
      if (!deepEqual(shippingDraft, billingDraft)) {
        setBillingDraft(shippingDraft);
      }
      if (billingAddressIdState !== null) {
        setBillingAddressId(null);
      }
    } else {
      if (billingAddressIdState !== shippingAddressIdState) {
        setBillingAddressId(shippingAddressIdState);
      }
      if (!deepEqual(billingDraft, emptyDraft)) {
        setBillingDraft(emptyDraft);
      }
    }
  }, [
    billingAddressIdState,
    billingDraft,
    sameAsShipping,
    shippingAddressIdState,
    shippingDraft,
    useCustomBilling,
    useCustomShipping
  ]);
  const loadAddresses = React.useCallback(
    async (id) => {
      if (!id) {
        setAddressOptions([]);
        return;
      }
      setAddressesLoading(true);
      setAddressesError(null);
      try {
        const params = new URLSearchParams({ page: "1", pageSize: "50", entityId: id });
        const call = await apiCall(
          `/api/customers/addresses?${params.toString()}`
        );
        if (call.ok && Array.isArray(call.result?.items)) {
          const options = call.result.items.map((item) => mapApiAddress(item, addressFormat)).filter((entry) => !!entry);
          setAddressOptions(options);
        } else {
          setAddressOptions([]);
        }
      } catch (err) {
        logger.error("sales.documents.addresses.load", { err });
        const message = t("sales.documents.detail.addresses.loadError", "Failed to load addresses.");
        setAddressesError(message);
        flash(message, "error");
        setAddressOptions([]);
      } finally {
        setAddressesLoading(false);
      }
    },
    [addressFormat, t]
  );
  const loadAddressOptionById = React.useCallback(
    async (addressId) => {
      const call = await apiCall(
        `/api/customers/addresses?id=${encodeURIComponent(addressId)}&pageSize=1`
      );
      const items = Array.isArray(call.result?.items) ? call.result.items : [];
      return items.map((item) => mapApiAddress(item, addressFormat)).find((entry) => entry?.id === addressId) ?? null;
    },
    [addressFormat]
  );
  React.useEffect(() => {
    loadAddresses(customerId).catch(() => {
    });
  }, [customerId, loadAddresses]);
  React.useEffect(() => {
    const selectedIds = [shippingAddressIdState, billingAddressIdState].filter(
      (id) => typeof id === "string" && id.length > 0
    );
    const missingIds = selectedIds.filter((id) => !addressOptions.some((option) => option.id === id));
    if (!missingIds.length) return;
    Promise.all(missingIds.map((id) => loadAddressOptionById(id).catch(() => null))).then((selectedOptions) => {
      setAddressOptions(
        (current) => selectedOptions.reduce(
          (next, selected) => mergeAddressOption(next, selected),
          current
        )
      );
    }).catch(() => {
    });
  }, [addressOptions, billingAddressIdState, loadAddressOptionById, shippingAddressIdState]);
  const guardLocked = React.useCallback(() => {
    if (!locked) return false;
    if (lockedReason) {
      flash(lockedReason, "error");
    }
    return true;
  }, [locked, lockedReason]);
  React.useEffect(() => {
    setAddressOptions(
      (prev) => prev.map((entry) => {
        const summary = formatAddressString(entry.value, addressFormat);
        const label = (entry.name && entry.name.trim().length ? entry.name : "") || summary || entry.id;
        return { ...entry, summary, label };
      })
    );
  }, [addressFormat]);
  React.useEffect(() => {
    let cancelled = false;
    async function fetchAddressFormat() {
      try {
        const call = await apiCall("/api/customers/settings/address-format");
        const format = typeof call.result?.addressFormat === "string" ? call.result.addressFormat : null;
        if (!cancelled && (format === "street_first" || format === "line_first")) {
          setAddressFormat(format);
        }
      } catch (err) {
        logger.error("sales.documents.addresses.format", { err });
      }
    }
    fetchAddressFormat().catch(() => {
    });
    return () => {
      cancelled = true;
    };
  }, []);
  const shippingOptions = React.useMemo(() => {
    if (shippingAddressIdState && !addressOptions.some((entry) => entry.id === shippingAddressIdState)) {
      const fallback = {
        id: shippingAddressIdState,
        label: shippingAddressIdState,
        summary: "",
        value: { addressLine1: null }
      };
      return [fallback, ...addressOptions];
    }
    return addressOptions;
  }, [addressOptions, shippingAddressIdState]);
  const billingOptions = React.useMemo(() => {
    if (billingAddressIdState && !addressOptions.some((entry) => entry.id === billingAddressIdState)) {
      const fallback = {
        id: billingAddressIdState,
        label: billingAddressIdState,
        summary: "",
        value: { addressLine1: null }
      };
      return [fallback, ...addressOptions];
    }
    return addressOptions;
  }, [addressOptions, billingAddressIdState]);
  const handleAddAdditionalAddress = React.useCallback(async () => {
    if (guardLocked()) return;
    if (!customerId) {
      flash(t("sales.documents.form.address.customerRequired", "Select a customer first"), "error");
      return;
    }
    if (!additionalUseCustom && !additionalSelectedId) {
      flash(t("sales.documents.detail.addresses.select", "Select an address to add."), "error");
      return;
    }
    setAdditionalSaving(true);
    try {
      let resolvedValue = null;
      let customerAddressId = null;
      let name;
      let purpose;
      if (additionalUseCustom) {
        const normalized = normalizeAddressDraft(additionalDraft);
        name = normalized?.name ?? void 0;
        purpose = normalized?.purpose ?? void 0;
        resolvedValue = {
          addressLine1: normalized?.addressLine1 ?? normalized?.name ?? "Address",
          addressLine2: normalized?.addressLine2 ?? null,
          buildingNumber: normalized?.buildingNumber ?? null,
          flatNumber: normalized?.flatNumber ?? null,
          city: normalized?.city ?? null,
          region: normalized?.region ?? null,
          postalCode: normalized?.postalCode ?? null,
          country: normalized?.country ?? null,
          companyName: normalized?.companyName ?? null
        };
      } else {
        const option = addressOptionsMap.get(additionalSelectedId);
        if (option) {
          resolvedValue = option.value;
          customerAddressId = option.id;
          name = option.name ?? void 0;
          purpose = option.purpose ?? void 0;
        }
      }
      if (!resolvedValue || !resolvedValue.addressLine1) {
        throw new Error(t("sales.documents.detail.addresses.saveError", "Failed to update addresses."));
      }
      const call = await apiCallOrThrow(
        "/api/sales/document-addresses",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            documentId,
            documentKind: kind,
            customerAddressId: customerAddressId ?? void 0,
            name,
            purpose,
            addressLine1: resolvedValue.addressLine1,
            addressLine2: resolvedValue.addressLine2 ?? void 0,
            buildingNumber: resolvedValue.buildingNumber ?? void 0,
            flatNumber: resolvedValue.flatNumber ?? void 0,
            city: resolvedValue.city ?? void 0,
            region: resolvedValue.region ?? void 0,
            postalCode: resolvedValue.postalCode ?? void 0,
            country: resolvedValue.country ?? void 0,
            companyName: resolvedValue.companyName ?? void 0
          })
        },
        { errorMessage: t("sales.documents.detail.addresses.saveError", "Failed to update addresses.") }
      );
      const savedId = typeof call.result?.id === "string" ? call.result.id : null;
      const assignedValue = resolvedValue;
      setDocumentAddresses((prev) => [
        {
          id: savedId ?? `temp-${Date.now()}`,
          value: assignedValue,
          summary: resolveAddressSummary(assignedValue),
          customerAddressId: customerAddressId ?? null,
          name: name ?? null,
          purpose: purpose ?? null,
          companyName: assignedValue.companyName ?? null
        },
        ...prev.filter((entry) => !savedId || entry.id !== savedId)
      ]);
      if (additionalUseCustom || customerAddressId && !addressOptionsMap.has(customerAddressId)) {
        loadAddresses(customerId).catch(() => {
        });
      }
      setAdditionalFormOpen(false);
      setAdditionalUseCustom(false);
      setAdditionalSelectedId("");
      setAdditionalDraft(emptyDraft);
      flash(t("sales.documents.detail.updatedMessage", "Document updated."), "success");
    } catch (err) {
      const message = err instanceof Error && err.message ? err.message : t("sales.documents.detail.addresses.saveError", "Failed to update addresses.");
      flash(message, "error");
    } finally {
      setAdditionalSaving(false);
    }
  }, [
    additionalDraft,
    additionalSelectedId,
    additionalUseCustom,
    addressOptionsMap,
    customerId,
    documentId,
    kind,
    loadAddresses,
    resolveAddressSummary,
    t
  ]);
  const handleCancelEdit = React.useCallback(() => {
    setEditingAddressId(null);
    setEditingDraft(emptyDraft);
    setEditingSaving(false);
  }, []);
  const handleUpdateDocumentAddress = React.useCallback(async () => {
    if (!editingAddressId) return;
    const current = documentAddresses.find((entry) => entry.id === editingAddressId);
    if (!current) {
      handleCancelEdit();
      return;
    }
    if (guardLocked()) return;
    const normalizedRecord = normalizeAddressDraft(editingDraft) ?? {};
    const read = (key) => {
      const value = normalizedRecord[key];
      if (typeof value !== "string") return "";
      const trimmed = value.trim();
      return trimmed.length ? trimmed : "";
    };
    const addressLine1 = read("addressLine1");
    if (!addressLine1) {
      flash(t("sales.documents.detail.addresses.line1Required", "Add address line 1 to continue."), "error");
      return;
    }
    const updatedValue = {
      addressLine1,
      addressLine2: read("addressLine2") || null,
      buildingNumber: read("buildingNumber") || null,
      flatNumber: read("flatNumber") || null,
      city: read("city") || null,
      region: read("region") || null,
      postalCode: read("postalCode") || null,
      country: read("country") || null,
      companyName: read("companyName") || null
    };
    const nameValue = read("name") || null;
    const purposeValue = read("purpose") || null;
    setEditingSaving(true);
    try {
      const payload = {
        id: editingAddressId,
        documentId,
        documentKind: kind,
        customerAddressId: current.customerAddressId ?? void 0,
        name: nameValue,
        purpose: purposeValue,
        companyName: updatedValue.companyName,
        addressLine1: updatedValue.addressLine1,
        addressLine2: updatedValue.addressLine2,
        buildingNumber: updatedValue.buildingNumber,
        flatNumber: updatedValue.flatNumber,
        city: updatedValue.city,
        region: updatedValue.region,
        postalCode: updatedValue.postalCode,
        country: updatedValue.country
      };
      await runGuardedMutation(
        () => (
          // TODO(#2373-C): thread document updatedAt
          withScopedApiRequestHeaders(
            buildOptimisticLockHeader(void 0),
            () => apiCallOrThrow(
              "/api/sales/document-addresses",
              {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(payload)
              },
              { errorMessage: t("sales.documents.detail.addresses.saveError", "Failed to update addresses.") }
            )
          )
        ),
        payload
      );
      setDocumentAddresses(
        (prev) => prev.map(
          (entry) => entry.id === editingAddressId ? {
            ...entry,
            value: updatedValue,
            summary: resolveAddressSummary(updatedValue),
            name: nameValue,
            purpose: purposeValue,
            companyName: updatedValue.companyName ?? null
          } : entry
        )
      );
      flash(t("sales.documents.detail.updatedMessage", "Document updated."), "success");
      handleCancelEdit();
    } catch (err) {
      const message = err instanceof Error && err.message ? err.message : t("sales.documents.detail.addresses.saveError", "Failed to update addresses.");
      flash(message, "error");
    } finally {
      setEditingSaving(false);
    }
  }, [documentAddresses, documentId, editingAddressId, editingDraft, handleCancelEdit, kind, resolveAddressSummary, runGuardedMutation, t]);
  const handleDeleteDocumentAddress = React.useCallback(
    async (id) => {
      if (guardLocked()) return;
      const confirmMessage = t(
        "sales.documents.detail.addresses.deleteConfirm",
        "This will permanently remove this address from the document. Continue?"
      );
      const confirmed = await confirm({
        title: confirmMessage,
        variant: "destructive"
      });
      if (!confirmed) return;
      setDeletingAddressIds((prev) => {
        const next = new Set(prev);
        next.add(id);
        return next;
      });
      try {
        const payload = { id, documentId, documentKind: kind };
        await runGuardedMutation(
          () => (
            // TODO(#2373-C): thread document updatedAt
            withScopedApiRequestHeaders(
              buildOptimisticLockHeader(void 0),
              () => apiCallOrThrow(
                "/api/sales/document-addresses",
                {
                  method: "DELETE",
                  headers: { "Content-Type": "application/json" },
                  body: JSON.stringify(payload)
                },
                { errorMessage: t("sales.documents.detail.addresses.deleteError", "Failed to remove address.") }
              )
            )
          ),
          payload
        );
        setDocumentAddresses((prev) => prev.filter((entry) => entry.id !== id));
        if (editingAddressId === id) {
          handleCancelEdit();
        }
        flash(t("sales.documents.detail.addresses.removed", "Address unassigned."), "success");
      } catch (err) {
        const message = err instanceof Error && err.message ? err.message : t("sales.documents.detail.addresses.deleteError", "Failed to remove address.");
        flash(message, "error");
      } finally {
        setDeletingAddressIds((prev) => {
          const next = new Set(prev);
          next.delete(id);
          return next;
        });
      }
    },
    [confirm, documentId, editingAddressId, handleCancelEdit, kind, runGuardedMutation, t]
  );
  const handleSave = React.useCallback(async () => {
    if (guardLocked()) return;
    setSaving(true);
    try {
      const shippingSnapshot = useCustomShipping ? normalizeAddressDraft(shippingDraft) : null;
      let billingSnapshot = useCustomBilling ? normalizeAddressDraft(billingDraft) : null;
      const same = sameAsShipping;
      const payload = { id: documentId };
      if (same && useCustomShipping) {
        billingSnapshot = shippingSnapshot;
      }
      let shippingId = useCustomShipping ? null : shippingAddressIdState;
      let billingId = same ? useCustomShipping ? null : shippingAddressIdState : useCustomBilling ? null : billingAddressIdState;
      if (customerId && shippingSnapshot && useCustomShipping && saveShippingAddress) {
        const res = await createCrud("customers/addresses", {
          entityId: customerId,
          addressLine1: shippingSnapshot.addressLine1 ?? shippingSnapshot.name ?? "Address",
          name: shippingSnapshot.name ?? void 0,
          addressLine2: shippingSnapshot.addressLine2 ?? void 0,
          buildingNumber: shippingSnapshot.buildingNumber ?? void 0,
          flatNumber: shippingSnapshot.flatNumber ?? void 0,
          city: shippingSnapshot.city ?? void 0,
          region: shippingSnapshot.region ?? void 0,
          postalCode: shippingSnapshot.postalCode ?? void 0,
          country: shippingSnapshot.country ?? void 0,
          purpose: shippingSnapshot.purpose ?? void 0,
          isPrimary: shippingSnapshot.isPrimary ?? void 0
        });
        if (res?.result?.id) shippingId = res.result.id;
      }
      if (customerId && billingSnapshot && useCustomBilling && saveBillingAddress) {
        const res = await createCrud("customers/addresses", {
          entityId: customerId,
          addressLine1: billingSnapshot.addressLine1 ?? billingSnapshot.name ?? "Address",
          name: billingSnapshot.name ?? void 0,
          addressLine2: billingSnapshot.addressLine2 ?? void 0,
          buildingNumber: billingSnapshot.buildingNumber ?? void 0,
          flatNumber: billingSnapshot.flatNumber ?? void 0,
          city: billingSnapshot.city ?? void 0,
          region: billingSnapshot.region ?? void 0,
          postalCode: billingSnapshot.postalCode ?? void 0,
          country: billingSnapshot.country ?? void 0,
          purpose: billingSnapshot.purpose ?? void 0,
          isPrimary: billingSnapshot.isPrimary ?? void 0
        });
        if (res?.result?.id) billingId = res.result.id;
      }
      payload.shippingAddressSnapshot = shippingSnapshot ?? null;
      payload.billingAddressSnapshot = billingSnapshot ?? null;
      payload.shippingAddressId = shippingSnapshot ? null : shippingId;
      payload.billingAddressId = billingSnapshot ? null : billingId;
      const endpoint = kind === "order" ? "/api/sales/orders" : "/api/sales/quotes";
      const call = await runGuardedMutation(
        () => (
          // TODO(#2373-C): thread document updatedAt
          withScopedApiRequestHeaders(
            buildOptimisticLockHeader(void 0),
            () => apiCallOrThrow(
              endpoint,
              {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(payload)
              },
              { errorMessage: t("sales.documents.detail.updateError", "Failed to update document.") }
            )
          )
        ),
        payload
      );
      const result = call.result ?? {};
      onUpdated?.({
        shippingAddressId: result.shippingAddressId ?? payload.shippingAddressId ?? null,
        billingAddressId: result.billingAddressId ?? payload.billingAddressId ?? null,
        shippingAddressSnapshot: result.shippingAddressSnapshot ?? payload.shippingAddressSnapshot ?? null,
        billingAddressSnapshot: result.billingAddressSnapshot ?? payload.billingAddressSnapshot ?? null
      });
      if (customerId) {
        loadAddresses(customerId).catch(() => {
        });
      }
      flash(t("sales.documents.detail.updatedMessage", "Document updated."), "success");
    } catch (err) {
      const message = err instanceof Error && err.message ? err.message : t("sales.documents.detail.updateError", "Failed to update document.");
      flash(message, "error");
    } finally {
      setSaving(false);
    }
  }, [
    billingAddressIdState,
    billingDraft,
    customerId,
    documentId,
    kind,
    sameAsShipping,
    saveBillingAddress,
    saveShippingAddress,
    shippingAddressIdState,
    shippingDraft,
    t,
    loadAddresses,
    runGuardedMutation,
    useCustomBilling,
    useCustomShipping
  ]);
  const renderAddressSelect = (value, options, onChange, disabled) => {
    const selectedOption = options.find((addr) => addr.id === value) ?? null;
    const selectedLabel = selectedOption ? selectedOption.summary ? `${selectedOption.label} \u2014 ${selectedOption.summary}` : selectedOption.label : null;
    const optionsKey = options.map((addr) => `${addr.id}:${addr.summary ? `${addr.label} \u2014 ${addr.summary}` : addr.label}`).join("\0");
    return /* @__PURE__ */ jsxs(
      Select,
      {
        value: value || void 0,
        onValueChange: (next) => onChange(next || null),
        disabled,
        children: [
          /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(
            SelectValue,
            {
              placeholder: addressesLoading ? t("sales.documents.form.address.loading", "Loading addresses\u2026") : t("sales.documents.form.address.placeholder", "Select address"),
              children: selectedLabel ?? void 0
            }
          ) }),
          /* @__PURE__ */ jsx(SelectContent, { children: options.map((addr) => {
            const optionLabel = addr.summary ? `${addr.label} \u2014 ${addr.summary}` : addr.label;
            return /* @__PURE__ */ jsx(SelectItem, { value: addr.id, children: optionLabel }, addr.id);
          }) })
        ]
      },
      `address:${value}:${optionsKey}`
    );
  };
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "grid gap-4 md:grid-cols-2", children: [
      lockedReason ? /* @__PURE__ */ jsx(
        ErrorMessage,
        {
          label: lockedReason,
          className: "md:col-span-2",
          action: /* @__PURE__ */ jsx(Button, { size: "sm", variant: "outline", disabled: true, children: t("sales.documents.detail.addresses.blocked", "Addresses cannot be changed for the current status.") })
        }
      ) : null,
      addressesError ? /* @__PURE__ */ jsx(
        ErrorMessage,
        {
          label: addressesError,
          className: "md:col-span-2",
          action: /* @__PURE__ */ jsx(Button, { size: "sm", variant: "outline", onClick: () => loadAddresses(customerId), children: t("sales.documents.detail.retry", "Try again") })
        }
      ) : null,
      /* @__PURE__ */ jsxs("div", { className: "space-y-3 rounded border bg-card p-4", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1 md:flex-row md:items-center md:justify-between", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold", children: t("sales.documents.form.shipping.title", "Shipping address") }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: customerRequired ? t("sales.documents.form.address.customerRequired", "Select customer first or define custom address") : t("sales.documents.form.shipping.hint", "Select an address or define a new one.") })
          ] }),
          /* @__PURE__ */ jsx(
            SwitchField,
            {
              label: t("sales.documents.form.shipping.custom", "Define new address"),
              flip: true,
              checked: useCustomShipping,
              onCheckedChange: (checked) => setUseCustomShipping(checked),
              disabled: customerRequired || locked
            }
          )
        ] }),
        !useCustomShipping ? renderAddressSelect(
          shippingAddressIdState ?? "",
          shippingOptions,
          setShippingAddressId,
          addressesLoading || customerRequired || locked
        ) : null,
        useCustomShipping ? /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsx(
            AddressEditor,
            {
              value: shippingDraft,
              format: addressFormat,
              t,
              onChange: (next) => setShippingDraft(next),
              hidePrimaryToggle: true
            }
          ),
          /* @__PURE__ */ jsx(
            SwitchField,
            {
              label: t("sales.documents.form.address.saveToCustomer", "Save this address to the customer"),
              flip: true,
              checked: saveShippingAddress && !customerRequired,
              onCheckedChange: (checked) => setSaveShippingAddress(checked),
              disabled: customerRequired || locked
            }
          )
        ] }) : null
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-3 rounded border bg-card p-4", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1 md:flex-row md:items-center md:justify-between", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold", children: t("sales.documents.form.billing.title", "Billing address") }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: sameAsShipping ? t(
              "sales.documents.form.address.sameAsShippingHint",
              "Billing will mirror the shipping address. Uncheck to edit."
            ) : t("sales.documents.form.billing.hint", "Select an address or define a new one.") })
          ] }),
          /* @__PURE__ */ jsx(
            SwitchField,
            {
              label: t("sales.documents.form.address.sameAsShipping", "Same as shipping"),
              flip: true,
              checked: sameAsShipping,
              onCheckedChange: (checked) => {
                setSameAsShipping(checked);
                if (checked) {
                  setUseCustomBilling(useCustomShipping);
                  setBillingAddressId(useCustomShipping ? null : shippingAddressIdState);
                  setBillingDraft(useCustomShipping ? shippingDraft : emptyDraft);
                }
              },
              disabled: locked
            }
          )
        ] }),
        !sameAsShipping ? /* @__PURE__ */ jsxs(Fragment, { children: [
          !useCustomBilling ? renderAddressSelect(
            billingAddressIdState ?? "",
            billingOptions,
            setBillingAddressId,
            addressesLoading || customerRequired || locked
          ) : null,
          /* @__PURE__ */ jsx(
            SwitchField,
            {
              label: t("sales.documents.form.shipping.custom", "Define new address"),
              flip: true,
              checked: useCustomBilling,
              onCheckedChange: (checked) => setUseCustomBilling(checked),
              disabled: customerRequired || locked
            }
          ),
          useCustomBilling ? /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
            /* @__PURE__ */ jsx(
              AddressEditor,
              {
                value: billingDraft,
                format: addressFormat,
                t,
                onChange: (next) => setBillingDraft(next),
                hidePrimaryToggle: true
              }
            ),
            /* @__PURE__ */ jsx(
              SwitchField,
              {
                label: t("sales.documents.form.address.saveToCustomer", "Save this address to the customer"),
                flip: true,
                checked: saveBillingAddress && !customerRequired,
                onCheckedChange: (checked) => setSaveBillingAddress(checked),
                disabled: customerRequired || locked
              }
            )
          ] }) : null
        ] }) : null
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-3 rounded border bg-card p-4", children: [
      documentAddressesError ? /* @__PURE__ */ jsx(
        ErrorMessage,
        {
          label: documentAddressesError,
          action: /* @__PURE__ */ jsx(Button, { size: "sm", variant: "outline", onClick: () => loadDocumentAddresses(), children: t("sales.documents.detail.retry", "Try again") })
        }
      ) : null,
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 md:flex-row md:items-center md:justify-between", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold", children: t("sales.documents.detail.addresses.additional", "Additional addresses") }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
            "sales.documents.detail.addresses.additionalHint",
            "Assign extra customer addresses to this document."
          ) })
        ] }),
        /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "outline",
            size: "sm",
            onClick: () => setAdditionalFormOpen(true),
            disabled: customerRequired || locked,
            children: [
              /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
              t("sales.documents.detail.addresses.add", "Add address")
            ]
          }
        )
      ] }),
      documentAddressesLoading ? /* @__PURE__ */ jsx(
        LoadingMessage,
        {
          label: t("sales.documents.detail.addresses.loading", "Loading document addresses\u2026"),
          className: "min-h-[48px] justify-start border-0 bg-transparent p-0 text-sm text-muted-foreground shadow-none"
        }
      ) : null,
      !documentAddressesLoading && documentAddresses.length === 0 && !additionalFormOpen ? /* @__PURE__ */ jsx(
        TabEmptyState,
        {
          title: t("sales.documents.detail.addresses.empty", "No additional addresses yet."),
          description: t(
            "sales.documents.detail.addresses.additionalHint",
            "Assign extra customer addresses to this document."
          ),
          action: {
            label: t("sales.documents.detail.addresses.add", "Add address"),
            onClick: () => setAdditionalFormOpen(true),
            disabled: customerRequired || locked
          }
        }
      ) : null,
      /* @__PURE__ */ jsx("div", { className: "grid gap-3 sm:grid-cols-2 xl:grid-cols-3", children: documentAddresses.map((entry) => {
        const isEditing = editingAddressId === entry.id;
        const title = entry.name && entry.name.trim() || entry.purpose && entry.purpose.trim() || entry.summary || t("sales.documents.detail.addresses.itemLabel", "Address");
        return /* @__PURE__ */ jsx("div", { className: "space-y-2 rounded border bg-card p-3", children: isEditing ? /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold", children: title }),
            /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                variant: "ghost",
                size: "sm",
                onClick: handleCancelEdit,
                "aria-label": t("ui.detail.inline.cancel", "Cancel"),
                children: t("ui.detail.inline.cancel", "Cancel")
              }
            )
          ] }),
          /* @__PURE__ */ jsx(
            AddressEditor,
            {
              value: editingDraft,
              format: addressFormat,
              t,
              onChange: (next) => setEditingDraft(next),
              hidePrimaryToggle: true
            }
          ),
          /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                variant: "outline",
                size: "sm",
                onClick: handleCancelEdit,
                disabled: editingSaving,
                children: t("ui.detail.inline.cancel", "Cancel")
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                size: "sm",
                onClick: () => void handleUpdateDocumentAddress(),
                disabled: editingSaving,
                children: editingSaving ? t("sales.documents.form.address.saving", "Saving\u2026") : t("sales.documents.detail.addresses.save", "Save address")
              }
            )
          ] })
        ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
            /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
              /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold", children: title }),
              entry.companyName ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: entry.companyName }) : null
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  variant: "ghost",
                  size: "icon",
                  onClick: () => {
                    setEditingAddressId(entry.id);
                    setEditingDraft(draftFromDocumentAddress(entry));
                  },
                  disabled: locked,
                  "aria-label": t("sales.documents.detail.addresses.edit", "Edit address"),
                  children: /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" })
                }
              ),
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  variant: "ghost",
                  size: "icon",
                  onClick: () => handleDeleteDocumentAddress(entry.id),
                  disabled: deletingAddressIds.has(entry.id) || locked,
                  "aria-label": t("sales.documents.detail.addresses.delete", "Remove address"),
                  children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsx(
            AddressView,
            {
              address: entry.value,
              format: addressFormat,
              className: "space-y-1 text-sm",
              lineClassName: "text-sm text-foreground"
            }
          )
        ] }) }, entry.id);
      }) }),
      additionalFormOpen ? /* @__PURE__ */ jsxs("div", { className: "space-y-3 rounded border border-dashed p-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1 md:flex-row md:items-center md:justify-between", children: [
          /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold", children: t("sales.documents.detail.addresses.new", "Add a new address") }),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              onClick: () => {
                setAdditionalFormOpen(false);
                setAdditionalUseCustom(false);
                setAdditionalSelectedId("");
                setAdditionalDraft(emptyDraft);
              },
              children: t("ui.detail.inline.cancel", "Cancel")
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          SwitchField,
          {
            label: t("sales.documents.form.shipping.custom", "Define new address"),
            flip: true,
            checked: additionalUseCustom,
            onCheckedChange: (checked) => setAdditionalUseCustom(checked),
            disabled: customerRequired || locked
          }
        ),
        !additionalUseCustom ? renderAddressSelect(
          additionalSelectedId,
          addressOptions,
          (next) => setAdditionalSelectedId(next ?? ""),
          addressesLoading || customerRequired
        ) : null,
        additionalUseCustom ? /* @__PURE__ */ jsx(
          AddressEditor,
          {
            value: additionalDraft,
            format: addressFormat,
            t,
            onChange: (next) => setAdditionalDraft(next),
            hidePrimaryToggle: true
          }
        ) : null,
        /* @__PURE__ */ jsx("div", { className: "flex justify-end gap-2", children: /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            onClick: handleAddAdditionalAddress,
            disabled: additionalSaving || customerRequired || locked,
            children: additionalSaving ? t("sales.documents.form.address.saving", "Saving\u2026") : t("sales.documents.detail.addresses.add", "Add address")
          }
        ) })
      ] }) : null
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 md:flex-row md:items-center md:justify-between", children: [
      addressesLoading || documentAddressesLoading ? /* @__PURE__ */ jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsx(
        LoadingMessage,
        {
          label: t("sales.documents.form.address.loading", "Loading addresses\u2026"),
          className: "min-h-[48px] justify-start border-0 bg-transparent p-0 text-sm text-muted-foreground shadow-none"
        }
      ) }) : null,
      /* @__PURE__ */ jsx("div", { className: "flex justify-end gap-2 sm:justify-start", children: /* @__PURE__ */ jsx(Button, { type: "button", onClick: handleSave, disabled: saving || locked, children: saving ? t("sales.documents.form.address.saving", "Saving\u2026") : /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(Save, { className: "mr-2 h-4 w-4" }),
        t("sales.documents.detail.addresses.update", "Update addresses")
      ] }) }) })
    ] }),
    ConfirmDialogElement
  ] });
}
var AddressesSection_default = SalesDocumentAddressesSection;
export {
  SalesDocumentAddressesSection,
  AddressesSection_default as default
};
//# sourceMappingURL=AddressesSection.js.map
