"use client";
import { jsx } from "react/jsx-runtime";
import * as React from "react";
import { apiCall, apiCallOrThrow, readApiResultOrThrow, 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 { AddressesSection as SharedAddressesSection } from "@open-mercato/ui/backend/detail";
import { createTranslatorWithFallback } from "@open-mercato/shared/lib/i18n/translate";
import { useT } from "@open-mercato/shared/lib/i18n/context";
function AddressesSection({
  entityId,
  emptyLabel,
  addActionLabel,
  emptyState,
  onActionChange,
  translator,
  onLoadingChange
}) {
  const tHook = useT();
  const fallbackTranslator = React.useMemo(() => createTranslatorWithFallback(tHook), [tHook]);
  const t = translator ?? fallbackTranslator;
  const dataAdapter = React.useMemo(() => ({
    list: async ({ entityId: listEntityId }) => {
      if (!listEntityId) return [];
      const params = new URLSearchParams({ entityId: listEntityId, pageSize: "100" });
      const payload = await readApiResultOrThrow(
        `/api/customers/addresses?${params.toString()}`,
        void 0,
        { errorMessage: t("customers.people.detail.addresses.error") }
      );
      const items = Array.isArray(payload?.items) ? payload.items : [];
      return items.map((item) => {
        if (!item || typeof item !== "object") return null;
        const record = item;
        const rawId = record.id ?? record.address_id ?? null;
        const id = typeof rawId === "string" ? rawId : typeof rawId === "number" || typeof rawId === "bigint" ? String(rawId) : null;
        if (!id) return null;
        const addressLine1 = typeof record.address_line1 === "string" ? record.address_line1 : typeof record.addressLine1 === "string" ? record.addressLine1 : null;
        if (!addressLine1) return null;
        return {
          id,
          name: typeof record.name === "string" ? record.name : null,
          purpose: typeof record.purpose === "string" ? record.purpose : null,
          companyName: typeof record.company_name === "string" ? record.company_name : typeof record.companyName === "string" ? record.companyName : null,
          addressLine1,
          addressLine2: typeof record.address_line2 === "string" ? record.address_line2 : typeof record.addressLine2 === "string" ? record.addressLine2 : null,
          buildingNumber: typeof record.building_number === "string" ? record.building_number : typeof record.buildingNumber === "string" ? record.buildingNumber : null,
          flatNumber: typeof record.flat_number === "string" ? record.flat_number : typeof record.flatNumber === "string" ? record.flatNumber : null,
          city: typeof record.city === "string" ? record.city : null,
          region: typeof record.region === "string" ? record.region : null,
          postalCode: typeof record.postal_code === "string" ? record.postal_code : typeof record.postalCode === "string" ? record.postalCode : null,
          country: typeof record.country === "string" ? record.country : null,
          latitude: typeof record.latitude === "number" && Number.isFinite(record.latitude) ? record.latitude : null,
          longitude: typeof record.longitude === "number" && Number.isFinite(record.longitude) ? record.longitude : null,
          isPrimary: typeof record.is_primary === "boolean" ? record.is_primary : typeof record.isPrimary === "boolean" ? record.isPrimary : false,
          updatedAt: typeof record.updated_at === "string" ? record.updated_at : typeof record.updatedAt === "string" ? record.updatedAt : null
        };
      }).filter((value) => value !== null);
    },
    create: async ({ entityId: targetId, payload }) => {
      const response = await apiCallOrThrow(
        "/api/customers/addresses",
        {
          // optimistic-lock-exempt: address create-only (no prior version to compare)
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            entityId: targetId,
            ...payload,
            country: payload.country ? payload.country.toUpperCase() : void 0
          })
        },
        { errorMessage: t("customers.people.detail.addresses.error") }
      );
      return response.result ?? {};
    },
    update: async ({ id, payload, updatedAt }) => {
      try {
        await withScopedApiRequestHeaders(
          buildOptimisticLockHeader(updatedAt ?? null),
          () => apiCallOrThrow(
            "/api/customers/addresses",
            {
              method: "PUT",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({
                id,
                ...payload,
                country: payload.country ? payload.country.toUpperCase() : void 0
              })
            },
            { errorMessage: t("customers.people.detail.addresses.error") }
          )
        );
      } catch (err) {
        surfaceRecordConflict(err, t);
        throw err;
      }
    },
    delete: async ({ id, updatedAt }) => {
      try {
        await withScopedApiRequestHeaders(
          buildOptimisticLockHeader(updatedAt ?? null),
          () => apiCallOrThrow(
            "/api/customers/addresses",
            {
              method: "DELETE",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({ id })
            },
            { errorMessage: t("customers.people.detail.addresses.error") }
          )
        );
      } catch (err) {
        surfaceRecordConflict(err, t);
        throw err;
      }
    }
  }), [t]);
  const addressTypesAdapter = React.useMemo(() => ({
    list: async () => {
      const call = await apiCall("/api/customers/dictionaries/address-types", {
        method: "GET"
      });
      const payload = call.result ?? {};
      const rawItems = payload.items;
      const items = Array.isArray(rawItems) ? rawItems : [];
      return items.map((item) => {
        if (!item || typeof item !== "object") return null;
        const record = item;
        const value = typeof record.value === "string" ? record.value : null;
        if (!value) return null;
        const label = typeof record.label === "string" && record.label.trim().length ? record.label : value;
        return { value, label };
      }).filter((entry) => !!entry);
    },
    create: async (value) => {
      const response = await apiCallOrThrow(
        "/api/customers/dictionaries/address-types",
        {
          // optimistic-lock-exempt: address-type dictionary create-only
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ value })
        },
        { errorMessage: t("customers.people.detail.addresses.types.saveError", "Failed to save address type") }
      );
      const payload = response.result ?? {};
      const createdValue = typeof payload.value === "string" ? payload.value : value;
      const label = typeof payload.label === "string" && payload.label.trim().length ? payload.label : createdValue;
      return { value: createdValue, label };
    },
    manageHref: "/backend/config/customers"
  }), [t]);
  const loadFormat = React.useCallback(async () => {
    const call = await apiCall(
      "/api/customers/settings/address-format"
    );
    const payload = call.result ?? {};
    if (!call.ok) {
      const message = typeof payload?.error === "string" ? payload.error : t("customers.people.detail.addresses.formatLoadError", "Failed to load address configuration");
      throw new Error(message);
    }
    const valueRaw = payload?.addressFormat;
    const value = typeof valueRaw === "string" ? valueRaw : null;
    if (value === "street_first" || value === "line_first") {
      return value;
    }
    return "line_first";
  }, [t]);
  return /* @__PURE__ */ jsx(
    SharedAddressesSection,
    {
      entityId,
      emptyLabel,
      addActionLabel,
      emptyState,
      onActionChange,
      onLoadingChange,
      translator: t,
      dataAdapter,
      addressTypesAdapter,
      loadFormat,
      showCoordinateFields: true
    }
  );
}
var AddressesSection_default = AddressesSection;
export {
  AddressesSection,
  AddressesSection_default as default
};
//# sourceMappingURL=AddressesSection.js.map
