"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { Building2, UserSearch, Users } from "lucide-react";
import { EmptyState } from "@open-mercato/ui/primitives/empty-state";
import { useRouter, useSearchParams, usePathname } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { Button } from "@open-mercato/ui/primitives/button";
import { AttachmentsSection, ErrorMessage, LoadingMessage, NotesSection, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { InjectionSpot } from "@open-mercato/ui/backend/injection/InjectionSpot";
import { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from "@open-mercato/ui/backend/injection/recordContext";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { CollapsibleZoneLayout } from "@open-mercato/ui/backend/crud/CollapsibleZoneLayout";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { createTranslatorWithFallback } from "@open-mercato/shared/lib/i18n/translate";
import { E } from "../../../../../../generated/entities.ids.generated.js";
import { ActivitiesSection } from "../../../../components/detail/ActivitiesSection.js";
import { ChangelogTab } from "../../../../components/detail/ChangelogTab.js";
import { DealClosureActionBar } from "../../../../components/detail/DealClosureActionBar.js";
import { DealDetailHeader } from "../../../../components/detail/DealDetailHeader.js";
import { DealDetailTabs, resolveLegacyTab } from "../../../../components/detail/DealDetailTabs.js";
import { DealForm, useDealAssociationLookups } from "../../../../components/detail/DealForm.js";
import { DealLinkedEntitiesTab } from "../../../../components/detail/DealLinkedEntitiesTab.js";
import { ConfirmDealLostDialog } from "../../../../components/detail/ConfirmDealLostDialog.js";
import { DealLostSummaryDialog } from "../../../../components/detail/DealLostSummaryDialog.js";
import { DealWonPopup } from "../../../../components/detail/DealWonPopup.js";
import { InlineActivityComposer } from "../../../../components/detail/InlineActivityComposer.js";
import { PipelineStepper } from "../../../../components/detail/PipelineStepper.js";
import { PlannedActivitiesSection } from "../../../../components/detail/PlannedActivitiesSection.js";
import { ScheduleActivityDialog } from "../../../../components/detail/ScheduleActivityDialog.js";
import { createCustomerNotesAdapter } from "../../../../components/detail/notesAdapter.js";
import { readMarkdownPreferenceCookie, writeMarkdownPreferenceCookie } from "../../../../lib/markdownPreference.js";
import { ICON_SUGGESTIONS } from "../../../../lib/dictionaries.js";
import { renderDictionaryColor, renderDictionaryIcon } from "@open-mercato/core/modules/dictionaries/components/dictionaryAppearance";
import { formatCurrency, startOfNextQuarter } from "./hooks/formatters.js";
import { useDealActivities } from "./hooks/useDealActivities.js";
import { useDealAssociations } from "./hooks/useDealAssociations.js";
import { useDealClosure } from "./hooks/useDealClosure.js";
import { useDealData } from "./hooks/useDealData.js";
import { useDealFormHandlers } from "./hooks/useDealFormHandlers.js";
import { useDealInjectedTabs } from "./hooks/useDealInjectedTabs.js";
import { useDealMutationContext } from "./hooks/useDealMutationContext.js";
import { useDealPipeline } from "./hooks/useDealPipeline.js";
import { useScheduleDialog } from "./hooks/useScheduleDialog.js";
function DealDetailPage({ params }) {
  const id = params?.id ?? "";
  const t = useT();
  const router = useRouter();
  const searchParams = useSearchParams();
  const pathname = usePathname();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const detailTranslator = React.useMemo(() => createTranslatorWithFallback(t), [t]);
  const { data, setData, isLoading, error, isNotFound, loadData } = useDealData(id);
  const [isDirty, setIsDirty] = React.useState(false);
  const {
    scheduleDialogOpen,
    scheduleEditData,
    openSchedule,
    openEdit: openScheduleEdit,
    closeSchedule
  } = useScheduleDialog();
  const formWrapperRef = React.useRef(null);
  const initialTab = React.useMemo(() => resolveLegacyTab(searchParams?.get("tab")), [searchParams]);
  const [activeTab, setActiveTab] = React.useState(initialTab);
  React.useEffect(() => {
    setActiveTab(initialTab);
  }, [initialTab]);
  const currentDealId = data?.deal.id ?? id;
  const { injectionContext, runMutationWithContext } = useDealMutationContext({
    currentDealId,
    fallbackId: id,
    data
  });
  useSetCurrentRecordInjectionContext(
    buildRecordInjectionContext({
      resourceKind: "customers.deal",
      resourceId: data?.deal.id ?? null,
      updatedAt: data?.deal.updatedAt ?? null,
      data,
      path: pathname
    })
  );
  const notesAdapter = React.useMemo(
    () => createCustomerNotesAdapter(detailTranslator, { runMutation: runMutationWithContext }),
    [detailTranslator, runMutationWithContext]
  );
  const { injectedTabs, injectedTabMap } = useDealInjectedTabs({
    injectionContext,
    data,
    setData
  });
  const { searchPeoplePage, fetchPeopleByIds, searchCompaniesPage, fetchCompaniesByIds } = useDealAssociationLookups({
    excludeLinkedDealId: data?.deal.id ?? null
  });
  const {
    plannedActivities,
    activityRefreshKey,
    loadPlannedActivities,
    handleActivityCreated,
    handleMarkDone,
    handleCancelActivity
  } = useDealActivities({ dealId: id, runMutationWithContext });
  React.useEffect(() => {
    void Promise.all([loadData({ cache: true }), loadPlannedActivities({ cache: true })]);
  }, [loadData, loadPlannedActivities]);
  const activityEntities = React.useMemo(
    () => data ? [...data.people, ...data.companies].map((entry) => ({
      id: entry.id,
      label: entry.subtitle ? `${entry.label} \xB7 ${entry.subtitle}` : entry.label,
      kind: entry.kind
    })) : [],
    [data]
  );
  const [selectedActivityEntityId, setSelectedActivityEntityId] = React.useState(null);
  React.useEffect(() => {
    setSelectedActivityEntityId((current) => {
      if (activityEntities.length === 1) return activityEntities[0].id;
      if (current && activityEntities.some((entry) => entry.id === current)) return current;
      return null;
    });
  }, [activityEntities]);
  const selectedActivityEntity = React.useMemo(
    () => activityEntities.find((entry) => entry.id === selectedActivityEntityId) ?? null,
    [activityEntities, selectedActivityEntityId]
  );
  const dealOptions = React.useMemo(
    () => data ? [{ id: data.deal.id, label: data.deal.title || t("customers.deals.detail.untitled", "Untitled deal") }] : [],
    [data, t]
  );
  const entityOptions = React.useMemo(
    () => activityEntities.map(({ id: id2, label }) => ({ id: id2, label })),
    [activityEntities]
  );
  const confirmDiscardIfDirty = React.useCallback(async () => {
    if (!isDirty) return true;
    return confirm({
      title: t("customers.deals.detail.unsavedTitle", "Discard unsaved changes?"),
      description: t(
        "customers.deals.detail.unsavedDescription",
        "You have unsaved edits in this deal. Save them first or continue to discard them."
      ),
      confirmText: t("customers.deals.detail.unsavedConfirm", "Discard changes"),
      cancelText: t("customers.deals.detail.unsavedCancel", "Keep editing"),
      variant: "destructive"
    });
  }, [confirm, isDirty, t]);
  const {
    peopleEditorIds,
    companiesEditorIds,
    peopleSaving,
    companiesSaving,
    handlePeopleAssociationsChange,
    handleCompaniesAssociationsChange,
    loadLinkedPeoplePage,
    loadLinkedCompaniesPage
  } = useDealAssociations({
    currentDealId,
    data,
    setData,
    runMutationWithContext,
    onRefresh: () => {
      void loadData();
    }
  });
  const { isStageSaving, handleStageChange } = useDealPipeline({
    currentDealId,
    data,
    runMutationWithContext,
    confirmDiscardIfDirty,
    onStageChanged: loadData
  });
  const {
    lostDialogOpen,
    wonPopupOpen,
    lostPopupOpen,
    wonStats,
    lostStats,
    openLostDialog,
    closeLostDialog,
    closeWonPopup,
    closeLostPopup,
    handleWon,
    handleLostConfirm
  } = useDealClosure({
    currentDealId,
    dealUpdatedAt: data?.deal.updatedAt ?? null,
    runMutationWithContext,
    confirmDiscardIfDirty,
    onClosed: loadData
  });
  const handleTabChange = React.useCallback(async (tab) => {
    if (!await confirmDiscardIfDirty()) return;
    setActiveTab(tab);
    const nextParams = new URLSearchParams(searchParams?.toString() ?? "");
    nextParams.set("tab", tab);
    router.replace(`/backend/customers/deals/${encodeURIComponent(id)}?${nextParams.toString()}`, { scroll: false });
  }, [confirmDiscardIfDirty, id, router, searchParams]);
  const { isSaving, handleFormSubmit, handleDelete, handleHeaderSave } = useDealFormHandlers({
    data,
    currentDealId,
    loadData,
    runMutationWithContext,
    formWrapperRef,
    confirm
  });
  const handleEditActivity = React.useCallback((activity) => {
    if (activity.entityId && activityEntities.some((entry) => entry.id === activity.entityId)) {
      setSelectedActivityEntityId(activity.entityId);
    }
    const rawActivity = activity;
    openScheduleEdit({
      id: activity.id,
      updatedAt: typeof rawActivity.updatedAt === "string" ? rawActivity.updatedAt : typeof rawActivity.updated_at === "string" ? rawActivity.updated_at : null,
      interactionType: activity.interactionType,
      title: activity.title ?? null,
      body: activity.body ?? null,
      scheduledAt: activity.scheduledAt ?? null,
      occurredAt: activity.occurredAt ?? null,
      durationMinutes: activity.duration ?? null,
      location: activity.location ?? null,
      allDay: activity.allDay ?? null,
      recurrenceRule: activity.recurrenceRule ?? null,
      recurrenceEnd: activity.recurrenceEnd ?? null,
      participants: activity.participants ?? null,
      reminderMinutes: activity.reminderMinutes ?? null,
      visibility: activity.visibility ?? null,
      linkedEntities: activity.linkedEntities ?? null,
      guestPermissions: activity.guestPermissions ?? null,
      ...rawActivity.customValues && typeof rawActivity.customValues === "object" ? { customValues: rawActivity.customValues } : {},
      ...typeof rawActivity.phoneNumber === "string" ? { phoneNumber: rawActivity.phoneNumber } : {}
    });
  }, [activityEntities, openScheduleEdit]);
  const handleViewDashboard = React.useCallback(() => {
    closeWonPopup();
    router.push("/backend");
  }, [closeWonPopup, router]);
  const handleBackToPipeline = React.useCallback(() => {
    closeWonPopup();
    closeLostPopup();
    router.push("/backend/customers/deals/pipeline");
  }, [closeLostPopup, closeWonPopup, router]);
  const handleScheduleLostFollowUp = React.useCallback(() => {
    if (!data || !selectedActivityEntity) return;
    const nextQuarterDate = startOfNextQuarter(/* @__PURE__ */ new Date());
    closeLostPopup();
    openScheduleEdit({
      id: "",
      interactionType: "task",
      title: data.deal.title ? t("customers.deals.detail.lost.followUpTitle", "Revisit {{title}}", { title: data.deal.title }) : t("customers.deals.detail.lost.followUpFallbackTitle", "Revisit closed deal"),
      body: data.deal.lossNotes ?? null,
      scheduledAt: nextQuarterDate.toISOString(),
      durationMinutes: 30,
      location: null,
      allDay: false,
      recurrenceRule: null,
      recurrenceEnd: null,
      participants: null,
      reminderMinutes: 1440,
      visibility: "team",
      linkedEntities: [
        {
          id: data.deal.id,
          type: "deal",
          label: data.deal.title || t("customers.deals.detail.untitled", "Untitled deal")
        }
      ]
    });
  }, [closeLostPopup, data, openScheduleEdit, selectedActivityEntity, t]);
  const currentPipelineName = data ? data.pipelineName ?? wonStats?.pipelineName ?? lostStats?.pipelineName ?? null : wonStats?.pipelineName ?? lostStats?.pipelineName ?? null;
  const formPipelineOptions = React.useMemo(
    () => data?.deal.pipelineId ? [{
      id: data.deal.pipelineId,
      name: currentPipelineName ?? t("customers.deals.detail.pipeline.defaultName", "Current pipeline"),
      isDefault: false
    }] : [],
    [currentPipelineName, data?.deal.pipelineId, t]
  );
  if (isLoading) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(LoadingMessage, { label: t("customers.deals.detail.loading", "Loading deal\u2026") }) }) });
  }
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("customers.deals.detail.error.notFound", "Deal not found."),
        backHref: "/backend/customers/deals",
        backLabel: t("customers.deals.detail.actions.backToList", "Back to deals")
      }
    ) }) });
  }
  if (error || !data) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      ErrorMessage,
      {
        label: error ?? t("customers.deals.detail.error.load", "Failed to load deal."),
        action: /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", size: "sm", children: /* @__PURE__ */ jsx(Link, { href: "/backend/customers/deals", children: t("customers.deals.detail.actions.backToList", "Back to deals") }) })
      }
    ) }) });
  }
  const amountLabel = formatCurrency(data.deal.valueAmount, data.deal.valueCurrency);
  const dealName = data.deal.title || t("customers.deals.detail.untitled", "Untitled deal");
  const zone1Content = /* @__PURE__ */ jsx("div", { ref: formWrapperRef, children: /* @__PURE__ */ jsx(
    DealForm,
    {
      mode: "edit",
      embedded: true,
      trackDirtyWhenEmbedded: true,
      hideFooterActions: true,
      singleColumnGroups: true,
      showAssociationsGroup: false,
      showVersionHistory: false,
      showCancelAction: false,
      injectionSpotId: "crud-form:customers.deal",
      optimisticLockUpdatedAt: data.deal.updatedAt,
      onDirtyChange: setIsDirty,
      initialPipelineOptions: formPipelineOptions,
      initialPipelineStageOptions: data.pipelineStages,
      collapsibleGroups: { pageType: "deal-detail-v3", chevronPosition: "right" },
      sortableGroups: { pageType: "deal-detail-v3" },
      initialValues: {
        ...data.deal,
        valueAmount: typeof data.deal.valueAmount === "string" && data.deal.valueAmount.trim().length ? Number(data.deal.valueAmount) : null,
        personIds: data.linkedPersonIds,
        companyIds: data.linkedCompanyIds,
        customFields: data.customFields,
        ...Object.fromEntries(Object.entries(data.customFields ?? {}).map(([key, value]) => [`cf_${key}`, value]))
      },
      onSubmit: handleFormSubmit,
      onCancel: () => {
        void loadData();
      },
      onDelete: handleDelete
    }
  ) });
  const zone2Content = /* @__PURE__ */ jsx("div", { className: "rounded-[10px] border border-border bg-card px-5 py-5", children: (() => {
    const injected = injectedTabMap.get(activeTab);
    if (injected) return injected();
    if (activeTab === "activities") {
      const activityEntitySelection = activityEntities.length > 1 ? /* @__PURE__ */ jsxs("div", { className: "rounded-[10px] border border-border bg-muted/20 px-5 py-5", children: [
        /* @__PURE__ */ jsx("label", { htmlFor: "deal-activity-entity", className: "text-sm font-semibold text-foreground", children: t("customers.deals.detail.activities.selectEntityLabel", "Choose customer record") }),
        /* @__PURE__ */ jsx("div", { className: "mt-1 text-sm text-muted-foreground", children: t(
          "customers.deals.detail.activities.selectEntityDescription",
          "Pick the person or company that should own new deal activities and follow-ups."
        ) }),
        /* @__PURE__ */ jsxs(
          "select",
          {
            id: "deal-activity-entity",
            "aria-label": t("customers.deals.detail.activities.selectEntityLabel", "Choose customer record"),
            className: "mt-4 h-9 w-full rounded border border-muted-foreground/40 bg-background px-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",
            value: selectedActivityEntityId ?? "",
            onChange: (event) => setSelectedActivityEntityId(event.target.value || null),
            children: [
              /* @__PURE__ */ jsx("option", { value: "", children: t("customers.deals.detail.activities.selectEntityPlaceholder", "Select a person or company") }),
              activityEntities.map((entry) => /* @__PURE__ */ jsx("option", { value: entry.id, children: entry.label }, entry.id))
            ]
          }
        )
      ] }) : null;
      return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
        activityEntities.length > 1 ? activityEntitySelection : null,
        activityEntities.length === 0 ? /* @__PURE__ */ jsxs("div", { className: "rounded-[10px] border border-border bg-muted/20 px-5 py-5", children: [
          /* @__PURE__ */ jsx("div", { className: "text-sm font-semibold text-foreground", children: t("customers.deals.detail.activities.linkEntityTitle", "Link a person or company first") }),
          /* @__PURE__ */ jsx("div", { className: "mt-1 text-sm text-muted-foreground", children: t("customers.deals.detail.activities.linkEntityDescription", "Activities on a deal still need a customer record for timeline ownership.") }),
          /* @__PURE__ */ jsxs("div", { className: "mt-4 flex gap-2", children: [
            /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => handleTabChange("people"), children: t("customers.deals.detail.tabs.people", "People") }),
            /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => handleTabChange("companies"), children: t("customers.deals.detail.tabs.companies", "Companies") })
          ] })
        ] }) : selectedActivityEntity ? /* @__PURE__ */ jsx(
          InlineActivityComposer,
          {
            entityType: selectedActivityEntity.kind,
            entityId: selectedActivityEntity.id,
            dealId: data.deal.id,
            onActivityCreated: () => {
              void handleActivityCreated();
            },
            runGuardedMutation: runMutationWithContext,
            onScheduleRequested: openSchedule
          }
        ) : /* @__PURE__ */ jsx(
          EmptyState,
          {
            size: "sm",
            icon: /* @__PURE__ */ jsx(UserSearch, { className: "h-8 w-8", "aria-hidden": "true" }),
            title: t("customers.deals.detail.activities.selectEntityRequiredTitle", "Choose a person or company to continue"),
            description: t(
              "customers.deals.detail.activities.selectEntityRequiredDescription",
              "Select the customer record that should receive new deal activities before logging or scheduling anything."
            )
          }
        ),
        /* @__PURE__ */ jsx(
          PlannedActivitiesSection,
          {
            activities: plannedActivities,
            onComplete: (interactionId) => {
              void handleMarkDone(interactionId);
            },
            onSchedule: selectedActivityEntity ? openSchedule : void 0,
            onEdit: handleEditActivity,
            onCancel: (interactionId) => {
              void handleCancelActivity(interactionId);
            }
          }
        ),
        selectedActivityEntity ? /* @__PURE__ */ jsx(
          ActivitiesSection,
          {
            entityId: selectedActivityEntity.id,
            entityName: selectedActivityEntity.label,
            dealId: data.deal.id,
            dealOptions,
            entityOptions,
            defaultEntityId: selectedActivityEntity.id,
            addActionLabel: t("customers.deals.detail.activitiesAdd", "Log activity"),
            emptyState: {
              title: t("customers.deals.detail.activitiesEmptyTitle", "No activities yet"),
              actionLabel: t("customers.deals.detail.activitiesEmptyAction", "Log activity")
            },
            runGuardedMutation: runMutationWithContext,
            onDataRefresh: () => {
              void handleActivityCreated();
            },
            refreshKey: activityRefreshKey,
            onEditActivity: handleEditActivity
          }
        ) : null
      ] });
    }
    if (activeTab === "people") {
      return /* @__PURE__ */ jsx(
        DealLinkedEntitiesTab,
        {
          entityLabel: t("customers.deals.detail.tabs.peopleSingular", "Person"),
          entityLabelPlural: t("customers.deals.detail.tabs.people", "People"),
          manageLabel: t("customers.deals.detail.peopleEditorTitle", "Manage linked people"),
          searchPlaceholder: t("customers.deals.detail.peopleSearch", "Search linked people\u2026"),
          linkedItems: data.people,
          linkedCount: data.counts.people,
          selectedIds: peopleEditorIds,
          disabled: peopleSaving || isSaving,
          savePending: peopleSaving,
          hrefBuilder: (personId) => `/backend/customers/people-v2/${encodeURIComponent(personId)}`,
          onSaveSelection: (next) => handlePeopleAssociationsChange(next),
          loadLinkedPage: loadLinkedPeoplePage,
          searchEntities: searchPeoplePage,
          fetchEntitiesByIds: fetchPeopleByIds,
          icon: /* @__PURE__ */ jsx(Users, { className: "size-4" })
        }
      );
    }
    if (activeTab === "companies") {
      return /* @__PURE__ */ jsx(
        DealLinkedEntitiesTab,
        {
          entityLabel: t("customers.deals.detail.tabs.companySingular", "Company"),
          entityLabelPlural: t("customers.deals.detail.tabs.companies", "Companies"),
          manageLabel: t("customers.deals.detail.companiesEditorTitle", "Manage linked companies"),
          searchPlaceholder: t("customers.deals.detail.companiesSearch", "Search linked companies\u2026"),
          linkedItems: data.companies,
          linkedCount: data.counts.companies,
          selectedIds: companiesEditorIds,
          disabled: companiesSaving || isSaving,
          savePending: companiesSaving,
          hrefBuilder: (companyId) => `/backend/customers/companies-v2/${encodeURIComponent(companyId)}`,
          onSaveSelection: (next) => handleCompaniesAssociationsChange(next),
          loadLinkedPage: loadLinkedCompaniesPage,
          searchEntities: searchCompaniesPage,
          fetchEntitiesByIds: fetchCompaniesByIds,
          icon: /* @__PURE__ */ jsx(Building2, { className: "size-4" })
        }
      );
    }
    if (activeTab === "notes") {
      return /* @__PURE__ */ jsx(
        NotesSection,
        {
          entityId: null,
          dealId: data.deal.id,
          dealOptions,
          entityOptions,
          emptyLabel: t("customers.deals.detail.notesEmpty", "No notes yet."),
          viewerUserId: data.viewer?.userId ?? null,
          viewerName: data.viewer?.name ?? null,
          viewerEmail: data.viewer?.email ?? null,
          addActionLabel: t("customers.deals.detail.notesAdd", "Add note"),
          emptyState: {
            title: t("customers.deals.detail.notesEmptyTitle", "Keep everyone in the loop"),
            actionLabel: t("customers.deals.detail.notesEmptyAction", "Add a note")
          },
          translator: detailTranslator,
          dataAdapter: notesAdapter,
          renderIcon: renderDictionaryIcon,
          renderColor: renderDictionaryColor,
          iconSuggestions: ICON_SUGGESTIONS,
          readMarkdownPreference: readMarkdownPreferenceCookie,
          writeMarkdownPreference: writeMarkdownPreferenceCookie
        }
      );
    }
    if (activeTab === "files") {
      return /* @__PURE__ */ jsx(
        AttachmentsSection,
        {
          entityId: E.customers.customer_deal,
          recordId: data.deal.id,
          title: t("customers.deals.detail.tabs.files", "Files"),
          description: t("customers.deals.detail.files.subtitle", "Upload and manage files linked to this deal.")
        }
      );
    }
    if (activeTab === "changelog") {
      return /* @__PURE__ */ jsx(ChangelogTab, { entityId: data.deal.id, entityType: "deal" });
    }
    return null;
  })() });
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsxs(PageBody, { children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
      /* @__PURE__ */ jsx(InjectionSpot, { spotId: "detail:customers.deal:header", context: injectionContext, data }),
      /* @__PURE__ */ jsx(
        DealDetailHeader,
        {
          deal: data.deal,
          owner: data.owner,
          people: data.people,
          companies: data.companies,
          pipelineName: currentPipelineName,
          stageOptions: data.pipelineStages,
          currentStageId: data.deal.pipelineStageId,
          onStageChange: handleStageChange,
          isStageSaving,
          onSave: handleHeaderSave,
          onDelete: handleDelete,
          isDirty,
          isSaving
        }
      ),
      /* @__PURE__ */ jsx(InjectionSpot, { spotId: "detail:customers.deal:status-badges", context: injectionContext, data }),
      /* @__PURE__ */ jsx(
        PipelineStepper,
        {
          stages: data.pipelineStages,
          transitions: data.stageTransitions,
          currentStageId: data.deal.pipelineStageId,
          pipelineName: currentPipelineName,
          closureOutcome: data.deal.closureOutcome,
          footer: data.deal.closureOutcome ? null : /* @__PURE__ */ jsx(
            DealClosureActionBar,
            {
              embedded: true,
              closureOutcome: data.deal.closureOutcome,
              onWon: () => {
                void handleWon();
              },
              onLost: openLostDialog
            }
          )
        }
      ),
      /* @__PURE__ */ jsx(
        DealDetailTabs,
        {
          activeTab,
          onTabChange: handleTabChange,
          injectedTabs: injectedTabs.map((tab) => ({ id: tab.id, label: tab.label })),
          peopleCount: data.counts.people,
          companiesCount: data.counts.companies,
          children: /* @__PURE__ */ jsx(
            CollapsibleZoneLayout,
            {
              pageType: "deal-detail-v3",
              entityName: dealName,
              isDirty,
              zone1DefaultWidth: "540px",
              zone1: zone1Content,
              zone2: zone2Content
            }
          )
        }
      ),
      /* @__PURE__ */ jsx(InjectionSpot, { spotId: "detail:customers.deal:footer", context: injectionContext, data })
    ] }),
    ConfirmDialogElement,
    selectedActivityEntity ? /* @__PURE__ */ jsx(
      ScheduleActivityDialog,
      {
        open: scheduleDialogOpen,
        onClose: closeSchedule,
        entityId: selectedActivityEntity.id,
        dealId: data.deal.id,
        entityType: selectedActivityEntity.kind,
        entityName: selectedActivityEntity.label,
        companyName: selectedActivityEntity.kind === "company" ? selectedActivityEntity.label : data.companies[0]?.label ?? null,
        onActivityCreated: () => {
          void handleActivityCreated();
        },
        editData: scheduleEditData
      }
    ) : null,
    /* @__PURE__ */ jsx(
      ConfirmDealLostDialog,
      {
        open: lostDialogOpen,
        onClose: closeLostDialog,
        dealTitle: data.deal.title || t("customers.deals.detail.untitled", "Untitled deal"),
        dealValue: amountLabel,
        companyName: data.companies[0]?.label ?? null,
        onConfirm: handleLostConfirm
      }
    ),
    /* @__PURE__ */ jsx(
      DealWonPopup,
      {
        open: wonPopupOpen,
        onClose: closeWonPopup,
        dealTitle: data.deal.title || t("customers.deals.detail.untitled", "Untitled deal"),
        stats: wonStats,
        onViewDashboard: handleViewDashboard,
        onBackToPipeline: handleBackToPipeline
      }
    ),
    /* @__PURE__ */ jsx(
      DealLostSummaryDialog,
      {
        open: lostPopupOpen,
        onClose: closeLostPopup,
        dealTitle: data.deal.title || t("customers.deals.detail.untitled", "Untitled deal"),
        lossNotes: data.deal.lossNotes,
        stats: lostStats,
        onBackToPipeline: handleBackToPipeline,
        onScheduleFollowUp: selectedActivityEntity ? handleScheduleLostFollowUp : void 0
      }
    )
  ] }) });
}
export {
  DealDetailPage as default
};
//# sourceMappingURL=page.js.map
