"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { apiCall, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { normalizeCrudServerError } from "@open-mercato/ui/backend/utils/serverErrors";
import { LoadingMessage, TabEmptyState } from "@open-mercato/ui/backend/detail";
import { Button } from "@open-mercato/ui/primitives/button";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { Pencil, Trash2 } from "lucide-react";
import {
  DictionaryValue,
  createDictionaryMap,
  normalizeDictionaryEntries
} from "@open-mercato/core/modules/dictionaries/components/dictionaryAppearance";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useOrganizationScopeDetail } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { emitSalesDocumentTotalsRefresh } from "@open-mercato/core/modules/sales/lib/frontend/documentTotalsEvents";
import { LineItemDialog } from "./LineItemDialog.js";
import { handleSectionMutationError } from "./optimisticLock.js";
import { formatMoney, normalizeNumber } from "./lineItemUtils.js";
import { extractCustomFieldValues } from "./customFieldHelpers.js";
import { canonicalizeUnitCode } from "@open-mercato/shared/lib/units/unitCodes";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("sales");
function isPlainObject(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isSalesLineUomSnapshot(value) {
  if (!isPlainObject(value)) return false;
  return value.version === 1 && typeof value.enteredQuantity === "string" && typeof value.toBaseFactor === "string" && typeof value.normalizedQuantity === "string";
}
function extractUomSnapshot(item) {
  const raw = item.uom_snapshot ?? item.uomSnapshot;
  if (isSalesLineUomSnapshot(raw)) return raw;
  return null;
}
function resolveUnitPriceReference(snapshot) {
  if (!snapshot) return null;
  const ref = isSalesLineUomSnapshot(snapshot) ? snapshot.unitPriceReference : isPlainObject(snapshot) ? isPlainObject(snapshot.unitPriceReference) ? snapshot.unitPriceReference : isPlainObject(snapshot.unit_price_reference) ? snapshot.unit_price_reference : null : null;
  if (!ref || !isPlainObject(ref)) return null;
  const refRecord = ref;
  const grossPerReference = normalizeNumber(
    refRecord.grossPerReference ?? refRecord.gross_per_reference,
    Number.NaN
  );
  if (!Number.isFinite(grossPerReference)) return null;
  const referenceUnitCode = typeof refRecord.referenceUnitCode === "string" ? refRecord.referenceUnitCode : typeof refRecord.reference_unit_code === "string" ? refRecord.reference_unit_code : typeof refRecord.referenceUnit === "string" ? refRecord.referenceUnit : null;
  if (!referenceUnitCode) return null;
  return { grossPerReference, referenceUnitCode };
}
function getUomFields(item) {
  const uomSnapshot = extractUomSnapshot(item);
  return {
    normalizedQuantity: item.normalized_quantity ?? item.normalizedQuantity ?? null,
    normalizedUnit: item.normalized_unit ?? item.normalizedUnit ?? null,
    quantityUnit: item.quantity_unit ?? item.quantityUnit ?? null,
    uomSnapshot
  };
}
function SalesDocumentItemsSection({
  documentId,
  kind,
  currencyCode,
  documentUpdatedAt,
  organizationId: orgFromProps,
  tenantId: tenantFromProps,
  onActionChange,
  onItemsChange
}) {
  const t = useT();
  const { organizationId, tenantId } = useOrganizationScopeDetail();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const resolvedOrganizationId = orgFromProps ?? organizationId ?? null;
  const resolvedTenantId = tenantFromProps ?? tenantId ?? null;
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [dialogOpen, setDialogOpen] = React.useState(false);
  const [lineForEdit, setLineForEdit] = React.useState(
    null
  );
  const [lineStatusMap, setLineStatusMap] = React.useState({});
  const [shippedTotals, setShippedTotals] = React.useState(
    /* @__PURE__ */ new Map()
  );
  const resourcePath = React.useMemo(
    () => kind === "order" ? "sales/order-lines" : "sales/quote-lines",
    [kind]
  );
  const documentKey = kind === "order" ? "orderId" : "quoteId";
  const lineStatusesLoaded = React.useRef(false);
  const itemsLoadedForDocument = React.useRef(null);
  const shipmentsLoadedForDocument = React.useRef(null);
  const loadLineStatuses = React.useCallback(async () => {
    try {
      const params = new URLSearchParams({ page: "1", pageSize: "100" });
      const response = await apiCall(`/api/sales/order-line-statuses?${params.toString()}`, void 0, {
        fallback: { items: [] }
      });
      const entries = normalizeDictionaryEntries(response.result?.items ?? [], { sort: false });
      setLineStatusMap(createDictionaryMap(entries));
    } catch (err) {
      logger.error("sales.document.line-statuses.load", { err });
      setLineStatusMap({});
    }
  }, []);
  const loadItems = React.useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams({
        page: "1",
        pageSize: "100",
        [documentKey]: documentId
      });
      const response = await apiCall(`/api/${resourcePath}?${params.toString()}`, void 0, {
        fallback: { items: [] }
      });
      if (response.ok && Array.isArray(response.result?.items)) {
        const mapped = response.result.items.flatMap(
          (item) => {
            const id = typeof item.id === "string" ? item.id : null;
            if (!id) return [];
            const taxRate = normalizeNumber(
              item.tax_rate ?? item.taxRate,
              0
            );
            const customFields = extractCustomFieldValues(
              item
            );
            const name = typeof item.name === "string" ? item.name : typeof item.catalog_snapshot === "object" && item.catalog_snapshot && typeof item.catalog_snapshot.name === "string" ? item.catalog_snapshot.name : null;
            const quantity = normalizeNumber(item.quantity, 0);
            const uomFields = getUomFields(item);
            const quantityUnit = canonicalizeUnitCode(uomFields.quantityUnit);
            const normalizedQuantity = normalizeNumber(
              uomFields.normalizedQuantity,
              quantity
            );
            const normalizedUnit = canonicalizeUnitCode(uomFields.normalizedUnit) ?? quantityUnit;
            const uomSnapshot = uomFields.uomSnapshot;
            const unitPriceNetRaw = normalizeNumber(
              item.unit_price_net ?? item.unitPriceNet,
              Number.NaN
            );
            const unitPriceGrossRaw = normalizeNumber(
              item.unit_price_gross ?? item.unitPriceGross,
              Number.NaN
            );
            const unitPriceNet = Number.isFinite(unitPriceNetRaw) ? unitPriceNetRaw : Number.isFinite(unitPriceGrossRaw) ? unitPriceGrossRaw / (1 + taxRate / 100) : 0;
            const unitPriceGross = Number.isFinite(unitPriceGrossRaw) ? unitPriceGrossRaw : Number.isFinite(unitPriceNetRaw) ? unitPriceNetRaw * (1 + taxRate / 100) : 0;
            const totalNetRaw = normalizeNumber(
              item.total_net_amount ?? item.totalNetAmount,
              Number.NaN
            );
            const totalGrossRaw = normalizeNumber(
              item.total_gross_amount ?? item.totalGrossAmount,
              Number.NaN
            );
            const totalNet = Number.isFinite(totalNetRaw) ? totalNetRaw : unitPriceNet * quantity;
            const totalGross = Number.isFinite(totalGrossRaw) ? totalGrossRaw : unitPriceGross * quantity;
            const priceModeRaw = item.metadata && typeof item.metadata === "object" ? item.metadata.priceMode : null;
            const priceMode = priceModeRaw === "net" ? "net" : "gross";
            const customFieldSetId = typeof item.custom_field_set_id === "string" ? item.custom_field_set_id : typeof item.customFieldSetId === "string" ? item.customFieldSetId : null;
            const statusEntryId = typeof item.status_entry_id === "string" ? item.status_entry_id : typeof item.statusEntryId === "string" ? item.statusEntryId : null;
            const status = typeof item.status === "string" ? item.status : null;
            const record = {
              id,
              name,
              productId: typeof item.product_id === "string" ? item.product_id : null,
              productVariantId: typeof item.product_variant_id === "string" ? item.product_variant_id : null,
              quantity,
              quantityUnit,
              normalizedQuantity,
              normalizedUnit,
              currencyCode: typeof item.currency_code === "string" ? item.currency_code : typeof currencyCode === "string" ? currencyCode : null,
              unitPriceNet,
              unitPriceGross,
              taxRate,
              totalNet,
              totalGross,
              priceMode,
              uomSnapshot,
              metadata: item.metadata ?? null,
              catalogSnapshot: item.catalog_snapshot ?? null,
              customFieldSetId,
              customFields: Object.keys(customFields).length ? customFields : null,
              status,
              statusEntryId
            };
            return [record];
          }
        );
        setItems(mapped);
        if (onItemsChange) onItemsChange(mapped);
      } else {
        setItems([]);
        if (onItemsChange) onItemsChange([]);
      }
    } catch (err) {
      logger.error("sales.document.items.load", { err });
      setError(t("sales.documents.items.errorLoad", "Failed to load items."));
      if (onItemsChange) onItemsChange([]);
    } finally {
      setLoading(false);
    }
  }, [currencyCode, documentId, documentKey, onItemsChange, resourcePath, t]);
  const loadShippedTotals = React.useCallback(async () => {
    if (kind !== "order") {
      setShippedTotals(/* @__PURE__ */ new Map());
      return;
    }
    try {
      const params = new URLSearchParams({
        page: "1",
        pageSize: "100",
        orderId: documentId
      });
      const response = await apiCall(`/api/sales/shipments?${params.toString()}`, void 0, {
        fallback: { items: [] }
      });
      if (response.ok && Array.isArray(response.result?.items)) {
        const totals = /* @__PURE__ */ new Map();
        response.result.items.forEach((shipment) => {
          const entries = Array.isArray(shipment.items) ? shipment.items : [];
          entries.forEach((entry) => {
            const lineId = typeof entry.orderLineId === "string" ? entry.orderLineId : typeof entry.order_line_id === "string" ? entry.order_line_id : null;
            if (!lineId) return;
            const quantity = normalizeNumber(entry.quantity, 0);
            if (!Number.isFinite(quantity) || quantity <= 0) return;
            const current = totals.get(lineId) ?? 0;
            totals.set(lineId, current + quantity);
          });
        });
        setShippedTotals(totals);
      } else {
        setShippedTotals(/* @__PURE__ */ new Map());
      }
    } catch (err) {
      logger.error("sales.document.shipments.load", { err });
      setShippedTotals(/* @__PURE__ */ new Map());
    }
  }, [documentId, kind]);
  React.useEffect(() => {
    if (lineStatusesLoaded.current) return;
    lineStatusesLoaded.current = true;
    void loadLineStatuses();
  }, [loadLineStatuses]);
  React.useEffect(() => {
    if (!documentId) return;
    if (itemsLoadedForDocument.current === documentId) return;
    itemsLoadedForDocument.current = documentId;
    void loadItems();
  }, [documentId, loadItems]);
  React.useEffect(() => {
    if (kind !== "order") {
      shipmentsLoadedForDocument.current = null;
      setShippedTotals(/* @__PURE__ */ new Map());
      return;
    }
    const key = `${kind}:${documentId}`;
    if (shipmentsLoadedForDocument.current === key) return;
    shipmentsLoadedForDocument.current = key;
    void loadShippedTotals();
  }, [documentId, kind, loadShippedTotals]);
  const openCreate = React.useCallback(() => {
    setLineForEdit(null);
    setDialogOpen(true);
  }, []);
  React.useEffect(() => {
    if (!onActionChange) return;
    onActionChange({
      label: t("sales.documents.items.add", "Add item"),
      onClick: openCreate,
      disabled: false
    });
    return () => onActionChange(null);
  }, [onActionChange, openCreate, t]);
  const handleEdit = React.useCallback((line) => {
    setLineForEdit(line);
    setDialogOpen(true);
  }, []);
  const resolveVariantInfo = React.useCallback((record) => {
    const meta = record.metadata ?? null;
    const snapshot = record.catalogSnapshot ?? null;
    const variantSnapshot = snapshot && typeof snapshot.variant === "object" && snapshot.variant ? snapshot.variant : null;
    const variantTitle = meta && typeof meta.variantTitle === "string" ? meta.variantTitle : variantSnapshot && typeof variantSnapshot.name === "string" ? variantSnapshot.name : null;
    const variantSku = meta && typeof meta.variantSku === "string" ? meta.variantSku : variantSnapshot && typeof variantSnapshot.sku === "string" ? variantSnapshot.sku : null;
    return { variantTitle, variantSku };
  }, []);
  const handleDelete = React.useCallback(
    async (line) => {
      const confirmed = await confirm({
        title: t(
          "sales.documents.items.deleteConfirm",
          "Delete this line item?"
        ),
        variant: "destructive"
      });
      if (!confirmed) return;
      try {
        const result = await withScopedApiRequestHeaders(
          buildOptimisticLockHeader(documentUpdatedAt),
          () => deleteCrud(resourcePath, {
            body: {
              id: line.id,
              [documentKey]: documentId,
              organizationId: resolvedOrganizationId ?? void 0,
              tenantId: resolvedTenantId ?? void 0
            },
            errorMessage: t(
              "sales.documents.items.errorDelete",
              "Failed to delete line."
            )
          })
        );
        if (result.ok) {
          flash(t("sales.documents.items.deleted", "Line removed."), "success");
          await loadItems();
          emitSalesDocumentTotalsRefresh({ documentId, kind });
        }
      } catch (err) {
        if (handleSectionMutationError(err, t, () => void loadItems())) return;
        logger.error("sales.document.items.delete", { err });
        const normalized = normalizeCrudServerError(err);
        const fallback = t(
          "sales.documents.items.errorDelete",
          "Failed to delete line."
        );
        flash(normalized.message || fallback, "error");
      }
    },
    [
      confirm,
      documentId,
      documentKey,
      documentUpdatedAt,
      kind,
      loadItems,
      resolvedOrganizationId,
      resourcePath,
      t,
      resolvedTenantId
    ]
  );
  const renderStatus = React.useCallback(
    (line) => {
      const value = line.status ?? null;
      if (!value) {
        return /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t("sales.documents.items.table.statusEmpty", "No status") });
      }
      return /* @__PURE__ */ jsx(
        DictionaryValue,
        {
          value,
          map: lineStatusMap,
          fallback: /* @__PURE__ */ jsx("span", { className: "text-xs font-medium", children: value }),
          className: "text-xs font-medium",
          iconWrapperClassName: "inline-flex h-6 w-6 items-center justify-center rounded bg-muted text-muted-foreground",
          iconClassName: "h-3.5 w-3.5",
          colorClassName: "h-4 w-4 rounded-full border border-border/70"
        }
      );
    },
    [lineStatusMap, t]
  );
  const renderImage = (record) => {
    const meta = record.metadata ?? {};
    const snapshot = record.catalogSnapshot ?? {};
    const productSnapshot = typeof snapshot === "object" && snapshot ? snapshot.product ?? {} : {};
    const variantSnapshot = typeof snapshot === "object" && snapshot ? snapshot.variant ?? {} : {};
    const productThumb = meta && typeof meta.productThumbnail === "string" && meta.productThumbnail || productSnapshot && typeof productSnapshot.thumbnailUrl === "string" && productSnapshot.thumbnailUrl || null;
    const variantThumb = meta && typeof meta.variantThumbnail === "string" && meta.variantThumbnail || variantSnapshot && typeof variantSnapshot.thumbnailUrl === "string" && variantSnapshot.thumbnailUrl || null;
    const thumbnail = variantThumb ?? productThumb;
    if (thumbnail) {
      return /* @__PURE__ */ jsx(
        "img",
        {
          src: thumbnail,
          alt: record.name ?? record.id,
          className: "h-10 w-10 rounded border object-cover"
        }
      );
    }
    return /* @__PURE__ */ jsx("div", { className: "flex h-10 w-10 items-center justify-center rounded border bg-muted text-xs text-muted-foreground", children: "N/A" });
  };
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    loading ? /* @__PURE__ */ jsx(
      LoadingMessage,
      {
        label: t("sales.documents.items.loading", "Loading items\u2026"),
        className: "border-0 bg-transparent p-0 py-8 justify-center"
      }
    ) : error ? /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: error }) : items.length === 0 ? /* @__PURE__ */ jsx(
      TabEmptyState,
      {
        title: t("sales.documents.items.empty", "No items yet."),
        description: t(
          "sales.documents.items.subtitle",
          "Add products and configure pricing for this document."
        ),
        action: {
          label: t("sales.documents.items.add", "Add item"),
          onClick: openCreate
        }
      }
    ) : /* @__PURE__ */ jsx("div", { className: "overflow-hidden rounded border", children: /* @__PURE__ */ jsxs("table", { className: "w-full text-sm", children: [
      /* @__PURE__ */ jsx("thead", { className: "bg-muted", children: /* @__PURE__ */ jsxs("tr", { className: "text-left", children: [
        /* @__PURE__ */ jsx("th", { className: "px-3 py-2 font-medium", children: t("sales.documents.items.table.product", "Product") }),
        /* @__PURE__ */ jsx("th", { className: "px-3 py-2 font-medium", children: t("sales.documents.items.table.status", "Status") }),
        /* @__PURE__ */ jsx("th", { className: "px-3 py-2 font-medium", children: t("sales.documents.items.table.quantity", "Qty") }),
        /* @__PURE__ */ jsx("th", { className: "px-3 py-2 font-medium", children: t("sales.documents.items.table.unit", "Unit price") }),
        /* @__PURE__ */ jsx("th", { className: "px-3 py-2 font-medium", children: t("sales.documents.items.table.total", "Total") }),
        /* @__PURE__ */ jsx("th", { className: "px-3 py-2 font-medium sr-only", children: t("sales.documents.items.table.actions", "Actions") })
      ] }) }),
      /* @__PURE__ */ jsx("tbody", { children: items.map((item) => {
        const meta = item.metadata ?? null;
        const { variantTitle, variantSku } = resolveVariantInfo(item);
        const productSku = meta && typeof meta.productSku === "string" ? meta.productSku : null;
        const variantLabel = variantTitle ?? variantSku;
        const variantSuffix = variantSku && variantLabel && variantSku !== variantLabel ? ` \u2022 ${variantSku}` : "";
        const showProductSku = productSku && productSku !== variantSku ? productSku : null;
        const shippedQuantity = Math.max(
          0,
          shippedTotals.get(item.id) ?? 0
        );
        const quantityLabel = item.quantityUnit ? `${item.quantity} ${item.quantityUnit}` : String(item.quantity);
        const showNormalized = Number.isFinite(item.normalizedQuantity) && item.normalizedQuantity > 0 && (item.normalizedUnit ?? null) && (Math.abs(item.normalizedQuantity - item.quantity) > 1e-6 || (item.normalizedUnit ?? null) !== (item.quantityUnit ?? null));
        const unitPriceReference = resolveUnitPriceReference(
          item.uomSnapshot
        );
        return /* @__PURE__ */ jsxs(
          "tr",
          {
            className: "border-t hover:bg-muted/50 cursor-pointer transition-colors",
            onClick: () => handleEdit(item),
            children: [
              /* @__PURE__ */ jsx("td", { className: "px-3 py-3", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
                renderImage(item),
                /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
                  /* @__PURE__ */ jsx("div", { className: "truncate font-medium", children: item.name ?? t("sales.documents.items.untitled", "Untitled") }),
                  variantLabel ? /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground truncate", children: [
                    variantLabel,
                    variantSuffix
                  ] }) : null,
                  showProductSku ? /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground truncate", children: showProductSku }) : null
                ] })
              ] }) }),
              /* @__PURE__ */ jsx("td", { className: "px-3 py-3", children: /* @__PURE__ */ jsx("div", { className: "flex items-center", children: renderStatus(item) }) }),
              /* @__PURE__ */ jsx("td", { className: "px-3 py-3", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-0.5", children: [
                /* @__PURE__ */ jsx("span", { className: "font-medium", children: quantityLabel }),
                showNormalized ? /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground", children: [
                  item.normalizedQuantity,
                  " ",
                  item.normalizedUnit
                ] }) : null,
                shippedQuantity > 0 ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t(
                  "sales.documents.items.table.shipped",
                  "{{shipped}} / {{total}} shipped",
                  {
                    shipped: shippedQuantity,
                    total: item.quantity
                  }
                ) }) : null
              ] }) }),
              /* @__PURE__ */ jsx("td", { className: "px-3 py-3", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-0.5", children: [
                /* @__PURE__ */ jsxs("span", { className: "font-mono text-sm", children: [
                  formatMoney(
                    item.unitPriceGross,
                    item.currencyCode ?? currencyCode ?? void 0
                  ),
                  " ",
                  /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t("sales.documents.items.table.gross", "gross") })
                ] }),
                /* @__PURE__ */ jsxs("span", { className: "font-mono text-xs text-muted-foreground", children: [
                  formatMoney(
                    item.unitPriceNet,
                    item.currencyCode ?? currencyCode ?? void 0
                  ),
                  " ",
                  t("sales.documents.items.table.net", "net")
                ] }),
                unitPriceReference ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t(
                  "sales.documents.items.table.unitPriceReference",
                  "{{value}} per 1 {{unit}}",
                  {
                    value: formatMoney(
                      unitPriceReference.grossPerReference,
                      item.currencyCode ?? currencyCode ?? void 0
                    ),
                    unit: unitPriceReference.referenceUnitCode
                  }
                ) }) : null
              ] }) }),
              /* @__PURE__ */ jsx("td", { className: "px-3 py-3 font-semibold", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-0.5", children: [
                /* @__PURE__ */ jsxs("span", { children: [
                  formatMoney(
                    item.totalGross,
                    item.currencyCode ?? currencyCode ?? void 0
                  ),
                  " ",
                  /* @__PURE__ */ jsx("span", { className: "text-xs font-normal text-muted-foreground", children: t("sales.documents.items.table.gross", "gross") })
                ] }),
                /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium text-muted-foreground", children: [
                  formatMoney(
                    item.totalNet,
                    item.currencyCode ?? currencyCode ?? void 0
                  ),
                  " ",
                  t("sales.documents.items.table.net", "net")
                ] })
              ] }) }),
              /* @__PURE__ */ jsx("td", { className: "px-3 py-3", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 justify-end", children: [
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    size: "icon",
                    variant: "ghost",
                    className: "h-8 w-8",
                    onClick: (event) => {
                      event.stopPropagation();
                      handleEdit(item);
                    },
                    children: /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" })
                  }
                ),
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    size: "icon",
                    variant: "ghost",
                    className: "h-8 w-8 text-destructive",
                    onClick: (event) => {
                      event.stopPropagation();
                      void handleDelete(item);
                    },
                    children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
                  }
                )
              ] }) })
            ]
          },
          item.id
        );
      }) })
    ] }) }),
    /* @__PURE__ */ jsx(
      LineItemDialog,
      {
        open: dialogOpen,
        onOpenChange: (next) => {
          setDialogOpen(next);
          if (!next) setLineForEdit(null);
        },
        kind,
        documentId,
        currencyCode,
        documentUpdatedAt,
        organizationId: resolvedOrganizationId,
        tenantId: resolvedTenantId,
        initialLine: lineForEdit,
        onSaved: async () => {
          await loadItems();
          emitSalesDocumentTotalsRefresh({ documentId, kind });
        }
      }
    ),
    ConfirmDialogElement
  ] });
}
export {
  SalesDocumentItemsSection
};
//# sourceMappingURL=ItemsSection.js.map
