"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 { Separator } from "@open-mercato/ui/primitives/separator";
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 { RecordNotFoundState, ErrorMessage } from "@open-mercato/ui/backend/detail";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { DetailFieldsSection } from "@open-mercato/ui/backend/detail";
import {
  ActivitiesSection
} from "../../../../components/detail/ActivitiesSection.js";
import {
  NotesSection
} 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 { CustomDataSection } from "../../../../components/detail/CustomDataSection.js";
import { CompanyHighlights } from "../../../../components/detail/CompanyHighlights.js";
import { normalizeCustomFieldSubmitValue } from "../../../../components/detail/customFieldUtils.js";
import { InlineDictionaryEditor, renderMultilineMarkdownDisplay } from "../../../../components/detail/InlineEditors.js";
import { formatTemplate } from "../../../../components/detail/utils.js";
import { coerceDisplayName } from "../../../../lib/displayName.js";
import { createTranslatorWithFallback } from "@open-mercato/shared/lib/i18n/translate";
import {
  CompanyPeopleSection
} from "../../../../components/detail/CompanyPeopleSection.js";
import { AnnualRevenueField } from "../../../../components/detail/AnnualRevenueField.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 CustomerCompanyDetailPage({ 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 === "people" || 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 currentCompanyId = data?.company?.id ?? null;
  const companyDisplayName = coerceDisplayName(data?.company?.displayName);
  const companyName = companyDisplayName.trim().length ? companyDisplayName : t("customers.companies.list.deleteFallbackName", "this company");
  const translateCompanyDetail = React.useCallback(
    (key, fallback, params2) => {
      const mappedKey = key.startsWith("customers.people.detail.") ? key.replace("customers.people.detail.", "customers.companies.detail.") : key;
      const adjustedFallback = key.startsWith("customers.people.detail.") && fallback ? fallback.replace(/\bPerson\b/g, "Company").replace(/\bperson\b/g, "company").replace(/\bPeople\b/g, "Companies").replace(/\bpeople\b/g, "companies") : fallback;
      const translated = t(mappedKey, params2);
      if (translated !== mappedKey || mappedKey === key) return translated;
      const fallbackValue = t(key, params2);
      if (fallbackValue !== key) return fallbackValue;
      if (!adjustedFallback) return mappedKey;
      return formatTemplate(adjustedFallback, params2);
    },
    [t]
  );
  const sectionLoaderLabel = activeTab === "activities" ? t("customers.companies.detail.activities.loading", "Loading activities\u2026") : activeTab === "deals" ? t("customers.companies.detail.deals.loading", "Loading deals\u2026") : activeTab === "people" ? t("customers.companies.detail.people.loading", "Loading people\u2026") : t("customers.companies.detail.sectionLoading", "Loading\u2026");
  const mutationContextId = React.useMemo(
    () => currentCompanyId ? `customer-company:${currentCompanyId}` : `customer-company:${id ?? "pending"}`,
    [currentCompanyId, id]
  );
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const injectionContext = React.useMemo(
    () => ({
      formId: mutationContextId,
      companyId: currentCompanyId,
      resourceKind: "customers.company",
      resourceId: currentCompanyId ?? (id ?? void 0),
      data,
      retryLastMutation
    }),
    [currentCompanyId, data, id, mutationContextId, retryLastMutation]
  );
  const runMutationWithContext = React.useCallback(
    async (operation, mutationPayload) => {
      return runMutation({
        operation,
        mutationPayload,
        context: injectionContext
      });
    },
    [injectionContext, runMutation]
  );
  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.companies.detail.inline.emailInvalid", "Enter a valid email address.");
    },
    phone: (value) => {
      if (!value) return null;
      return value.length >= 3 ? null : t("customers.companies.detail.inline.phoneInvalid", "Phone number is too short.");
    },
    displayName: (value) => {
      const trimmed = value.trim();
      return trimmed.length ? null : t("customers.companies.form.displayName.error", "Company name is required.");
    },
    website: (value) => {
      if (!value) return null;
      try {
        const url = new URL(value.trim());
        return url.protocol === "http:" || url.protocol === "https:" ? null : t("customers.companies.detail.inline.websiteInvalid", "Use a valid http(s) address.");
      } catch {
        return t("customers.companies.detail.inline.websiteInvalid", "Use a valid http(s) address.");
      }
    },
    annualRevenue: (value) => {
      if (!value) return null;
      const normalized = value.replace(/[, ]+/g, "");
      const amount = Number(normalized);
      if (Number.isNaN(amount) || amount < 0) {
        return t("customers.companies.detail.inline.annualRevenueInvalid", "Enter a non-negative number.");
      }
      return null;
    }
  }), [t]);
  const { widgets: injectedTabWidgets } = useInjectionWidgets("customers.company.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.companies.detail.tabs.notes", "Notes") },
      { id: "activities", label: t("customers.companies.detail.tabs.activities", "Activities") },
      { id: "deals", label: t("customers.companies.detail.tabs.deals", "Deals") },
      { id: "people", label: t("customers.companies.detail.tabs.people", "People") },
      { id: "addresses", label: t("customers.companies.detail.tabs.addresses", "Addresses") },
      { id: "tasks", label: t("customers.companies.detail.tabs.tasks", "Tasks") },
      ...injectedTabs.map((tab) => ({ id: tab.id, label: tab.label }))
    ],
    [injectedTabs, t]
  );
  React.useEffect(() => {
    if (!id) {
      setIsNotFound(true);
      setIsLoading(false);
      return;
    }
    const companyId2 = id;
    let cancelled = false;
    async function load() {
      setIsLoading(true);
      setError(null);
      try {
        const search = new URLSearchParams();
        search.append("include", "todos");
        search.append("include", "people");
        const payload = await readApiResultOrThrow(
          `/api/customers/companies/${encodeURIComponent(companyId2)}?${search.toString()}`,
          void 0,
          { errorMessage: t("customers.companies.detail.error.load", "Failed to load company.") }
        );
        if (cancelled) return;
        setData(payload);
      } catch (err) {
        if (cancelled) return;
        if (err.status === 404) {
          setIsNotFound(true);
        } else {
          const message = err instanceof Error ? err.message : t("customers.companies.detail.error.load", "Failed to load company.");
          setError(message);
        }
        setData(null);
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    }
    load().catch(() => {
    });
    return () => {
      cancelled = true;
    };
  }, [id, t]);
  const saveCompany = React.useCallback(
    async (patch, apply) => {
      if (!data) return;
      const payload = { id: data.company.id, ...patch };
      const result = await runMutationWithContext(
        () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(data?.company?.updatedAt),
          () => apiCallOrThrow(
            "/api/customers/companies",
            {
              method: "PUT",
              headers: { "content-type": "application/json" },
              body: JSON.stringify(payload)
            },
            { errorMessage: t("customers.companies.detail.inline.error", "Unable to update company.") }
          )
        ),
        payload
      );
      const nextUpdatedAt = result?.result?.updatedAt ?? null;
      setData((prev) => {
        if (!prev) return prev;
        const applied = apply(prev);
        return nextUpdatedAt ? { ...applied, company: { ...applied.company, updatedAt: nextUpdatedAt } } : applied;
      });
    },
    [data, runMutationWithContext, t]
  );
  const updateDisplayName = React.useCallback(
    async (next) => {
      const send = typeof next === "string" ? next : "";
      await saveCompany(
        { displayName: send },
        (prev) => ({
          ...prev,
          company: {
            ...prev.company,
            displayName: next && next.length ? next : prev.company.displayName
          }
        })
      );
    },
    [saveCompany]
  );
  const updateCompanyField = React.useCallback(
    async (field, next) => {
      const send = typeof next === "string" ? next : "";
      await saveCompany(
        { [field]: send },
        (prev) => ({
          ...prev,
          company: {
            ...prev.company,
            [field]: next && next.length ? next : null
          }
        })
      );
    },
    [saveCompany]
  );
  const updateProfileField = React.useCallback(
    async (field, next) => {
      const send = typeof next === "string" ? next : "";
      await saveCompany(
        { [field]: send },
        (prev) => {
          if (!prev.profile) return prev;
          const nextValue = next && next.length ? next : null;
          return {
            ...prev,
            profile: {
              ...prev.profile,
              [field]: nextValue
            }
          };
        }
      );
    },
    [saveCompany]
  );
  const submitCustomFields = React.useCallback(
    async (prefixedValues, { showFlash = true } = {}) => {
      if (!data) throw new Error(t("customers.companies.detail.inline.error", "Unable to update company."));
      const customPayload = collectCustomFieldValues(prefixedValues, {
        transform: (value) => normalizeCustomFieldSubmitValue(value)
      });
      const normalized = {};
      for (const [fieldId, value] of Object.entries(customPayload)) {
        normalized[`cf_${fieldId}`] = value;
      }
      if (!Object.keys(customPayload).length) {
        if (showFlash) flash(t("ui.forms.flash.saveSuccess", "Saved successfully."), "success");
        return;
      }
      const payload = {
        id: data.company.id,
        customFields: customPayload
      };
      let customFieldsUpdatedAt = null;
      try {
        const result = await runMutationWithContext(
          () => withScopedApiRequestHeaders(
            buildOptimisticLockHeader(data?.company?.updatedAt),
            () => apiCallOrThrow(
              "/api/customers/companies",
              {
                method: "PUT",
                headers: { "content-type": "application/json" },
                body: JSON.stringify(payload)
              },
              { errorMessage: t("customers.companies.detail.inline.error", "Unable to update company.") }
            )
          ),
          payload
        );
        customFieldsUpdatedAt = result?.result?.updatedAt ?? null;
      } catch (err) {
        const { message: helperMessage, fieldErrors } = mapCrudServerErrorToFormErrors(err);
        const message = helperMessage ?? t("customers.companies.detail.inline.error", "Unable to update company.");
        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(message);
        if (mappedErrors && Object.keys(mappedErrors).length) error2.fieldErrors = mappedErrors;
        throw error2;
      }
      setData((prev) => {
        if (!prev) return prev;
        return {
          ...prev,
          company: customFieldsUpdatedAt ? { ...prev.company, updatedAt: customFieldsUpdatedAt } : prev.company,
          customFields: {
            ...prev.customFields,
            ...normalized
          }
        };
      });
      if (showFlash) flash(t("ui.forms.flash.saveSuccess", "Saved successfully."), "success");
    },
    [data, runMutationWithContext, t]
  );
  const handleAnnualRevenueChange = React.useCallback(
    async ({ amount, currency }) => {
      await saveCompany(
        { annualRevenue: amount ?? null },
        (prev) => {
          if (!prev.profile) return prev;
          return {
            ...prev,
            profile: {
              ...prev.profile,
              annualRevenue: amount === null ? null : String(amount)
            }
          };
        }
      );
      await submitCustomFields(
        { cf_annual_revenue_currency: currency ?? null },
        { showFlash: false }
      );
      flash(t("ui.forms.flash.saveSuccess", "Saved successfully."), "success");
    },
    [saveCompany, submitCustomFields, t]
  );
  const handleDelete = React.useCallback(async () => {
    if (!currentCompanyId) return;
    const confirmed = await confirm({
      title: t("customers.companies.list.deleteConfirm", void 0, { name: companyName }),
      variant: "destructive"
    });
    if (!confirmed) return;
    setIsDeleting(true);
    try {
      await runMutationWithContext(
        () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(data?.company?.updatedAt),
          () => apiCallOrThrow(
            `/api/customers/companies?id=${encodeURIComponent(currentCompanyId)}`,
            {
              method: "DELETE",
              headers: { "content-type": "application/json" }
            },
            { errorMessage: t("customers.companies.list.deleteError", "Failed to delete company.") }
          )
        ),
        { id: currentCompanyId }
      );
      flash(t("customers.companies.list.deleteSuccess", "Company deleted."), "success");
      router.push("/backend/customers/companies");
    } catch (err) {
      const message = err instanceof Error ? err.message : t("customers.companies.list.deleteError", "Failed to delete company.");
      flash(message, "error");
    } finally {
      setIsDeleting(false);
    }
  }, [companyName, confirm, currentCompanyId, router, runMutationWithContext, t]);
  const handleTagsChange = React.useCallback((nextTags) => {
    setData((prev) => prev ? { ...prev, tags: nextTags } : prev);
  }, []);
  const handleCustomFieldsSubmit = React.useCallback(
    async (values) => {
      await submitCustomFields(values);
    },
    [submitCustomFields]
  );
  const handleNotesLoadingChange = React.useCallback(() => {
  }, []);
  const handleActivitiesLoadingChange = React.useCallback(() => {
  }, []);
  const handleDealsLoadingChange = React.useCallback(() => {
  }, []);
  const handlePeopleLoadingChange = React.useCallback(() => {
  }, []);
  const handleAddressesLoadingChange = React.useCallback(() => {
  }, []);
  const handleTasksLoadingChange = React.useCallback(() => {
  }, []);
  const dealsScope = React.useMemo(
    () => currentCompanyId ? { kind: "company", entityId: currentCompanyId } : null,
    [currentCompanyId]
  );
  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.companies.detail.loading", "Loading company\u2026") })
    ] }) }) });
  }
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("customers.companies.detail.error.notFound", "Company not found."),
        backHref: "/backend/customers/companies",
        backLabel: t("customers.companies.detail.actions.backToList", "Back to companies")
      }
    ) }) });
  }
  if (error || !data?.company?.id) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      ErrorMessage,
      {
        label: error ?? t("customers.companies.detail.error.notFound", "Company not found."),
        action: /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", size: "sm", children: /* @__PURE__ */ jsx(Link, { href: "/backend/customers/companies", children: t("customers.companies.detail.actions.backToList", "Back to companies") }) })
      }
    ) }) });
  }
  const { company, profile } = data;
  const companyId = company.id;
  const annualRevenueCurrency = typeof data.customFields?.annual_revenue_currency === "string" ? data.customFields.annual_revenue_currency : null;
  const detailFields = [
    {
      key: "displayName",
      kind: "text",
      label: t("customers.companies.detail.fields.displayName", "Display name"),
      value: company.displayName,
      placeholder: t("customers.companies.form.displayName.placeholder", "Enter company name"),
      emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
      validator: validators.displayName,
      onSave: updateDisplayName
    },
    {
      key: "legalName",
      kind: "text",
      label: t("customers.companies.detail.fields.legalName", "Legal name"),
      value: profile?.legalName ?? null,
      placeholder: t("customers.companies.detail.fields.legalNamePlaceholder", "Add legal name"),
      emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
      onSave: (value) => updateProfileField("legalName", value)
    },
    {
      key: "brandName",
      kind: "text",
      label: t("customers.companies.detail.fields.brandName", "Brand name"),
      value: profile?.brandName ?? null,
      placeholder: t("customers.companies.detail.fields.brandNamePlaceholder", "Add brand name"),
      emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
      onSave: (value) => updateProfileField("brandName", value)
    },
    {
      key: "description",
      kind: "multiline",
      label: t("customers.companies.detail.fields.description", "Description"),
      value: company.description ?? null,
      placeholder: t("customers.companies.detail.fields.descriptionPlaceholder", "Describe the company"),
      emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
      gridClassName: "sm:col-span-2 xl:col-span-3",
      renderDisplay: renderMultilineMarkdownDisplay,
      onSave: async (next) => {
        const send = typeof next === "string" ? next : "";
        await saveCompany(
          { description: send },
          (prev) => ({
            ...prev,
            company: { ...prev.company, description: next && next.length ? next : null }
          })
        );
      }
    },
    {
      key: "lifecycleStage",
      kind: "custom",
      label: t("customers.companies.detail.fields.lifecycleStage", "Lifecycle stage"),
      emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
      render: () => /* @__PURE__ */ jsx(
        InlineDictionaryEditor,
        {
          label: t("customers.companies.detail.fields.lifecycleStage", "Lifecycle stage"),
          value: company.lifecycleStage ?? null,
          emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
          kind: "lifecycle-stages",
          onSave: (next) => updateCompanyField("lifecycleStage", next),
          selectClassName: "h-9 w-full rounded border px-3 text-sm",
          variant: "muted",
          activateOnClick: true
        }
      )
    },
    {
      key: "source",
      kind: "custom",
      label: t("customers.companies.detail.fields.source", "Source"),
      emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
      render: () => /* @__PURE__ */ jsx(
        InlineDictionaryEditor,
        {
          label: t("customers.companies.detail.fields.source", "Source"),
          value: company.source ?? null,
          emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
          kind: "sources",
          onSave: (next) => updateCompanyField("source", next),
          selectClassName: "h-9 w-full rounded border px-3 text-sm",
          variant: "muted",
          activateOnClick: true
        }
      )
    },
    {
      key: "domain",
      kind: "text",
      label: t("customers.companies.detail.fields.domain", "Domain"),
      value: profile?.domain ?? null,
      placeholder: t("customers.companies.detail.fields.domainPlaceholder", "example.com"),
      emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
      onSave: (value) => updateProfileField("domain", value)
    },
    {
      key: "industry",
      kind: "custom",
      label: t("customers.companies.detail.fields.industry", "Industry"),
      emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
      render: () => /* @__PURE__ */ jsx(
        InlineDictionaryEditor,
        {
          label: t("customers.companies.detail.fields.industry", "Industry"),
          value: profile?.industry ?? null,
          emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
          kind: "industries",
          onSave: (next) => updateProfileField("industry", next),
          selectClassName: "h-9 w-full rounded border px-3 text-sm",
          variant: "muted",
          activateOnClick: true
        }
      )
    },
    {
      key: "sizeBucket",
      kind: "text",
      label: t("customers.companies.detail.fields.sizeBucket", "Company size"),
      value: profile?.sizeBucket ?? null,
      placeholder: t("customers.companies.detail.fields.sizeBucketPlaceholder", "Add size bucket"),
      emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
      onSave: (value) => updateProfileField("sizeBucket", value)
    },
    {
      key: "annualRevenue",
      kind: "custom",
      label: t("customers.companies.detail.fields.annualRevenue", "Annual revenue"),
      emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
      render: () => /* @__PURE__ */ jsx(
        AnnualRevenueField,
        {
          label: t("customers.companies.detail.fields.annualRevenue", "Annual revenue"),
          amount: profile?.annualRevenue ?? null,
          currency: annualRevenueCurrency,
          emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
          validator: validators.annualRevenue,
          onSave: handleAnnualRevenueChange
        }
      )
    },
    {
      key: "websiteUrl",
      kind: "text",
      label: t("customers.companies.detail.fields.website", "Website"),
      value: profile?.websiteUrl ?? null,
      placeholder: t("customers.companies.detail.fields.websitePlaceholder", "https://example.com"),
      emptyLabel: t("customers.companies.detail.noValue", "Not provided"),
      inputType: "url",
      validator: validators.website,
      onSave: (value) => updateProfileField("websiteUrl", value)
    }
  ];
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "space-y-8", children: [
      /* @__PURE__ */ jsx(
        CompanyHighlights,
        {
          company,
          profile: profile ?? null,
          validators,
          onDisplayNameSave: updateDisplayName,
          utilityActions: /* @__PURE__ */ jsx(
            SendObjectMessageDialog,
            {
              object: {
                entityModule: "customers",
                entityType: "company",
                entityId: companyId,
                previewData: {
                  title: company.displayName,
                  subtitle: company.primaryEmail ?? void 0,
                  metadata: {
                    [t("customers.companies.detail.highlights.primaryPhone")]: company.primaryPhone ?? "-",
                    [t("customers.companies.detail.fields.industry")]: profile?.industry ?? "-"
                  }
                }
              },
              viewHref: `/backend/customers/companies/${companyId}`
            }
          ),
          onPrimaryEmailSave: (value) => updateCompanyField("primaryEmail", value),
          onPrimaryPhoneSave: (value) => updateCompanyField("primaryPhone", value),
          onStatusSave: (value) => updateCompanyField("status", value),
          onNextInteractionSave: async (payload) => {
            await saveCompany(
              {
                nextInteraction: payload ? {
                  at: payload.at,
                  name: payload.name ?? void 0,
                  refId: payload.refId ?? void 0,
                  icon: payload.icon ?? void 0,
                  color: payload.color ?? void 0
                } : null
              },
              (prev) => ({
                ...prev,
                company: {
                  ...prev.company,
                  nextInteractionAt: payload?.at ?? null,
                  nextInteractionName: payload?.name ?? null,
                  nextInteractionRefId: payload?.refId ?? null,
                  nextInteractionIcon: payload?.icon ?? null,
                  nextInteractionColor: payload?.color ?? null
                }
              })
            );
          },
          onDelete: handleDelete,
          isDeleting
        }
      ),
      /* @__PURE__ */ jsx(
        DetailTabsLayout,
        {
          className: "space-y-6",
          tabs,
          activeTab,
          onTabChange: setActiveTab,
          sectionAction,
          onSectionAction: handleSectionAction,
          navAriaLabel: t("customers.companies.detail.tabs.label", "Company detail sections"),
          navClassName: "gap-4",
          children: (() => {
            const injected = injectedTabMap.get(activeTab);
            if (injected) return injected();
            if (activeTab === "notes") {
              return /* @__PURE__ */ jsx(
                NotesSection,
                {
                  entityId: companyId,
                  emptyLabel: t("customers.companies.detail.empty.comments", "No notes yet."),
                  viewerUserId: data.viewer?.userId ?? null,
                  viewerName: data.viewer?.name ?? null,
                  viewerEmail: data.viewer?.email ?? null,
                  addActionLabel: t("customers.companies.detail.notes.addLabel", "Add note"),
                  emptyState: {
                    title: t("customers.companies.detail.emptyState.notes.title", "Keep everyone in the loop"),
                    actionLabel: t("customers.companies.detail.emptyState.notes.action", "Create a note")
                  },
                  onActionChange: handleSectionActionChange,
                  translator: translateCompanyDetail,
                  onLoadingChange: handleNotesLoadingChange,
                  dataAdapter: notesAdapter,
                  renderIcon: renderDictionaryIcon,
                  renderColor: renderDictionaryColor,
                  iconSuggestions: ICON_SUGGESTIONS,
                  readMarkdownPreference: readMarkdownPreferenceCookie,
                  writeMarkdownPreference: writeMarkdownPreferenceCookie
                }
              );
            }
            if (activeTab === "activities") {
              return /* @__PURE__ */ jsx(
                ActivitiesSection,
                {
                  entityId: companyId,
                  runGuardedMutation: runMutationWithContext,
                  addActionLabel: t("customers.companies.detail.activities.add", "Log activity"),
                  emptyState: {
                    title: t("customers.companies.detail.emptyState.activities.title", "No activities logged yet"),
                    actionLabel: t("customers.companies.detail.emptyState.activities.action", "Log activity")
                  },
                  onActionChange: handleSectionActionChange,
                  onLoadingChange: handleActivitiesLoadingChange
                }
              );
            }
            if (activeTab === "deals") {
              return /* @__PURE__ */ jsx(
                DealsSection,
                {
                  scope: dealsScope,
                  emptyLabel: t("customers.companies.detail.empty.deals", "No deals linked to this company."),
                  addActionLabel: t("customers.companies.detail.actions.addDeal", "Add deal"),
                  emptyState: {
                    title: t("customers.companies.detail.emptyState.deals.title", "No deals yet"),
                    actionLabel: t("customers.companies.detail.emptyState.deals.action", "Create a deal")
                  },
                  onActionChange: handleSectionActionChange,
                  onLoadingChange: handleDealsLoadingChange,
                  translator: detailTranslator,
                  runGuardedMutation: runMutationWithContext
                }
              );
            }
            if (activeTab === "people") {
              return /* @__PURE__ */ jsx(
                CompanyPeopleSection,
                {
                  companyId,
                  initialPeople: data.people ?? [],
                  addActionLabel: t("customers.companies.detail.people.add", "Add person"),
                  emptyLabel: t("customers.companies.detail.people.empty", "No people linked to this company yet."),
                  emptyState: {
                    title: t("customers.companies.detail.emptyState.people.title", "Build the account team"),
                    actionLabel: t("customers.companies.detail.emptyState.people.action", "Create person")
                  },
                  onActionChange: handleSectionActionChange,
                  onLoadingChange: handlePeopleLoadingChange,
                  translator: detailTranslator,
                  runGuardedMutation: runMutationWithContext,
                  onPeopleChange: (next) => {
                    setData((prev) => prev ? { ...prev, people: next } : prev);
                  }
                }
              );
            }
            if (activeTab === "addresses") {
              return /* @__PURE__ */ jsx(
                AddressesSection,
                {
                  entityId: companyId,
                  emptyLabel: t("customers.companies.detail.empty.addresses", "No addresses recorded."),
                  addActionLabel: t("customers.companies.detail.addresses.add", "Add address"),
                  emptyState: {
                    title: t("customers.companies.detail.emptyState.addresses.title", "No addresses yet"),
                    actionLabel: t("customers.companies.detail.emptyState.addresses.action", "Add address")
                  },
                  onActionChange: handleSectionActionChange,
                  onLoadingChange: handleAddressesLoadingChange,
                  translator: detailTranslator
                }
              );
            }
            if (activeTab === "tasks") {
              return /* @__PURE__ */ jsx(
                TasksSection,
                {
                  entityId: companyId,
                  initialTasks: data.todos,
                  runGuardedMutation: runMutationWithContext,
                  emptyLabel: t("customers.companies.detail.empty.todos", "No tasks linked to this company."),
                  addActionLabel: t("customers.companies.detail.tasks.add", "Add task"),
                  emptyState: {
                    title: t("customers.companies.detail.emptyState.tasks.title", "Plan what happens next"),
                    actionLabel: t("customers.companies.detail.emptyState.tasks.action", "Create task")
                  },
                  onActionChange: handleSectionActionChange,
                  onLoadingChange: handleTasksLoadingChange,
                  translator: translateCompanyDetail,
                  entityName: companyName,
                  dialogContextKey: "customers.companies.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.companies.detail.sections.details", "Company details") }),
          /* @__PURE__ */ jsx(DetailFieldsSection, { fields: detailFields }),
          /* @__PURE__ */ jsx(
            InjectionSpot,
            {
              spotId: "customers.company.detail:details",
              context: injectionContext,
              data,
              onDataChange: (next) => setData(next)
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          CustomDataSection,
          {
            entityIds: [E.customers.customer_entity, E.customers.customer_company_profile],
            values: data.customFields ?? {},
            onSubmit: handleCustomFieldsSubmit,
            title: t("customers.companies.detail.sections.customFields", "Custom fields")
          }
        ),
        /* @__PURE__ */ jsx(
          TagsSection,
          {
            entityId: companyId,
            tags: data.tags,
            onChange: handleTagsChange,
            isSubmitting: false
          }
        )
      ] }),
      /* @__PURE__ */ jsx(Separator, { className: "my-4" })
    ] }) }),
    ConfirmDialogElement
  ] });
}
export {
  CustomerCompanyDetailPage as default
};
//# sourceMappingURL=page.js.map
