"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useRouter, useSearchParams, usePathname } from "next/navigation";
import { User, Hash, Users, Building2 } from "lucide-react";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { CollapsibleZoneLayout } from "@open-mercato/ui/backend/crud/CollapsibleZoneLayout";
import { useIsMobile } from "@open-mercato/ui/hooks/useIsMobile";
import { updateCrud, deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { E } from "../../../../../../generated/entities.ids.generated.js";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useOrganizationScopeDetail } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { Button } from "@open-mercato/ui/primitives/button";
import { AttachmentsSection, ErrorMessage, LoadingMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { InjectionSpot, useInjectionWidgets } from "@open-mercato/ui/backend/injection/InjectionSpot";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from "@open-mercato/ui/backend/injection/recordContext";
import { createTranslatorWithFallback } from "@open-mercato/shared/lib/i18n/translate";
import { ActivitiesSection } from "../../../../components/detail/ActivitiesSection.js";
import { PersonEmailThreadsTab } from "../../../../components/detail/PersonEmailThreadsTab.js";
import { ActivitiesCard } from "../../../../components/detail/ActivitiesCard.js";
import { DealsSection } from "../../../../components/detail/DealsSection.js";
import { TasksSection } from "../../../../components/detail/TasksSection.js";
import { ScheduleActivityDialog } from "../../../../components/detail/ScheduleActivityDialog.js";
import { PersonDetailHeader } from "../../../../components/detail/PersonDetailHeader.js";
import { ChangelogTab } from "../../../../components/detail/ChangelogTab.js";
import { PersonDetailTabs, resolveLegacyTab } from "../../../../components/detail/PersonDetailTabs.js";
import { AddressesSection } from "../../../../components/detail/AddressesSection.js";
import { PersonCompaniesSection } from "../../../../components/detail/PersonCompaniesSection.js";
import { MobilePersonDetail } from "../../../../components/detail/MobilePersonDetail.js";
import {
  buildPersonEditPayload,
  createPersonEditFields,
  createPersonPersonalDataGroups,
  createPersonEditSchema,
  mapPersonOverviewToFormValues
} from "../../../../components/formConfig.js";
import { coerceDisplayName, coerceDisplayNameOrNull } from "../../../../lib/displayName.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("customers");
function PersonDetailV2Page({ params }) {
  const id = params?.id;
  const t = useT();
  const router = useRouter();
  const searchParams = useSearchParams();
  const pathname = usePathname();
  const { organizationId } = useOrganizationScopeDetail();
  const isMobile = useIsMobile();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const detailTranslator = React.useMemo(() => createTranslatorWithFallback(t), [t]);
  const formSchema = React.useMemo(() => createPersonEditSchema(), []);
  const fields = React.useMemo(() => createPersonEditFields(t), [t]);
  const [data, setData] = React.useState(null);
  const dataRef = React.useRef(null);
  React.useEffect(() => {
    dataRef.current = data;
  }, [data]);
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const [isDirty, setIsDirty] = React.useState(false);
  const [isSaving, setIsSaving] = React.useState(false);
  const formWrapperRef = React.useRef(null);
  const initialTab = React.useMemo(() => {
    return resolveLegacyTab(searchParams?.get("tab"));
  }, [searchParams]);
  const [activeTab, setActiveTab] = React.useState(initialTab);
  const [sectionAction, setSectionAction] = React.useState(null);
  const [scheduleDialogOpen, setScheduleDialogOpen] = React.useState(false);
  const [scheduleEditData, setScheduleEditData] = React.useState(null);
  const [activityRefreshKey, setActivityRefreshKey] = React.useState(0);
  const [dealCount, setDealCount] = React.useState(0);
  const currentPersonId = data?.person?.id ?? null;
  const mutationContextId = React.useMemo(
    () => currentPersonId ? `customer-person:${currentPersonId}` : `customer-person:${id ?? "pending"}`,
    [currentPersonId, id]
  );
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const personDisplayName = coerceDisplayName(data?.person?.displayName);
  const personName = personDisplayName.trim().length ? personDisplayName : t("customers.people.list.deleteFallbackName", "this person");
  const personDisplayNameForGroups = personDisplayName.trim().length ? personDisplayName.trim() : null;
  const scheduleDialogCompanyName = coerceDisplayNameOrNull(
    data?.company?.displayName ?? data?.companies?.[0]?.displayName ?? null
  );
  const groups = React.useMemo(
    () => createPersonPersonalDataGroups(t, { entityName: personDisplayNameForGroups }),
    [t, personDisplayNameForGroups]
  );
  const zoneSections = React.useMemo(() => [
    { id: "personalData", icon: User, label: t("customers.people.form.groups.personalData", "Personal data") },
    { id: "companyRole", icon: Building2, label: t("customers.people.form.groups.companyRole", "Company & role") },
    { id: "customFields", icon: Hash, label: t("customers.people.form.groups.customAttributes", "Custom attributes") },
    { id: "roles", icon: Users, label: t("customers.people.form.groups.roles", "My roles") }
  ], [t]);
  const initialLoadDoneRef = React.useRef(false);
  const loadData = React.useCallback(async (lockTokenOverride) => {
    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)}`,
        void 0,
        { errorMessage: t("customers.people.detail.error.load", "Failed to load person.") }
      );
      const next = lockTokenOverride && payload?.person ? { ...payload, person: { ...payload.person, updatedAt: lockTokenOverride, updated_at: lockTokenOverride } } : payload;
      setData(next);
    } catch (err) {
      if (err.status === 404) {
        setIsNotFound(true);
      } else {
        const message = err instanceof Error ? err.message : t("customers.people.detail.error.load", "Failed to load person.");
        setError(message);
      }
      if (!initialLoadDoneRef.current) setData(null);
    } finally {
      setIsLoading(false);
      initialLoadDoneRef.current = true;
    }
  }, [id, t]);
  React.useEffect(() => {
    loadData().catch((err) => logger.warn("loadData failed", { component: "people-v2", err }));
  }, [loadData]);
  React.useEffect(() => {
    setDealCount(data?.counts?.deals ?? 0);
  }, [data?.counts?.deals]);
  const handleActivityCreated = React.useCallback(() => {
    setActivityRefreshKey((k) => k + 1);
    loadData().catch((err) => logger.warn("reload after activity failed", { component: "people-v2", err }));
  }, [loadData]);
  const plannedActivities = React.useMemo(() => {
    return data?.plannedActivitiesPreview ?? [];
  }, [data?.plannedActivitiesPreview]);
  const injectionContext = React.useMemo(
    () => ({
      formId: mutationContextId,
      personId: currentPersonId,
      resourceKind: "customers.person",
      resourceId: currentPersonId ?? (id ?? void 0),
      data,
      retryLastMutation
    }),
    [currentPersonId, data, id, mutationContextId, retryLastMutation]
  );
  const runMutationWithContext = React.useCallback(
    async (operation, mutationPayload) => {
      return runMutation({
        operation,
        mutationPayload,
        context: injectionContext
      });
    },
    [injectionContext, runMutation]
  );
  useSetCurrentRecordInjectionContext(
    buildRecordInjectionContext({
      resourceKind: "customers.person",
      resourceId: currentPersonId,
      updatedAt: data?.person?.updatedAt ?? data?.person?.updated_at ?? null,
      data,
      path: pathname
    })
  );
  const handleAddActivity = React.useCallback((kind) => {
    setScheduleEditData({
      id: "",
      interactionType: kind,
      title: null,
      body: null,
      scheduledAt: null,
      durationMinutes: null,
      location: null,
      allDay: null,
      recurrenceRule: null,
      recurrenceEnd: null,
      participants: null,
      reminderMinutes: null,
      visibility: null,
      linkedEntities: null,
      guestPermissions: null
    });
    setScheduleDialogOpen(true);
  }, []);
  const handleEditActivity = React.useCallback((activity) => {
    const raw = activity;
    const durationValue = typeof raw.duration === "number" ? raw.duration : typeof raw.durationMinutes === "number" ? raw.durationMinutes : null;
    const editPayload = {
      id: activity.id,
      updatedAt: typeof raw.updatedAt === "string" ? raw.updatedAt : typeof raw.updated_at === "string" ? raw.updated_at : null,
      interactionType: typeof activity.interactionType === "string" ? activity.interactionType : void 0,
      title: typeof activity.title === "string" ? activity.title : null,
      body: typeof activity.body === "string" ? activity.body : null,
      scheduledAt: typeof activity.scheduledAt === "string" ? activity.scheduledAt : null,
      occurredAt: typeof activity.occurredAt === "string" ? activity.occurredAt : null,
      durationMinutes: durationValue,
      location: typeof raw.location === "string" ? raw.location : null,
      allDay: typeof raw.allDay === "boolean" ? raw.allDay : null,
      recurrenceRule: typeof raw.recurrenceRule === "string" ? raw.recurrenceRule : null,
      recurrenceEnd: typeof raw.recurrenceEnd === "string" ? raw.recurrenceEnd : null,
      participants: Array.isArray(raw.participants) ? raw.participants : null,
      reminderMinutes: typeof raw.reminderMinutes === "number" ? raw.reminderMinutes : null,
      visibility: typeof raw.visibility === "string" ? raw.visibility : null,
      linkedEntities: Array.isArray(raw.linkedEntities) ? raw.linkedEntities : null,
      guestPermissions: raw.guestPermissions && typeof raw.guestPermissions === "object" ? raw.guestPermissions : null,
      customValues: raw.customValues && typeof raw.customValues === "object" ? raw.customValues : null,
      phoneNumber: typeof raw.phoneNumber === "string" ? raw.phoneNumber : null
    };
    setScheduleEditData(editPayload);
    setScheduleDialogOpen(true);
  }, []);
  const { widgets: injectedTabWidgets } = useInjectionWidgets("detail:customers.person:tabs", {
    context: injectionContext,
    triggerOnLoad: true
  });
  const injectedTabs = React.useMemo(
    () => (injectedTabWidgets ?? []).filter((widget) => (widget.placement?.kind ?? "tab") === "tab").map((widget) => {
      const tabId = widget.placement?.groupId ?? widget.widgetId;
      const label = widget.placement?.groupLabel ?? widget.module.metadata.title ?? tabId;
      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: tabId, 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 handleTagsChange = React.useCallback((nextTags) => {
    setData((prev) => prev ? { ...prev, tags: nextTags } : prev);
  }, []);
  const tagsSectionControllerRef = React.useRef(null);
  const handleSectionActionChange = React.useCallback((action) => {
    setSectionAction((prev) => action !== null ? action : prev);
  }, []);
  React.useEffect(() => {
    setSectionAction(null);
  }, [activeTab]);
  const dealsScope = React.useMemo(
    () => currentPersonId ? { kind: "person", entityId: currentPersonId } : null,
    [currentPersonId]
  );
  const initialValues = React.useMemo(
    () => data ? mapPersonOverviewToFormValues(data) : void 0,
    [data]
  );
  const handleFormSubmit = React.useCallback(
    async (values) => {
      setIsSaving(true);
      try {
        await tagsSectionControllerRef.current?.flush();
        let payload;
        try {
          payload = buildPersonEditPayload(values, organizationId);
        } catch (err) {
          if (err instanceof Error && err.message === "DISPLAY_NAME_REQUIRED") {
            const message = t("customers.people.form.displayName.error");
            throw createCrudFormError(message, { displayName: message });
          }
          throw err;
        }
        const lockedUpdatedAt = dataRef.current?.person?.updatedAt ?? dataRef.current?.person?.updated_at ?? null;
        const updateResponse = await withScopedApiRequestHeaders(
          buildOptimisticLockHeader(lockedUpdatedAt),
          () => updateCrud("customers/people", payload)
        );
        flash(t("customers.people.form.updateSuccess", "Person updated."), "success");
        const savedUpdatedAt = typeof updateResponse.result?.updatedAt === "string" ? updateResponse.result.updatedAt : null;
        await loadData(savedUpdatedAt);
      } finally {
        setIsSaving(false);
      }
    },
    [loadData, organizationId, t]
  );
  const handleFormDelete = React.useCallback(
    async () => {
      const personId2 = data?.person?.id ?? "";
      if (!personId2) return;
      const approved = await confirm({
        title: t("customers.people.detail.deleteConfirmTitle", "Delete person?"),
        description: t("customers.people.detail.deleteConfirmDescription", "This action cannot be undone."),
        confirmText: t("customers.people.detail.actions.delete", "Delete"),
        cancelText: t("customers.people.detail.actions.cancel", "Cancel"),
        variant: "destructive"
      });
      if (!approved) return;
      try {
        await runMutationWithContext(
          () => withScopedApiRequestHeaders(
            buildOptimisticLockHeader(data?.person?.updatedAt ?? data?.person?.updated_at ?? null),
            () => deleteCrud("customers/people", { id: personId2 })
          ),
          { id: personId2, operation: "deletePerson" }
        );
      } catch (err) {
        if (!surfaceRecordConflict(err, t)) {
          flash(
            err instanceof Error && err.message.trim().length > 0 ? err.message : t("customers.people.detail.deleteError", "Failed to delete person."),
            "error"
          );
        }
        return;
      }
      flash(t("customers.people.list.deleteSuccess", "Person deleted."), "success");
      router.push("/backend/customers/people");
    },
    [confirm, data?.person?.id, router, runMutationWithContext, t]
  );
  const handleHeaderSave = React.useCallback(() => {
    const form = formWrapperRef.current?.querySelector("form");
    if (form) form.requestSubmit();
  }, []);
  const interactionCount = data?.counts?.activities ?? 0;
  const todoCount = data?.counts?.todos ?? 0;
  const companyCount = data?.counts?.companies ?? (data?.companies?.length ?? (data?.company ? 1 : 0));
  if (isLoading) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(LoadingMessage, { label: t("customers.people.detail.loading", "Loading person\u2026") }) }) });
  }
  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?.person?.id || !initialValues) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      ErrorMessage,
      {
        label: error ?? t("customers.people.detail.error.load", "Failed to load person."),
        action: /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", children: /* @__PURE__ */ jsx(Link, { href: "/backend/customers/people", children: t("customers.people.detail.actions.backToList", "Back to people") }) })
      }
    ) }) });
  }
  const personId = data.person.id;
  const useCanonicalInteractions = data.interactionMode === "canonical";
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsx(InjectionSpot, { spotId: "detail:customers.person:header", context: injectionContext, data }),
    /* @__PURE__ */ jsx(InjectionSpot, { spotId: "detail:customers.person:status-badges", context: injectionContext, data }),
    /* @__PURE__ */ jsx(
      PersonDetailHeader,
      {
        data,
        onTagsChange: handleTagsChange,
        tagsSectionControllerRef,
        onSave: handleHeaderSave,
        onDelete: handleFormDelete,
        isDirty,
        isSaving,
        onOpenCompaniesTab: () => setActiveTab("companies"),
        onDataReload: () => {
          loadData().catch((err) => logger.warn("onDataReload failed", { component: "people-v2", err }));
        },
        onFocusField: (fieldName) => {
          const selectorMap = {
            primaryEmail: 'input[type="email"]',
            primaryPhone: 'input[type="tel"]'
          };
          const selector = selectorMap[fieldName];
          const input = selector ? formWrapperRef.current?.querySelector(selector) : null;
          if (input) {
            input.scrollIntoView({ behavior: "smooth", block: "center" });
            requestAnimationFrame(() => input.focus());
          }
        }
      }
    ),
    (() => {
      const zone1Content = /* @__PURE__ */ jsx("div", { ref: formWrapperRef, children: /* @__PURE__ */ jsx(
        CrudForm,
        {
          embedded: true,
          trackDirtyWhenEmbedded: true,
          injectionSpotId: "crud-form:customers.person",
          entityIds: [E.customers.customer_entity, E.customers.customer_person_profile],
          schema: formSchema,
          fields,
          groups,
          initialValues,
          optimisticLockUpdatedAt: data.person.updatedAt ?? data.person.updated_at ?? null,
          onSubmit: handleFormSubmit,
          onDelete: handleFormDelete,
          hideFooterActions: true,
          collapsibleGroups: { pageType: "person-v2", chevronPosition: "right" },
          sortableGroups: { pageType: "person-v2" },
          onDirtyChange: setIsDirty
        }
      ) });
      const zone2Content = /* @__PURE__ */ jsx(
        PersonDetailTabs,
        {
          activeTab,
          onTabChange: setActiveTab,
          injectedTabs: injectedTabs.map((tab) => ({ id: tab.id, label: tab.label })),
          activitiesCount: interactionCount,
          dealsCount: dealCount,
          companiesCount: companyCount,
          addressesCount: data?.counts?.addresses ?? 0,
          tasksCount: todoCount,
          sectionAction,
          children: /* @__PURE__ */ jsx("div", { className: "min-w-0", children: (() => {
            const injected = injectedTabMap.get(activeTab);
            if (injected) return injected();
            if (activeTab === "activities") {
              return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
                /* @__PURE__ */ jsx(
                  ActivitiesCard,
                  {
                    entityId: personId,
                    plannedActivities,
                    refreshKey: activityRefreshKey,
                    onAddNew: handleAddActivity,
                    onEditActivity: handleEditActivity,
                    entityCompanyName: data.company?.displayName ?? data.companies?.[0]?.displayName ?? null
                  }
                ),
                /* @__PURE__ */ jsx(
                  ActivitiesSection,
                  {
                    entityId: personId,
                    entityName: personName,
                    useCanonicalInteractions,
                    runGuardedMutation: runMutationWithContext,
                    onDataRefresh: handleActivityCreated,
                    refreshKey: activityRefreshKey,
                    addActionLabel: t("customers.people.detail.activities.add", "Log activity"),
                    emptyState: {
                      title: t("customers.people.detail.emptyState.activities.title", "No activities logged yet"),
                      actionLabel: t("customers.people.detail.emptyState.activities.action", "Log activity")
                    },
                    onActionChange: handleSectionActionChange,
                    onEditActivity: handleEditActivity
                  }
                )
              ] });
            }
            if (activeTab === "emails") {
              return /* @__PURE__ */ jsx(
                PersonEmailThreadsTab,
                {
                  personId,
                  defaultRecipient: data.person?.primaryEmail ?? null
                }
              );
            }
            if (activeTab === "deals") {
              return /* @__PURE__ */ jsx(
                DealsSection,
                {
                  scope: dealsScope,
                  emptyLabel: t("customers.people.detail.empty.deals", "No deals linked to this person."),
                  addActionLabel: t("customers.people.detail.actions.addDeal", "Add deal"),
                  emptyState: {
                    title: t("customers.people.detail.emptyState.deals.title", "No deals yet"),
                    actionLabel: t("customers.people.detail.emptyState.deals.action", "Create a deal")
                  },
                  onActionChange: handleSectionActionChange,
                  translator: detailTranslator,
                  runGuardedMutation: runMutationWithContext,
                  onCountDelta: (delta) => setDealCount((current) => Math.max(0, current + delta))
                }
              );
            }
            if (activeTab === "companies") {
              return /* @__PURE__ */ jsx(
                PersonCompaniesSection,
                {
                  personId,
                  personName,
                  initialLinkedCompanies: data?.companies ?? [],
                  onChanged: loadData,
                  runGuardedMutation: runMutationWithContext
                }
              );
            }
            if (activeTab === "addresses") {
              return /* @__PURE__ */ jsx(
                AddressesSection,
                {
                  entityId: personId,
                  emptyLabel: t("customers.people.detail.empty.addresses", "No addresses linked to this person."),
                  addActionLabel: t("customers.people.detail.addresses.add", "Add address"),
                  emptyState: {
                    title: t("customers.people.detail.emptyState.addresses.title", "No addresses yet"),
                    actionLabel: t("customers.people.detail.emptyState.addresses.action", "Add address")
                  },
                  onActionChange: handleSectionActionChange,
                  translator: detailTranslator
                }
              );
            }
            if (activeTab === "tasks") {
              return /* @__PURE__ */ jsx(
                TasksSection,
                {
                  entityId: personId,
                  initialTasks: [],
                  useCanonicalInteractions,
                  runGuardedMutation: runMutationWithContext,
                  onDataRefresh: loadData,
                  emptyLabel: t("customers.people.detail.empty.todos", "No tasks linked to this person."),
                  addActionLabel: t("customers.people.detail.tasks.add", "Add task"),
                  emptyState: {
                    title: t("customers.people.detail.emptyState.tasks.title", "Plan what happens next"),
                    actionLabel: t("customers.people.detail.emptyState.tasks.action", "Create task")
                  },
                  onActionChange: handleSectionActionChange,
                  translator: detailTranslator,
                  entityName: personName,
                  dialogContextKey: "customers.people.detail.tasks.dialog.context",
                  dialogContextFallback: "This task will be linked to {{name}}"
                }
              );
            }
            if (activeTab === "files") {
              return /* @__PURE__ */ jsx(
                AttachmentsSection,
                {
                  entityId: E.customers.customer_entity,
                  recordId: personId,
                  title: t("customers.people.detail.tabs.files", "Files"),
                  description: t("customers.people.detail.files.subtitle", "Upload and manage files linked to this person.")
                }
              );
            }
            if (activeTab === "changelog") {
              return /* @__PURE__ */ jsx(ChangelogTab, { entityId: personId, entityType: "person" });
            }
            return null;
          })() })
        }
      );
      return isMobile ? /* @__PURE__ */ jsx(MobilePersonDetail, { zone1: zone1Content, zone2: zone2Content }) : /* @__PURE__ */ jsx(
        CollapsibleZoneLayout,
        {
          pageType: "person-v2",
          entityName: personName,
          isDirty,
          sections: zoneSections,
          zone1: zone1Content,
          zone2: zone2Content
        }
      );
    })(),
    /* @__PURE__ */ jsx(InjectionSpot, { spotId: "detail:customers.person:footer", context: injectionContext, data }),
    /* @__PURE__ */ jsx(
      ScheduleActivityDialog,
      {
        open: scheduleDialogOpen,
        onClose: () => {
          setScheduleDialogOpen(false);
          setScheduleEditData(null);
        },
        entityId: personId,
        entityName: personName,
        companyName: scheduleDialogCompanyName,
        entityType: "person",
        onActivityCreated: handleActivityCreated,
        editData: scheduleEditData
      }
    ),
    ConfirmDialogElement
  ] }) }) });
}
export {
  PersonDetailV2Page as default
};
//# sourceMappingURL=page.js.map
