"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { Button } from "@open-mercato/ui/primitives/button";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCallOrThrow, readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customFieldValues";
import { mapCrudServerErrorToFormErrors } from "@open-mercato/ui/backend/utils/serverErrors";
import { E } from "../../../../../../generated/entities.ids.generated.js";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import {
  ActivitiesSection
} from "../../../../components/detail/ActivitiesSection.js";
import {
  NotesSection,
  RecordNotFoundState,
  ErrorMessage
} from "@open-mercato/ui/backend/detail";
import {
  TagsSection
} from "../../../../components/detail/TagsSection.js";
import { DealsSection } from "../../../../components/detail/DealsSection.js";
import { AddressesSection } from "../../../../components/detail/AddressesSection.js";
import { TasksSection } from "../../../../components/detail/TasksSection.js";
import { PersonHighlights } from "../../../../components/detail/PersonHighlights.js";
import {
  renderLinkedInDisplay,
  renderTwitterDisplay,
  renderMultilineMarkdownDisplay,
  InlineDictionaryEditor
} from "../../../../components/detail/InlineEditors.js";
import { DetailFieldsSection } from "@open-mercato/ui/backend/detail";
import { isValidSocialUrl } from "@open-mercato/core/modules/customers/lib/detailHelpers";
import { CustomDataSection } from "../../../../components/detail/CustomDataSection.js";
import { createTranslatorWithFallback } from "@open-mercato/shared/lib/i18n/translate";
import { normalizeCustomFieldSubmitValue } from "../../../../components/detail/customFieldUtils.js";
import { renderDictionaryColor, renderDictionaryIcon } from "@open-mercato/core/modules/dictionaries/components/dictionaryAppearance";
import { ICON_SUGGESTIONS } from "../../../../lib/dictionaries.js";
import { createCustomerNotesAdapter } from "../../../../components/detail/notesAdapter.js";
import { readMarkdownPreferenceCookie, writeMarkdownPreferenceCookie } from "../../../../lib/markdownPreference.js";
import { InjectionSpot, useInjectionWidgets } from "@open-mercato/ui/backend/injection/InjectionSpot";
import { DetailTabsLayout } from "../../../../components/detail/DetailTabsLayout.js";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { SendObjectMessageDialog } from "@open-mercato/ui/backend/messages";
function CustomerPersonDetailPage({ params }) {
  const id = params?.id;
  const t = useT();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const detailTranslator = React.useMemo(() => createTranslatorWithFallback(t), [t]);
  const notesAdapter = React.useMemo(() => createCustomerNotesAdapter(detailTranslator), [detailTranslator]);
  const router = useRouter();
  const searchParams = useSearchParams();
  const initialTab = React.useMemo(() => {
    const raw = searchParams?.get("tab");
    if (raw === "notes" || raw === "activities" || raw === "deals" || raw === "addresses" || raw === "tasks") {
      return raw;
    }
    return "notes";
  }, [searchParams]);
  const [data, setData] = React.useState(null);
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const [activeTab, setActiveTab] = React.useState(initialTab);
  const [sectionAction, setSectionAction] = React.useState(null);
  const [isDeleting, setIsDeleting] = React.useState(false);
  const handleSectionActionChange = React.useCallback((action) => {
    setSectionAction(action);
  }, []);
  const handleSectionAction = React.useCallback(() => {
    if (!sectionAction || sectionAction.disabled) return;
    sectionAction.onClick();
  }, [sectionAction]);
  React.useEffect(() => {
    setSectionAction(null);
  }, [activeTab]);
  const validators = React.useMemo(() => ({
    email: (value) => {
      if (!value) return null;
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return emailRegex.test(value) ? null : t("customers.people.detail.inline.emailInvalid");
    },
    phone: (value) => {
      if (!value) return null;
      return value.length >= 3 ? null : t("customers.people.detail.inline.phoneInvalid");
    },
    displayName: (value) => {
      const trimmed = value.trim();
      return trimmed.length ? null : t("customers.people.form.displayName.error");
    },
    linkedInUrl: (value) => {
      if (!value) return null;
      const candidate = value.trim();
      return isValidSocialUrl(candidate, { hosts: ["linkedin.com"], pathRequired: true }) ? null : t("customers.people.detail.inline.linkedInInvalid");
    },
    twitterUrl: (value) => {
      if (!value) return null;
      const candidate = value.trim();
      return isValidSocialUrl(candidate, { hosts: ["twitter.com", "x.com"], pathRequired: true }) ? null : t("customers.people.detail.inline.twitterInvalid");
    }
  }), [t]);
  const personId = data?.person?.id ?? null;
  const mutationContextId = React.useMemo(
    () => personId ? `customer-person:${personId}` : `customer-person:${id ?? "pending"}`,
    [id, personId]
  );
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const injectionContext = React.useMemo(
    () => ({
      formId: mutationContextId,
      personId,
      resourceKind: "customers.person",
      resourceId: personId ?? (id ?? void 0),
      data,
      retryLastMutation
    }),
    [data, id, mutationContextId, personId, retryLastMutation]
  );
  const runMutationWithContext = React.useCallback(
    async (operation, mutationPayload) => {
      return runMutation({
        operation,
        mutationPayload,
        context: injectionContext
      });
    },
    [injectionContext, runMutation]
  );
  const { widgets: injectedTabWidgets } = useInjectionWidgets("customers.person.detail:tabs", {
    context: injectionContext,
    triggerOnLoad: true
  });
  const injectedTabs = React.useMemo(
    () => (injectedTabWidgets ?? []).filter((widget) => (widget.placement?.kind ?? "tab") === "tab").map((widget) => {
      const id2 = widget.placement?.groupId ?? widget.widgetId;
      const label = widget.placement?.groupLabel ?? widget.module.metadata.title;
      const priority = typeof widget.placement?.priority === "number" ? widget.placement.priority : 0;
      const render = () => /* @__PURE__ */ jsx(
        widget.module.Widget,
        {
          context: injectionContext,
          data,
          onDataChange: (next) => setData(next)
        }
      );
      return { id: id2, label, priority, render };
    }).sort((a, b) => b.priority - a.priority),
    [data, injectedTabWidgets, injectionContext]
  );
  const injectedTabMap = React.useMemo(() => new Map(injectedTabs.map((tab) => [tab.id, tab.render])), [injectedTabs]);
  const tabs = React.useMemo(
    () => [
      { id: "notes", label: t("customers.people.detail.tabs.notes") },
      { id: "activities", label: t("customers.people.detail.tabs.activities") },
      { id: "deals", label: t("customers.people.detail.tabs.deals") },
      { id: "addresses", label: t("customers.people.detail.tabs.addresses") },
      { id: "tasks", label: t("customers.people.detail.tabs.tasks") },
      ...injectedTabs.map((tab) => ({ id: tab.id, label: tab.label }))
    ],
    [injectedTabs, t]
  );
  const personName = React.useMemo(
    () => data?.person?.displayName ? data.person.displayName : t("customers.people.list.deleteFallbackName"),
    [data?.person?.displayName, t]
  );
  const dealsScope = React.useMemo(
    () => personId ? { kind: "person", entityId: personId } : null,
    [personId]
  );
  const dealSelectOptions = React.useMemo(
    () => Array.isArray(data?.deals) ? data.deals.map((deal) => {
      if (!deal || typeof deal !== "object") return null;
      const record = deal;
      const id2 = typeof record.id === "string" ? record.id : "";
      if (!id2) return null;
      const rawTitle = typeof record.title === "string" ? record.title.trim() : "";
      const label = rawTitle.length ? rawTitle : id2;
      return { id: id2, label };
    }).filter((option) => option !== null) : [],
    [data?.deals]
  );
  const handleNotesLoadingChange = React.useCallback(() => {
  }, []);
  const handleActivitiesLoadingChange = React.useCallback(() => {
  }, []);
  const handleDealsLoadingChange = React.useCallback(() => {
  }, []);
  const handleAddressesLoadingChange = React.useCallback(() => {
  }, []);
  const handleTasksLoadingChange = React.useCallback(() => {
  }, []);
  const initialLoadDoneRef = React.useRef(false);
  const loadData = React.useCallback(async () => {
    if (!id) {
      setIsNotFound(true);
      setIsLoading(false);
      return;
    }
    if (!initialLoadDoneRef.current) {
      setIsLoading(true);
    }
    setError(null);
    setIsNotFound(false);
    try {
      const payload = await readApiResultOrThrow(
        `/api/customers/people/${encodeURIComponent(id)}?include=todos`,
        void 0,
        { errorMessage: t("customers.people.detail.error.load") }
      );
      setData(payload);
    } catch (err) {
      if (err.status === 404) {
        setIsNotFound(true);
      } else {
        const message = err instanceof Error ? err.message : t("customers.people.detail.error.load");
        setError(message);
      }
      if (!initialLoadDoneRef.current) setData(null);
    } finally {
      setIsLoading(false);
      initialLoadDoneRef.current = true;
    }
  }, [id, t]);
  React.useEffect(() => {
    loadData().catch(() => {
    });
  }, [loadData]);
  const savePerson = React.useCallback(
    async (patch, apply) => {
      if (!data) return;
      const payload = { id: data.person.id, ...patch };
      const result = await runMutationWithContext(
        () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(data?.person?.updatedAt),
          () => apiCallOrThrow(
            "/api/customers/people",
            {
              method: "PUT",
              headers: { "content-type": "application/json" },
              body: JSON.stringify(payload)
            },
            { errorMessage: t("customers.people.detail.inline.error") }
          )
        ),
        payload
      );
      const nextUpdatedAt = result?.result?.updatedAt ?? null;
      setData((prev) => {
        if (!prev) return prev;
        const applied = apply(prev);
        return nextUpdatedAt ? { ...applied, person: { ...applied.person, updatedAt: nextUpdatedAt } } : applied;
      });
    },
    [data, runMutationWithContext, t]
  );
  const updateDisplayName = React.useCallback(
    async (next) => {
      const send = typeof next === "string" ? next : "";
      await savePerson(
        { displayName: send },
        (prev) => ({
          ...prev,
          person: {
            ...prev.person,
            displayName: next && next.length ? next : prev.person.displayName
          }
        })
      );
    },
    [savePerson]
  );
  const updateProfileField = React.useCallback(
    async (field, next) => {
      const send = typeof next === "string" ? next : "";
      await savePerson(
        { [field]: send },
        (prev) => {
          if (!prev.profile) return prev;
          const nextValue = next && next.length ? next : null;
          return {
            ...prev,
            profile: {
              ...prev.profile,
              [field]: nextValue
            }
          };
        }
      );
    },
    [savePerson]
  );
  const handleDelete = React.useCallback(async () => {
    if (!personId) return;
    const confirmed = await confirm({
      title: t("customers.people.list.deleteConfirm", void 0, { name: personName }),
      variant: "destructive"
    });
    if (!confirmed) return;
    setIsDeleting(true);
    try {
      await runMutationWithContext(
        () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(data?.person?.updatedAt),
          () => apiCallOrThrow(
            `/api/customers/people?id=${encodeURIComponent(personId)}`,
            {
              method: "DELETE",
              headers: { "content-type": "application/json" }
            },
            { errorMessage: t("customers.people.list.deleteError") }
          )
        ),
        { id: personId }
      );
      flash(t("customers.people.list.deleteSuccess"), "success");
      router.push("/backend/customers/people");
    } catch (err) {
      const message = err instanceof Error ? err.message : t("customers.people.list.deleteError");
      flash(message, "error");
    } finally {
      setIsDeleting(false);
    }
  }, [confirm, personId, personName, router, runMutationWithContext, t]);
  const handleTagsChange = React.useCallback((nextTags) => {
    setData((prev) => prev ? { ...prev, tags: nextTags } : prev);
  }, []);
  const handleCustomFieldsSubmit = React.useCallback(
    async (values) => {
      if (!data) {
        throw new Error(t("customers.people.detail.inline.error"));
      }
      const customPayload = collectCustomFieldValues(values, {
        transform: (value) => normalizeCustomFieldSubmitValue(value)
      });
      const prefixed = {};
      for (const [fieldId, value] of Object.entries(customPayload)) {
        prefixed[`cf_${fieldId}`] = value;
      }
      if (!Object.keys(customPayload).length) {
        flash(t("ui.forms.flash.saveSuccess"), "success");
        return;
      }
      try {
        const payload = {
          id: data.person.id,
          customFields: customPayload
        };
        await runMutationWithContext(
          () => withScopedApiRequestHeaders(
            buildOptimisticLockHeader(data?.person?.updatedAt),
            () => apiCallOrThrow(
              "/api/customers/people",
              {
                method: "PUT",
                headers: { "content-type": "application/json" },
                body: JSON.stringify(payload)
              },
              { errorMessage: t("customers.people.detail.inline.error") }
            )
          ),
          payload
        );
      } catch (err) {
        const { message: helperMessage, fieldErrors } = mapCrudServerErrorToFormErrors(err);
        const mappedErrors = fieldErrors ? Object.entries(fieldErrors).reduce((acc, [key, value]) => {
          const formKey = key.startsWith("cf_") ? key : `cf_${key}`;
          acc[formKey] = value;
          return acc;
        }, {}) : void 0;
        const error2 = new Error(helperMessage ?? t("customers.people.detail.inline.error"));
        if (mappedErrors && Object.keys(mappedErrors).length) error2.fieldErrors = mappedErrors;
        throw error2;
      }
      setData((prev) => {
        if (!prev) return prev;
        const nextCustomFields = { ...prefixed };
        return { ...prev, customFields: nextCustomFields };
      });
      flash(t("ui.forms.flash.saveSuccess"), "success");
    },
    [data, runMutationWithContext, t]
  );
  if (isLoading) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "flex h-[50vh] flex-col items-center justify-center gap-2 text-muted-foreground", children: [
      /* @__PURE__ */ jsx(Spinner, { className: "h-6 w-6" }),
      /* @__PURE__ */ jsx("span", { children: t("customers.people.detail.loading") })
    ] }) }) });
  }
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("customers.people.detail.error.notFound", "Person not found."),
        backHref: "/backend/customers/people",
        backLabel: t("customers.people.detail.actions.backToList", "Back to people")
      }
    ) }) });
  }
  if (error || !data || !personId) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      ErrorMessage,
      {
        label: error ?? t("customers.people.detail.error.notFound", "Person not found."),
        action: /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", size: "sm", children: /* @__PURE__ */ jsx(Link, { href: "/backend/customers/people", children: t("customers.people.detail.actions.backToList", "Back to people") }) })
      }
    ) }) });
  }
  const { person, profile } = data;
  const detailFields = [
    {
      key: "displayName",
      kind: "text",
      label: t("customers.people.detail.fields.displayName"),
      value: person.displayName,
      placeholder: t("customers.people.form.displayName.placeholder"),
      emptyLabel: t("customers.people.detail.noValue"),
      validator: validators.displayName,
      onSave: updateDisplayName
    },
    {
      key: "firstName",
      kind: "text",
      label: t("customers.people.form.firstName"),
      value: profile?.firstName ?? null,
      placeholder: t("customers.people.form.firstName"),
      emptyLabel: t("customers.people.detail.noValue"),
      onSave: (next) => updateProfileField("firstName", next)
    },
    {
      key: "lastName",
      kind: "text",
      label: t("customers.people.form.lastName"),
      value: profile?.lastName ?? null,
      placeholder: t("customers.people.form.lastName"),
      emptyLabel: t("customers.people.detail.noValue"),
      onSave: (next) => updateProfileField("lastName", next)
    },
    {
      key: "jobTitle",
      kind: "custom",
      label: t("customers.people.form.jobTitle"),
      emptyLabel: t("customers.people.detail.noValue"),
      render: () => /* @__PURE__ */ jsx(
        InlineDictionaryEditor,
        {
          label: t("customers.people.form.jobTitle"),
          value: profile?.jobTitle ?? null,
          emptyLabel: t("customers.people.detail.noValue"),
          kind: "job-titles",
          onSave: async (next) => updateProfileField("jobTitle", next),
          selectClassName: "h-9 w-full rounded border px-3 text-sm",
          variant: "muted",
          activateOnClick: true
        }
      )
    },
    {
      key: "lifecycleStage",
      kind: "custom",
      label: t("customers.people.detail.fields.lifecycleStage"),
      emptyLabel: t("customers.people.detail.noValue"),
      render: () => /* @__PURE__ */ jsx(
        InlineDictionaryEditor,
        {
          label: t("customers.people.detail.fields.lifecycleStage"),
          value: person.lifecycleStage ?? null,
          emptyLabel: t("customers.people.detail.noValue"),
          kind: "lifecycle-stages",
          onSave: async (next) => {
            const send = typeof next === "string" ? next : "";
            await savePerson(
              { lifecycleStage: send },
              (prev) => ({
                ...prev,
                person: { ...prev.person, lifecycleStage: next && next.length ? next : null }
              })
            );
          },
          selectClassName: "h-9 w-full rounded border px-3 text-sm",
          variant: "muted",
          activateOnClick: true
        }
      )
    },
    {
      key: "source",
      kind: "custom",
      label: t("customers.people.form.source"),
      emptyLabel: t("customers.people.detail.noValue"),
      render: () => /* @__PURE__ */ jsx(
        InlineDictionaryEditor,
        {
          label: t("customers.people.form.source"),
          value: person.source ?? null,
          emptyLabel: t("customers.people.detail.noValue"),
          kind: "sources",
          onSave: async (next) => {
            const send = typeof next === "string" ? next : "";
            await savePerson(
              { source: send },
              (prev) => ({
                ...prev,
                person: { ...prev.person, source: next && next.length ? next : null }
              })
            );
          },
          selectClassName: "h-9 w-full rounded border px-3 text-sm",
          variant: "muted",
          activateOnClick: true
        }
      )
    },
    {
      key: "description",
      kind: "multiline",
      label: t("customers.people.form.description"),
      value: person.description ?? null,
      placeholder: t("customers.people.form.description"),
      emptyLabel: t("customers.people.detail.noValue"),
      gridClassName: "sm:col-span-2 xl:col-span-3",
      renderDisplay: renderMultilineMarkdownDisplay,
      onSave: async (next) => {
        const send = typeof next === "string" ? next : "";
        await savePerson(
          { description: send },
          (prev) => ({
            ...prev,
            person: { ...prev.person, description: next && next.length ? next : null }
          })
        );
      }
    },
    {
      key: "department",
      kind: "text",
      label: t("customers.people.detail.fields.department"),
      value: profile?.department ?? null,
      placeholder: t("customers.people.detail.fields.department"),
      emptyLabel: t("customers.people.detail.noValue"),
      onSave: (next) => updateProfileField("department", next)
    },
    {
      key: "linkedInUrl",
      kind: "text",
      label: t("customers.people.detail.fields.linkedIn"),
      value: profile?.linkedInUrl ?? null,
      placeholder: t("customers.people.detail.fields.linkedIn"),
      emptyLabel: t("customers.people.detail.noValue"),
      onSave: (next) => updateProfileField("linkedInUrl", next),
      inputType: "url",
      validator: validators.linkedInUrl,
      renderDisplay: renderLinkedInDisplay
    },
    {
      key: "twitterUrl",
      kind: "text",
      label: t("customers.people.detail.fields.twitter"),
      value: profile?.twitterUrl ?? null,
      placeholder: t("customers.people.detail.fields.twitter"),
      emptyLabel: t("customers.people.detail.noValue"),
      onSave: (next) => updateProfileField("twitterUrl", next),
      inputType: "url",
      validator: validators.twitterUrl,
      renderDisplay: renderTwitterDisplay
    }
  ];
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsxs(PageBody, { className: "space-y-8", children: [
      /* @__PURE__ */ jsx(
        PersonHighlights,
        {
          person,
          profile,
          validators: {
            email: validators.email,
            phone: validators.phone,
            displayName: validators.displayName
          },
          utilityActions: /* @__PURE__ */ jsx(
            SendObjectMessageDialog,
            {
              object: {
                entityModule: "customers",
                entityType: "person",
                entityId: personId,
                previewData: {
                  title: person.displayName,
                  subtitle: person.primaryEmail ?? void 0,
                  metadata: {
                    [t("customers.people.detail.highlights.primaryPhone")]: person.primaryPhone ?? "-",
                    [t("customers.people.detail.fields.jobTitle")]: profile?.jobTitle ?? "-"
                  }
                }
              },
              viewHref: `/backend/customers/people/${personId}`
            }
          ),
          onDisplayNameSave: updateDisplayName,
          onPrimaryEmailSave: async (next) => {
            const send = typeof next === "string" ? next : "";
            await savePerson(
              { primaryEmail: send },
              (prev) => ({
                ...prev,
                person: {
                  ...prev.person,
                  primaryEmail: next && next.length ? next.toLowerCase() : null
                }
              })
            );
          },
          onPrimaryPhoneSave: async (next) => {
            const send = typeof next === "string" ? next : "";
            await savePerson(
              { primaryPhone: send },
              (prev) => ({
                ...prev,
                person: {
                  ...prev.person,
                  primaryPhone: next && next.length ? next : null
                }
              })
            );
          },
          onStatusSave: async (next) => {
            const send = typeof next === "string" ? next : "";
            await savePerson(
              { status: send },
              (prev) => ({
                ...prev,
                person: {
                  ...prev.person,
                  status: next && next.length ? next : null
                }
              })
            );
          },
          onNextInteractionSave: async (next) => {
            await savePerson(
              {
                nextInteraction: next ? {
                  at: next.at,
                  name: next.name,
                  refId: next.refId ?? void 0,
                  icon: next.icon ?? void 0,
                  color: next.color ?? void 0
                } : null
              },
              (prev) => ({
                ...prev,
                person: {
                  ...prev.person,
                  nextInteractionAt: next ? next.at : null,
                  nextInteractionName: next ? next.name || null : null,
                  nextInteractionRefId: next ? next.refId || null : null,
                  nextInteractionIcon: next ? next.icon || null : null,
                  nextInteractionColor: next ? next.color || null : null
                }
              })
            );
          },
          onDelete: handleDelete,
          isDeleting,
          onCompanySave: async (next) => {
            const normalized = typeof next === "string" && next.trim().length ? next.trim() : null;
            await savePerson(
              { companyEntityId: normalized },
              (prev) => {
                if (!prev.profile) return prev;
                return {
                  ...prev,
                  profile: {
                    ...prev.profile,
                    companyEntityId: normalized
                  }
                };
              }
            );
          }
        }
      ),
      /* @__PURE__ */ jsx(
        DetailTabsLayout,
        {
          tabs,
          activeTab,
          onTabChange: setActiveTab,
          sectionAction,
          onSectionAction: handleSectionAction,
          navAriaLabel: t("customers.people.detail.tabs.label", "Person detail sections"),
          headerClassName: "mb-1",
          children: (() => {
            const injected = injectedTabMap.get(activeTab);
            if (injected) return injected();
            if (activeTab === "notes") {
              return /* @__PURE__ */ jsx(
                NotesSection,
                {
                  entityId: personId,
                  dealOptions: dealSelectOptions,
                  emptyLabel: t("customers.people.detail.empty.comments"),
                  viewerUserId: data.viewer?.userId ?? null,
                  viewerName: data.viewer?.name ?? null,
                  viewerEmail: data.viewer?.email ?? null,
                  addActionLabel: t("customers.people.detail.notes.addLabel"),
                  emptyState: {
                    title: t("customers.people.detail.emptyState.notes.title"),
                    actionLabel: t("customers.people.detail.emptyState.notes.action")
                  },
                  onActionChange: handleSectionActionChange,
                  translator: detailTranslator,
                  onLoadingChange: handleNotesLoadingChange,
                  dataAdapter: notesAdapter,
                  renderIcon: renderDictionaryIcon,
                  renderColor: renderDictionaryColor,
                  iconSuggestions: ICON_SUGGESTIONS,
                  readMarkdownPreference: readMarkdownPreferenceCookie,
                  writeMarkdownPreference: writeMarkdownPreferenceCookie
                }
              );
            }
            if (activeTab === "activities") {
              return /* @__PURE__ */ jsx(
                ActivitiesSection,
                {
                  entityId: personId,
                  dealOptions: dealSelectOptions,
                  defaultEntityId: personId ?? void 0,
                  runGuardedMutation: runMutationWithContext,
                  addActionLabel: t("customers.people.detail.activities.add"),
                  emptyState: {
                    title: t("customers.people.detail.emptyState.activities.title"),
                    actionLabel: t("customers.people.detail.emptyState.activities.action")
                  },
                  onActionChange: handleSectionActionChange,
                  onLoadingChange: handleActivitiesLoadingChange
                }
              );
            }
            if (activeTab === "deals") {
              return /* @__PURE__ */ jsx(
                DealsSection,
                {
                  scope: dealsScope,
                  emptyLabel: t("customers.people.detail.empty.deals"),
                  addActionLabel: t("customers.people.detail.actions.addDeal"),
                  emptyState: {
                    title: t("customers.people.detail.emptyState.deals.title"),
                    actionLabel: t("customers.people.detail.emptyState.deals.action")
                  },
                  onActionChange: handleSectionActionChange,
                  onLoadingChange: handleDealsLoadingChange,
                  onDataRefresh: loadData,
                  translator: detailTranslator,
                  runGuardedMutation: runMutationWithContext
                }
              );
            }
            if (activeTab === "addresses") {
              return /* @__PURE__ */ jsx(
                AddressesSection,
                {
                  entityId: personId,
                  emptyLabel: t("customers.people.detail.empty.addresses"),
                  addActionLabel: t("customers.people.detail.addresses.add"),
                  emptyState: {
                    title: t("customers.people.detail.emptyState.addresses.title"),
                    actionLabel: t("customers.people.detail.emptyState.addresses.action")
                  },
                  onActionChange: handleSectionActionChange,
                  onLoadingChange: handleAddressesLoadingChange,
                  translator: detailTranslator
                }
              );
            }
            if (activeTab === "tasks") {
              return /* @__PURE__ */ jsx(
                TasksSection,
                {
                  entityId: personId,
                  initialTasks: data.todos,
                  runGuardedMutation: runMutationWithContext,
                  emptyLabel: t("customers.people.detail.empty.todos"),
                  addActionLabel: t("customers.people.detail.tasks.add"),
                  emptyState: {
                    title: t("customers.people.detail.emptyState.tasks.title"),
                    actionLabel: t("customers.people.detail.emptyState.tasks.action")
                  },
                  onActionChange: handleSectionActionChange,
                  onLoadingChange: handleTasksLoadingChange,
                  translator: detailTranslator,
                  entityName: personName,
                  dialogContextKey: "customers.people.detail.tasks.dialog.context",
                  dialogContextFallback: "This task will be linked to {{name}}"
                }
              );
            }
            return null;
          })()
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsx("h2", { className: "text-sm font-semibold", children: t("customers.people.detail.sections.details") }),
          /* @__PURE__ */ jsx(DetailFieldsSection, { fields: detailFields }),
          /* @__PURE__ */ jsx(
            InjectionSpot,
            {
              spotId: "customers.person.detail:details",
              context: injectionContext,
              data,
              onDataChange: (next) => setData(next)
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          CustomDataSection,
          {
            entityIds: [E.customers.customer_entity, E.customers.customer_person_profile],
            values: data.customFields ?? {},
            onSubmit: handleCustomFieldsSubmit,
            title: t("customers.people.detail.sections.customFields")
          }
        ),
        /* @__PURE__ */ jsx(
          TagsSection,
          {
            entityId: data.person.id,
            tags: data.tags,
            onChange: handleTagsChange,
            isSubmitting: false
          }
        )
      ] })
    ] }),
    ConfirmDialogElement
  ] });
}
export {
  CustomerPersonDetailPage as default
};
//# sourceMappingURL=page.js.map
