"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import {
  Check,
  Link2,
  Loader2,
  Plus,
  Search,
  SearchX
} from "lucide-react";
import { EmptyState } from "@open-mercato/ui/primitives/empty-state";
import { cn } from "@open-mercato/shared/lib/utils";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Avatar } from "@open-mercato/ui/primitives/avatar";
import { Button } from "@open-mercato/ui/primitives/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { Input } from "@open-mercato/ui/primitives/input";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
const SEARCH_DEBOUNCE_MS = 200;
function diffSelection(initial, next) {
  const initialSet = new Set(initial);
  const nextSet = new Set(next);
  const addedIds = [];
  const removedIds = [];
  next.forEach((id) => {
    if (!initialSet.has(id)) addedIds.push(id);
  });
  initial.forEach((id) => {
    if (!nextSet.has(id)) removedIds.push(id);
  });
  return { addedIds, removedIds };
}
function sameIds(left, right) {
  if (left.length !== right.length) return false;
  const rightSet = new Set(right);
  return left.every((value) => rightSet.has(value));
}
function mergeOptionMaps(existing, entries) {
  const next = new Map(existing);
  entries.forEach((entry) => next.set(entry.id, entry));
  return next;
}
function SelectionIndicator({ checked, disabled, label }) {
  return /* @__PURE__ */ jsx(
    "span",
    {
      role: "checkbox",
      "aria-checked": checked,
      "aria-disabled": disabled || void 0,
      "aria-label": label,
      className: cn(
        "inline-flex size-6 shrink-0 items-center justify-center rounded-full border transition-colors",
        checked ? "border-foreground bg-foreground text-background" : "border-border bg-background",
        disabled && "opacity-50"
      ),
      children: checked ? /* @__PURE__ */ jsx(Check, { className: "size-3", strokeWidth: 2.5 }) : null
    }
  );
}
function DefaultRow({
  option,
  ctx,
  avatarVariant,
  defaultAvatarIcon,
  selectLabel
}) {
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      Avatar,
      {
        label: option.label,
        variant: avatarVariant,
        size: "md",
        icon: option.icon ?? defaultAvatarIcon
      }
    ),
    /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
      /* @__PURE__ */ jsx("div", { className: "truncate text-sm font-semibold text-foreground", children: option.label }),
      option.subtitle ? /* @__PURE__ */ jsx("div", { className: "mt-0.5 truncate text-xs text-muted-foreground", children: option.subtitle }) : null
    ] }),
    /* @__PURE__ */ jsx(SelectionIndicator, { checked: ctx.selected, label: selectLabel })
  ] });
}
function LinkEntityDialog({
  open,
  onOpenChange,
  adapter,
  initialSelectedIds,
  initialPrimaryId,
  primarySupported = false,
  onConfirm,
  avatarVariant = "monochrome"
}) {
  const t = useT();
  const [query, setQuery] = React.useState("");
  const [activeFilter, setActiveFilter] = React.useState(
    adapter.filters?.defaultId
  );
  const [searchPage, setSearchPage] = React.useState(1);
  const [searchTotalPages, setSearchTotalPages] = React.useState(1);
  const [searchTotal, setSearchTotal] = React.useState(null);
  const [searchResults, setSearchResults] = React.useState([]);
  const [searchLoading, setSearchLoading] = React.useState(false);
  const [draftIds, setDraftIds] = React.useState(initialSelectedIds);
  const [draftPrimaryId, setDraftPrimaryId] = React.useState(
    initialPrimaryId ?? null
  );
  const [focusedId, setFocusedId] = React.useState(null);
  const [optionCache, setOptionCache] = React.useState(
    () => /* @__PURE__ */ new Map()
  );
  const [details, setDetails] = React.useState({});
  const [detailsLoadingId, setDetailsLoadingId] = React.useState(null);
  const [linkSettings, setLinkSettings] = React.useState(
    adapter.initialLinkSettings ?? {}
  );
  const [saving, setSaving] = React.useState(false);
  const [nestedOpen, setNestedOpen] = React.useState(false);
  const requestIdRef = React.useRef(0);
  const initialIdsKey = React.useMemo(() => initialSelectedIds.join("|"), [initialSelectedIds]);
  React.useEffect(() => {
    if (!open) return;
    setDraftIds(initialSelectedIds);
    setDraftPrimaryId(initialPrimaryId ?? null);
    setQuery("");
    setActiveFilter(adapter.filters?.defaultId);
    setSearchPage(1);
    setSearchTotalPages(1);
    setSearchTotal(null);
    setSearchResults([]);
    setFocusedId(null);
    setDetails({});
    setDetailsLoadingId(null);
    setLinkSettings(adapter.initialLinkSettings ?? {});
    setNestedOpen(false);
  }, [open, initialIdsKey, initialPrimaryId, adapter]);
  React.useEffect(() => {
    if (!open) return;
    setSearchPage(1);
  }, [open, query, activeFilter]);
  React.useEffect(() => {
    if (!open) return;
    let cancelled = false;
    const current = ++requestIdRef.current;
    setSearchLoading(true);
    const timeout = window.setTimeout(async () => {
      try {
        const result = await adapter.searchPage(query, searchPage, activeFilter);
        if (cancelled || current !== requestIdRef.current) return;
        setSearchResults(result.items);
        setSearchTotalPages(Math.max(1, result.totalPages));
        setSearchTotal(typeof result.total === "number" ? result.total : null);
        setOptionCache((prev) => mergeOptionMaps(prev, result.items));
      } catch {
        if (cancelled || current !== requestIdRef.current) return;
        setSearchResults([]);
        setSearchTotalPages(1);
        setSearchTotal(0);
      } finally {
        if (!cancelled && current === requestIdRef.current) {
          setSearchLoading(false);
        }
      }
    }, SEARCH_DEBOUNCE_MS);
    return () => {
      cancelled = true;
      window.clearTimeout(timeout);
    };
  }, [adapter, activeFilter, open, query, searchPage]);
  React.useEffect(() => {
    if (!open) return;
    const missingIds = draftIds.filter((id) => !optionCache.has(id));
    if (!missingIds.length) return;
    let cancelled = false;
    void adapter.fetchByIds(missingIds).then((entries) => {
      if (cancelled) return;
      setOptionCache((prev) => mergeOptionMaps(prev, entries));
    }).catch((error) => logger.warn("fetchByIds failed", { component: "LinkEntityDialog", err: error }));
    return () => {
      cancelled = true;
    };
  }, [adapter, draftIds, open, optionCache]);
  const focusedOption = React.useMemo(
    () => focusedId ? optionCache.get(focusedId) ?? null : null,
    [focusedId, optionCache]
  );
  const fetchDetails = adapter.fetchDetails;
  React.useEffect(() => {
    if (!open || !focusedId || !fetchDetails) return;
    if (details[focusedId] !== void 0) return;
    let cancelled = false;
    setDetailsLoadingId(focusedId);
    void fetchDetails(focusedId).then((result) => {
      if (cancelled) return;
      setDetails((prev) => ({ ...prev, [focusedId]: result }));
    }).catch((error) => logger.warn("fetchDetails failed", { component: "LinkEntityDialog", err: error })).finally(() => {
      if (!cancelled) setDetailsLoadingId(null);
    });
    return () => {
      cancelled = true;
    };
  }, [details, fetchDetails, focusedId, open]);
  const draftSet = React.useMemo(() => new Set(draftIds), [draftIds]);
  const displayedResults = React.useMemo(() => {
    const predicate = adapter.filters?.clientFilter;
    const effectiveFilter = activeFilter ?? adapter.filters?.defaultId;
    if (!predicate || !effectiveFilter) return searchResults;
    return searchResults.filter((option) => predicate(option, effectiveFilter));
  }, [adapter.filters, activeFilter, searchResults]);
  const selectedOptions = React.useMemo(
    () => draftIds.map((id) => optionCache.get(id) ?? { id, label: id }).filter((entry) => Boolean(entry)),
    [draftIds, optionCache]
  );
  React.useEffect(() => {
    if (!primarySupported) return;
    setDraftPrimaryId((current) => {
      const normalizedCurrent = current ?? null;
      if (draftIds.length === 0) return null;
      if (normalizedCurrent && draftIds.includes(normalizedCurrent)) return normalizedCurrent;
      return draftIds[0];
    });
  }, [draftIds, primarySupported]);
  const toggleDraftId = React.useCallback((id, checked) => {
    setDraftIds((current) => {
      if (checked) {
        if (current.includes(id)) return current;
        return [...current, id];
      }
      return current.filter((candidate) => candidate !== id);
    });
  }, []);
  const handleRowClick = React.useCallback(
    (option) => {
      setFocusedId(option.id);
      const isSelected = draftSet.has(option.id);
      toggleDraftId(option.id, !isSelected);
    },
    [draftSet, toggleDraftId]
  );
  const handleAddNewCreated = React.useCallback(
    (option) => {
      setOptionCache((prev) => mergeOptionMaps(prev, [option]));
      setDraftIds((current) => current.includes(option.id) ? current : [...current, option.id]);
      setFocusedId(option.id);
      setNestedOpen(false);
    },
    []
  );
  const handleDialogOpenChange = React.useCallback(
    (next) => {
      if (nestedOpen && !next) return;
      onOpenChange(next);
    },
    [nestedOpen, onOpenChange]
  );
  const handleSetPrimary = React.useCallback(
    (id) => {
      if (!primarySupported || !draftSet.has(id)) return;
      setDraftPrimaryId(id);
      setFocusedId(id);
    },
    [draftSet, primarySupported]
  );
  const hasChanges = React.useMemo(() => {
    if (!sameIds(initialSelectedIds, draftIds)) return true;
    if (primarySupported && (draftPrimaryId ?? null) !== (initialPrimaryId ?? null)) return true;
    return false;
  }, [draftIds, draftPrimaryId, initialPrimaryId, initialSelectedIds, primarySupported]);
  const handleSave = React.useCallback(async () => {
    if (saving) return;
    const { addedIds, removedIds } = diffSelection(initialSelectedIds, draftIds);
    const primaryChanged = primarySupported ? (draftPrimaryId ?? null) !== (initialPrimaryId ?? null) : false;
    if (!addedIds.length && !removedIds.length && !primaryChanged) {
      onOpenChange(false);
      return;
    }
    setSaving(true);
    try {
      const optionsById = {};
      optionCache.forEach((value, key) => {
        optionsById[key] = value;
      });
      await onConfirm({
        addedIds,
        removedIds,
        nextSelectedIds: draftIds,
        primaryId: primarySupported ? draftPrimaryId : void 0,
        optionsById,
        linkSettings
      });
      onOpenChange(false);
    } finally {
      setSaving(false);
    }
  }, [
    draftIds,
    draftPrimaryId,
    initialPrimaryId,
    initialSelectedIds,
    linkSettings,
    onConfirm,
    onOpenChange,
    optionCache,
    primarySupported,
    saving
  ]);
  const handleKeyDown = React.useCallback(
    (event) => {
      if (nestedOpen) return;
      if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
        event.preventDefault();
        void handleSave();
        return;
      }
      if (event.key === "Escape") {
        event.preventDefault();
        handleDialogOpenChange(false);
      }
    },
    [handleDialogOpenChange, handleSave, nestedOpen]
  );
  const selectedCountLabel = React.useMemo(() => {
    const kindLabels = {
      person: [
        "customers.linking.footer.personSingular",
        "{{count}} person selected",
        "customers.linking.footer.personPlural",
        "{{count}} people selected"
      ],
      company: [
        "customers.linking.footer.companySingular",
        "{{count}} company selected",
        "customers.linking.footer.companyPlural",
        "{{count}} companies selected"
      ],
      deal: [
        "customers.linking.footer.dealSingular",
        "{{count}} deal selected",
        "customers.linking.footer.dealPlural",
        "{{count}} deals selected"
      ]
    };
    const [singularKey, singularDefault, pluralKey, pluralDefault] = kindLabels[adapter.kind];
    if (draftIds.length === 1) {
      return t(singularKey, singularDefault, { count: String(draftIds.length) });
    }
    return t(pluralKey, pluralDefault, { count: String(draftIds.length) });
  }, [adapter.kind, draftIds.length, t]);
  const filterOptions = adapter.filters?.options ?? [];
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: handleDialogOpenChange, children: /* @__PURE__ */ jsxs(
      DialogContent,
      {
        className: "flex flex-col gap-0 overflow-hidden p-0",
        style: {
          width: "min(calc(100vw - 2rem), 920px)",
          maxWidth: "min(calc(100vw - 2rem), 920px)",
          maxHeight: "min(640px, calc(100vh - 4rem))"
        },
        onKeyDown: handleKeyDown,
        "aria-hidden": nestedOpen ? "true" : void 0,
        children: [
          /* @__PURE__ */ jsxs(DialogHeader, { className: "flex flex-row items-center gap-3 space-y-0 border-b border-border/70 bg-card px-6 py-5", children: [
            adapter.headerIcon ? /* @__PURE__ */ jsx("div", { className: "flex size-6 shrink-0 items-center justify-center text-foreground", children: adapter.headerIcon }) : null,
            /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
              /* @__PURE__ */ jsx(DialogTitle, { className: "text-lg font-bold text-foreground", children: adapter.dialogTitle }),
              adapter.dialogSubtitle ? /* @__PURE__ */ jsx(DialogDescription, { className: "mt-0.5 text-sm text-muted-foreground", children: adapter.dialogSubtitle }) : null
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-1 flex-col lg:flex-row", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-col gap-3 border-b border-border/70 bg-card p-4 lg:w-[480px] lg:shrink-0 lg:border-b-0 lg:border-r", children: [
              /* @__PURE__ */ jsxs("div", { className: "relative", children: [
                /* @__PURE__ */ jsx(Search, { className: "pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    value: query,
                    onChange: (event) => setQuery(event.target.value),
                    placeholder: adapter.searchPlaceholder,
                    className: "h-10 rounded-md pl-9 pr-20 text-sm",
                    autoFocus: true,
                    "aria-label": adapter.searchPlaceholder
                  }
                ),
                searchTotal !== null && !searchLoading ? /* @__PURE__ */ jsx("span", { className: "pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground", children: t("customers.linking.resultsCount", "{{count}} results", {
                  count: String(searchTotal)
                }) }) : null
              ] }),
              filterOptions.length > 0 ? /* @__PURE__ */ jsx("div", { className: "flex flex-wrap items-center gap-1.5", children: filterOptions.map((filter) => {
                const isActive = (activeFilter ?? adapter.filters?.defaultId) === filter.id;
                return /* @__PURE__ */ jsxs(
                  "button",
                  {
                    type: "button",
                    onClick: () => setActiveFilter(filter.id),
                    className: cn(
                      "inline-flex h-6 items-center gap-1.5 rounded-full px-2.5 text-xs font-semibold transition-colors",
                      isActive ? "bg-foreground text-background" : "bg-muted/70 text-muted-foreground hover:bg-muted"
                    ),
                    children: [
                      filter.dotColor ? /* @__PURE__ */ jsx(
                        "span",
                        {
                          "aria-hidden": "true",
                          className: "inline-block size-1.5 rounded-full",
                          style: { backgroundColor: filter.dotColor }
                        }
                      ) : null,
                      /* @__PURE__ */ jsx("span", { children: filter.label }),
                      typeof filter.count === "number" ? /* @__PURE__ */ jsx(
                        "span",
                        {
                          className: cn(
                            "inline-flex min-w-[14px] items-center justify-center rounded-full px-1 text-xs",
                            isActive ? "bg-background/20 text-background" : "bg-background text-muted-foreground"
                          ),
                          children: filter.count
                        }
                      ) : null
                    ]
                  },
                  filter.id
                );
              }) }) : null,
              adapter.sectionLabel ? /* @__PURE__ */ jsx("div", { className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: adapter.sectionLabel }) : null,
              /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-1 flex-col gap-2 overflow-auto", children: [
                searchLoading && displayedResults.length === 0 ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 rounded-lg border border-dashed border-border/70 px-4 py-6 text-sm text-muted-foreground", children: [
                  /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin" }),
                  t("customers.linking.searching", "Searching\u2026")
                ] }) : displayedResults.length === 0 ? /* @__PURE__ */ jsx(
                  EmptyState,
                  {
                    size: "sm",
                    icon: /* @__PURE__ */ jsx(SearchX, { className: "h-8 w-8", "aria-hidden": "true" }),
                    title: adapter.searchEmptyHint
                  }
                ) : displayedResults.map((result) => {
                  const checked = draftSet.has(result.id);
                  const focused = focusedId === result.id;
                  const ctx = { selected: checked, focused };
                  const selectLabel = t("customers.linking.selectEntity", "Select {{name}}", {
                    name: result.label
                  });
                  return /* @__PURE__ */ jsx(
                    "div",
                    {
                      role: "button",
                      tabIndex: 0,
                      "aria-pressed": checked,
                      onClick: () => handleRowClick(result),
                      onKeyDown: (event) => {
                        if (event.key === "Enter" || event.key === " ") {
                          event.preventDefault();
                          handleRowClick(result);
                        }
                      },
                      className: cn(
                        "group flex cursor-pointer items-center gap-3 rounded-lg border px-3.5 py-3 transition-colors focus:outline-none focus:ring-2 focus:ring-ring/40",
                        checked ? "border-border bg-muted/50" : "border-border/70 bg-card hover:bg-muted/30"
                      ),
                      children: adapter.renderRow ? adapter.renderRow(result, ctx) : /* @__PURE__ */ jsx(
                        DefaultRow,
                        {
                          option: result,
                          ctx,
                          avatarVariant,
                          defaultAvatarIcon: adapter.defaultAvatarIcon,
                          selectLabel
                        }
                      )
                    },
                    result.id
                  );
                }),
                adapter.addNew ? /* @__PURE__ */ jsxs(
                  "button",
                  {
                    type: "button",
                    onClick: () => setNestedOpen(true),
                    className: "mt-2 flex items-center gap-3 rounded-lg border border-dashed border-border px-4 py-3.5 text-left transition-colors hover:bg-muted/30 focus:outline-none focus:ring-2 focus:ring-ring/40",
                    children: [
                      /* @__PURE__ */ jsx("span", { className: "flex size-9 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground", children: /* @__PURE__ */ jsx(Plus, { className: "size-4" }) }),
                      /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
                        /* @__PURE__ */ jsx("span", { className: "block truncate text-sm font-semibold text-foreground", children: adapter.addNew.title }),
                        adapter.addNew.subtitle ? /* @__PURE__ */ jsx("span", { className: "mt-0.5 block truncate text-xs text-muted-foreground", children: adapter.addNew.subtitle }) : null
                      ] }),
                      /* @__PURE__ */ jsx("span", { className: "flex size-8 shrink-0 items-center justify-center rounded-md bg-foreground text-background", children: /* @__PURE__ */ jsx(Plus, { className: "size-3.5" }) })
                    ]
                  }
                ) : null,
                searchTotalPages > 1 ? /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between pt-2 text-xs text-muted-foreground", children: [
                  /* @__PURE__ */ jsx("span", { "aria-live": "polite", children: t("customers.linking.pagination.pageOf", "Page {{page}} of {{total}}", {
                    page: String(Math.min(searchPage, searchTotalPages)),
                    total: String(searchTotalPages)
                  }) }),
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                    /* @__PURE__ */ jsx(
                      Button,
                      {
                        type: "button",
                        variant: "outline",
                        size: "sm",
                        className: "h-8 rounded-md px-2.5 text-xs",
                        disabled: searchLoading || searchPage <= 1,
                        onClick: () => setSearchPage((current) => Math.max(1, current - 1)),
                        children: t("customers.linking.pagination.previousShort", "Previous")
                      }
                    ),
                    /* @__PURE__ */ jsx(
                      Button,
                      {
                        type: "button",
                        variant: "outline",
                        size: "sm",
                        className: "h-8 rounded-md px-2.5 text-xs",
                        disabled: searchLoading || searchPage >= searchTotalPages,
                        onClick: () => setSearchPage((current) => Math.min(searchTotalPages, current + 1)),
                        children: t("customers.linking.pagination.nextShort", "Next")
                      }
                    )
                  ] })
                ] }) : null
              ] })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-1 flex-col gap-4 overflow-auto bg-muted/20 p-5", children: [
              /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-border/70 bg-card p-4", children: [
                /* @__PURE__ */ jsx("div", { className: "mb-3 text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: t("customers.linking.selected.label", "Selected") }),
                selectedOptions.length > 0 ? /* @__PURE__ */ jsx("div", { className: "space-y-2", children: selectedOptions.map((option) => {
                  const isPrimary = primarySupported && draftPrimaryId === option.id;
                  return /* @__PURE__ */ jsxs(
                    "div",
                    {
                      className: cn(
                        "flex items-center gap-3 rounded-lg border px-3 py-2.5 transition-colors",
                        focusedId === option.id ? "border-border bg-muted/50" : "border-border/70 bg-card"
                      ),
                      children: [
                        /* @__PURE__ */ jsxs(
                          "button",
                          {
                            type: "button",
                            onClick: () => setFocusedId(option.id),
                            className: "flex min-w-0 flex-1 items-center gap-3 text-left",
                            children: [
                              /* @__PURE__ */ jsx(
                                Avatar,
                                {
                                  label: option.label,
                                  variant: avatarVariant,
                                  size: "sm",
                                  icon: option.icon ?? adapter.defaultAvatarIcon
                                }
                              ),
                              /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
                                /* @__PURE__ */ jsx("span", { className: "block truncate text-sm font-semibold text-foreground", children: option.label }),
                                option.subtitle ? /* @__PURE__ */ jsx("span", { className: "mt-0.5 block truncate text-xs text-muted-foreground", children: option.subtitle }) : null
                              ] })
                            ]
                          }
                        ),
                        primarySupported ? /* @__PURE__ */ jsx(
                          Button,
                          {
                            type: "button",
                            size: "sm",
                            variant: isPrimary ? "default" : "outline",
                            className: "h-7 rounded-full px-3 text-xs",
                            onClick: () => handleSetPrimary(option.id),
                            disabled: isPrimary,
                            children: isPrimary ? t("customers.linking.primary.current", "Primary") : t("customers.linking.primary.set", "Set primary")
                          }
                        ) : null
                      ]
                    },
                    option.id
                  );
                }) }) : /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-dashed border-border/70 px-4 py-4 text-sm text-muted-foreground", children: adapter.selectedEmptyHint }),
                primarySupported && selectedOptions.length > 0 ? /* @__PURE__ */ jsx("div", { className: "mt-3 text-xs text-muted-foreground", children: t(
                  "customers.linking.primary.help",
                  "Choose which linked company should remain primary."
                ) }) : null
              ] }),
              /* @__PURE__ */ jsx("div", { className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: t("customers.linking.preview.label", "Preview") }),
              focusedOption ? /* @__PURE__ */ jsxs(Fragment, { children: [
                adapter.renderPreview ? adapter.renderPreview(focusedOption, details[focusedOption.id]) : /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-border/70 bg-card p-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
                  /* @__PURE__ */ jsx(
                    Avatar,
                    {
                      label: focusedOption.label,
                      variant: avatarVariant,
                      size: "lg",
                      icon: focusedOption.icon ?? adapter.defaultAvatarIcon
                    }
                  ),
                  /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
                    /* @__PURE__ */ jsx("div", { className: "truncate text-base font-bold text-foreground", children: focusedOption.label }),
                    focusedOption.subtitle ? /* @__PURE__ */ jsx("div", { className: "mt-0.5 truncate text-xs text-muted-foreground", children: focusedOption.subtitle }) : null
                  ] })
                ] }) }),
                detailsLoadingId === focusedOption.id && adapter.fetchDetails ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs text-muted-foreground", children: [
                  /* @__PURE__ */ jsx(Loader2, { className: "size-3.5 animate-spin" }),
                  t("customers.linking.preview.loading", "Loading details\u2026")
                ] }) : null,
                adapter.renderLinkSettings ? /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-border/70 bg-card p-4", children: [
                  /* @__PURE__ */ jsx("div", { className: "mb-3 text-overline font-semibold uppercase tracking-wider text-muted-foreground", children: t("customers.linking.settings.label", "Link settings") }),
                  adapter.renderLinkSettings(linkSettings, setLinkSettings, focusedOption)
                ] }) : null
              ] }) : /* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-col items-center justify-center rounded-lg border border-dashed border-border/70 bg-card/40 p-6 text-center text-sm text-muted-foreground", children: [
                /* @__PURE__ */ jsx(Link2, { className: "mb-2 size-5 opacity-60" }),
                t(
                  "customers.linking.preview.empty",
                  "Select an entry on the left to see details here."
                )
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxs(DialogFooter, { className: "flex flex-row items-center justify-between border-t border-border/70 bg-muted/30 px-6 py-4 sm:flex-row sm:justify-between", children: [
            /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: selectedCountLabel }),
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  variant: "outline",
                  onClick: () => handleDialogOpenChange(false),
                  disabled: saving,
                  className: "h-9 rounded-md px-4",
                  children: t("customers.linking.actions.cancel", "Cancel")
                }
              ),
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  onClick: () => {
                    void handleSave();
                  },
                  disabled: saving || !hasChanges,
                  className: "h-9 rounded-md bg-foreground px-5 text-background hover:bg-foreground/90",
                  children: saving ? /* @__PURE__ */ jsxs(Fragment, { children: [
                    /* @__PURE__ */ jsx(Loader2, { className: "mr-2 size-4 animate-spin" }),
                    t("customers.linking.actions.saving", "Saving\u2026")
                  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
                    /* @__PURE__ */ jsx(Link2, { className: "mr-2 size-4" }),
                    adapter.confirmButtonLabel
                  ] })
                }
              )
            ] })
          ] })
        ]
      }
    ) }),
    adapter.addNew && nestedOpen ? adapter.addNew.render({
      onCreated: handleAddNewCreated,
      onCancel: () => setNestedOpen(false)
    }) : null
  ] });
}
export {
  LinkEntityDialog
};
//# sourceMappingURL=LinkEntityDialog.js.map
