"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { Button } from "@open-mercato/ui/primitives/button";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { extractCustomFieldEntries } from "@open-mercato/shared/lib/crud/custom-fields-client";
import { updateCrud, deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { switchTeamMemberSchedule } from "@open-mercato/core/modules/staff/lib/scheduleSwitch";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { createTranslatorWithFallback } from "@open-mercato/shared/lib/i18n/translate";
import { AvailabilityRulesEditor } from "@open-mercato/core/modules/planner/components/AvailabilityRulesEditor";
import { buildMemberScheduleItems } from "@open-mercato/core/modules/staff/lib/memberSchedule";
import { TeamMemberForm, buildTeamMemberPayload } from "@open-mercato/core/modules/staff/components/TeamMemberForm";
import { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from "@open-mercato/ui/backend/injection/recordContext";
import { NotesSection } from "@open-mercato/ui/backend/detail";
import { ActivitiesSection } from "@open-mercato/ui/backend/detail";
import { AddressesSection as SharedAddressesSection } from "@open-mercato/ui/backend/detail";
import { ErrorMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { renderDictionaryColor, renderDictionaryIcon, ICON_SUGGESTIONS } from "@open-mercato/core/modules/dictionaries/components/dictionaryAppearance";
import { createStaffNotesAdapter } from "@open-mercato/core/modules/staff/components/detail/notesAdapter";
import { createStaffActivitiesAdapter } from "@open-mercato/core/modules/staff/components/detail/activitiesAdapter";
import { createStaffAddressAdapter, createStaffAddressTypesAdapter } from "@open-mercato/core/modules/staff/components/detail/addressesAdapter";
import { MarkdownContent } from "@open-mercato/ui/backend/markdown/MarkdownContent";
import {
  createStaffDictionaryEntry,
  loadStaffDictionary
} from "@open-mercato/core/modules/staff/components/detail/dictionaries";
import { JobHistorySection } from "@open-mercato/core/modules/staff/components/detail/JobHistorySection";
import { Plus } from "lucide-react";
import { TranslationDrawerAction } from "@open-mercato/core/modules/translations/components/TranslationDrawerAction";
import { SendObjectMessageDialog } from "@open-mercato/ui/backend/messages";
const MARKDOWN_CLASSNAME = "text-sm text-muted-foreground break-words [&>*]:mb-2 [&>*:last-child]:mb-0 [&_ul]:ml-4 [&_ul]:list-disc [&_ol]:ml-4 [&_ol]:list-decimal [&_code]:rounded [&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5 [&_pre]:rounded-md [&_pre]:bg-muted [&_pre]:p-3 [&_pre]:text-xs";
function StaffTeamMemberDetailPage({ params }) {
  const memberId = params?.id;
  const t = useT();
  const detailTranslator = React.useMemo(() => createTranslatorWithFallback(t), [t]);
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [initialValues, setInitialValues] = React.useState(null);
  const [memberRecord, setMemberRecord] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const [availabilityRuleSetId, setAvailabilityRuleSetId] = React.useState(null);
  const [activePanel, setActivePanel] = React.useState("details");
  const [activeTab, setActiveTab] = React.useState("notes");
  const [sectionAction, setSectionAction] = React.useState(null);
  const [activityDictionaryId, setActivityDictionaryId] = React.useState(null);
  const [activityTypeEntries, setActivityTypeEntries] = React.useState([]);
  const flashShownRef = React.useRef(false);
  const notesAdapter = React.useMemo(() => createStaffNotesAdapter(detailTranslator), [detailTranslator]);
  const activitiesAdapter = React.useMemo(() => createStaffActivitiesAdapter(detailTranslator), [detailTranslator]);
  const addressesAdapter = React.useMemo(() => createStaffAddressAdapter(detailTranslator), [detailTranslator]);
  const addressTypesAdapter = React.useMemo(() => createStaffAddressTypesAdapter(detailTranslator), [detailTranslator]);
  const activityTypeLabels = React.useMemo(() => ({
    placeholder: t("staff.teamMembers.detail.activities.dictionary.placeholder", "Select an activity type"),
    addLabel: t("staff.teamMembers.detail.activities.dictionary.add", "Add type"),
    addPrompt: t("staff.teamMembers.detail.activities.dictionary.prompt", "Name the type"),
    dialogTitle: t("staff.teamMembers.detail.activities.dictionary.dialogTitle", "Add activity type"),
    valueLabel: t("staff.teamMembers.detail.activities.dictionary.valueLabel", "Name"),
    valuePlaceholder: t("staff.teamMembers.detail.activities.dictionary.valuePlaceholder", "Name"),
    labelLabel: t("staff.teamMembers.detail.activities.dictionary.labelLabel", "Label"),
    labelPlaceholder: t("staff.teamMembers.detail.activities.dictionary.labelPlaceholder", "Display name shown in UI"),
    emptyError: t("staff.teamMembers.detail.activities.dictionary.emptyError", "Please enter a name"),
    cancelLabel: t("staff.teamMembers.detail.activities.dictionary.cancel", "Cancel"),
    saveLabel: t("staff.teamMembers.detail.activities.dictionary.save", "Save"),
    saveShortcutHint: t("staff.teamMembers.detail.activities.dictionary.saveShortcut", "\u2318/Ctrl + Enter"),
    errorLoad: t("staff.teamMembers.detail.activities.dictionary.errorLoad", "Failed to load options"),
    errorSave: t("staff.teamMembers.detail.activities.dictionary.errorSave", "Failed to save option"),
    loadingLabel: t("staff.teamMembers.detail.activities.dictionary.loading", "Loading\u2026"),
    manageTitle: t("staff.teamMembers.detail.activities.dictionary.manage", "Manage dictionary")
  }), [t]);
  const loadActivityOptions = React.useCallback(async () => {
    const { dictionary, entries } = await loadStaffDictionary("activityTypes");
    setActivityDictionaryId(dictionary?.id ?? null);
    setActivityTypeEntries(entries);
    return entries;
  }, []);
  const createActivityOption = React.useCallback(
    async (input) => {
      const entry = await createStaffDictionaryEntry("activityTypes", input);
      if (!entry) {
        throw new Error(t("staff.teamMembers.detail.activities.dictionary.errorSave", "Failed to save option"));
      }
      return entry;
    },
    [t]
  );
  React.useEffect(() => {
    loadActivityOptions().catch(() => {
    });
  }, [loadActivityOptions]);
  const activityTypeMap = React.useMemo(
    () => new Map(activityTypeEntries.map((entry) => [entry.value, entry])),
    [activityTypeEntries]
  );
  const resolveActivityPresentation = React.useCallback(
    (activity) => {
      const entry = activityTypeMap.get(activity.activityType);
      return {
        label: entry?.label ?? activity.activityType,
        icon: entry?.icon ?? activity.appearanceIcon ?? null,
        color: entry?.color ?? activity.appearanceColor ?? null
      };
    },
    [activityTypeMap]
  );
  const manageActivityHref = React.useMemo(() => {
    if (!activityDictionaryId) return "/backend/config/dictionaries";
    return `/backend/config/dictionaries?dictionaryId=${encodeURIComponent(activityDictionaryId)}`;
  }, [activityDictionaryId]);
  const appearanceLabels = React.useMemo(() => ({
    colorLabel: t("staff.teamMembers.detail.activities.appearance.colorLabel", "Color"),
    colorHelp: t("staff.teamMembers.detail.activities.appearance.colorHelp", "Pick a highlight color for this entry."),
    colorClearLabel: t("staff.teamMembers.detail.activities.appearance.colorClear", "Remove color"),
    iconLabel: t("staff.teamMembers.detail.activities.appearance.iconLabel", "Icon or emoji"),
    iconPlaceholder: t("staff.teamMembers.detail.activities.appearance.iconPlaceholder", "Type an emoji or pick one of the suggestions."),
    iconPickerTriggerLabel: t("staff.teamMembers.detail.activities.appearance.iconBrowse", "Browse icons and emojis"),
    iconSearchPlaceholder: t("staff.teamMembers.detail.activities.appearance.iconSearchPlaceholder", "Search icons or emojis\u2026"),
    iconSearchEmptyLabel: t("staff.teamMembers.detail.activities.appearance.iconSearchEmpty", "No icons match your search."),
    iconSuggestionsLabel: t("staff.teamMembers.detail.activities.appearance.iconSuggestions", "Suggestions"),
    iconClearLabel: t("staff.teamMembers.detail.activities.appearance.iconClear", "Remove icon"),
    previewEmptyLabel: t("staff.teamMembers.detail.activities.appearance.previewEmpty", "No appearance selected")
  }), [t]);
  const renderCustomFields = React.useCallback((activity) => {
    const entries = Array.isArray(activity.customFields) ? activity.customFields : [];
    if (!entries.length) return null;
    const emptyLabel = t("staff.teamMembers.detail.activities.customFields.empty", "Not provided");
    return /* @__PURE__ */ jsx("div", { className: "grid gap-3 sm:grid-cols-2", children: entries.map((entry, index) => {
      const label = entry.label ?? entry.key;
      const value = entry.value;
      const hasValue = !(value == null || value === "" || Array.isArray(value) && value.length === 0);
      const content = hasValue ? Array.isArray(value) ? value.map((item) => String(item)).join(", ") : String(value) : emptyLabel;
      return /* @__PURE__ */ jsxs(
        "div",
        {
          className: "rounded-md border border-border/70 bg-muted/30 px-3 py-2",
          children: [
            /* @__PURE__ */ jsx("div", { className: "text-xs font-medium text-muted-foreground", children: label }),
            /* @__PURE__ */ jsx("div", { className: "mt-1 text-sm text-foreground", children: content })
          ]
        },
        `activity-${activity.id ?? "row"}-custom-${index}`
      );
    }) });
  }, [t]);
  React.useEffect(() => {
    if (!memberId) return;
    const memberIdValue = memberId;
    let cancelled = false;
    async function loadMember() {
      if (!cancelled) {
        setError(null);
        setIsNotFound(false);
      }
      try {
        const params2 = new URLSearchParams({ page: "1", pageSize: "1", ids: memberIdValue });
        const payload = await readApiResultOrThrow(
          `/api/staff/team-members?${params2.toString()}`,
          void 0,
          { errorMessage: t("staff.teamMembers.form.errors.load", "Failed to load team member.") }
        );
        const record = Array.isArray(payload.items) ? payload.items[0] : null;
        if (!record) {
          if (!cancelled) setIsNotFound(true);
          return;
        }
        const customFields = extractCustomFieldEntries(record);
        if (!cancelled) {
          const resolvedTeamId = record.teamId ?? record.team_id ?? null;
          const normalizedRoleIds = normalizeStringList(resolvePreferredArray(record.roleIds, record.role_ids));
          setInitialValues({
            id: record.id,
            teamId: resolvedTeamId,
            userId: record.userId ?? record.user_id ?? null,
            displayName: record.displayName ?? record.display_name ?? "",
            description: record.description ?? "",
            roleIds: normalizedRoleIds,
            tags: normalizeStringList(record.tags),
            isActive: record.isActive ?? record.is_active ?? true,
            updatedAt: typeof record.updatedAt === "string" ? record.updatedAt : typeof record.updated_at === "string" ? record.updated_at : null,
            ...customFields
          });
          setMemberRecord(record);
          setAvailabilityRuleSetId(
            typeof record.availabilityRuleSetId === "string" ? record.availabilityRuleSetId : typeof record.availability_rule_set_id === "string" ? record.availability_rule_set_id : null
          );
        }
      } catch (err) {
        if (!cancelled) {
          if (err.status === 404) {
            setIsNotFound(true);
          } else {
            const message = err instanceof Error ? err.message : t("staff.teamMembers.form.errors.load", "Failed to load team member.");
            setError(message);
          }
        }
      }
    }
    void loadMember();
    return () => {
      cancelled = true;
    };
  }, [memberId, t]);
  React.useEffect(() => {
    if (!searchParams) return;
    const created = searchParams.get("created") === "1";
    if (created && !flashShownRef.current) {
      flashShownRef.current = true;
      flash(t("staff.teamMembers.flash.createdAvailability", "Saved. You can now set availability."), "success");
      const nextParams = new URLSearchParams(searchParams.toString());
      nextParams.delete("created");
      const nextQuery = nextParams.toString();
      const nextPath = memberId ? `/backend/staff/team-members/${encodeURIComponent(memberId)}${nextQuery ? `?${nextQuery}` : ""}` : `/backend/staff/team-members${nextQuery ? `?${nextQuery}` : ""}`;
      router.replace(nextPath);
    }
  }, [memberId, router, searchParams, t]);
  const handleSubmit = React.useCallback(async (values) => {
    if (!memberId) return;
    const payload = buildTeamMemberPayload(values, { id: memberId });
    await updateCrud("staff/team-members", payload, {
      errorMessage: t("staff.teamMembers.form.errors.update", "Failed to update team member.")
    });
    flash(t("staff.teamMembers.form.flash.updated", "Team member updated."), "success");
    router.push("/backend/staff/team-members");
  }, [memberId, router, t]);
  const handleDelete = React.useCallback(async () => {
    if (!memberId) return;
    await deleteCrud("staff/team-members", memberId, {
      errorMessage: t("staff.teamMembers.form.errors.delete", "Failed to delete team member.")
    });
    flash(t("staff.teamMembers.form.flash.deleted", "Team member deleted."), "success");
    router.push("/backend/staff/team-members");
  }, [memberId, router, t]);
  const handleRulesetChange = React.useCallback(async (nextId) => {
    if (!memberId) return;
    const { updatedAt: nextUpdatedAt } = await switchTeamMemberSchedule({
      memberId,
      nextRuleSetId: nextId,
      expectedUpdatedAt: initialValues?.updatedAt,
      t
    });
    if (nextUpdatedAt) {
      setInitialValues((prev) => prev ? { ...prev, updatedAt: nextUpdatedAt } : prev);
    }
    setAvailabilityRuleSetId(nextId);
    flash(t("staff.teamMembers.availability.ruleset.updateSuccess", "Schedule updated."), "success");
  }, [initialValues?.updatedAt, memberId, t]);
  const panelTabs = React.useMemo(() => [
    { id: "details", label: t("staff.teamMembers.detail.tabs.details", "Details") },
    { id: "availability", label: t("staff.teamMembers.detail.tabs.availability", "Availability") },
    { id: "jobHistory", label: t("staff.teamMembers.detail.tabs.jobHistory", "Job history") }
  ], [t]);
  const tabs = React.useMemo(() => [
    { id: "notes", label: t("staff.teamMembers.detail.tabs.notes", "Notes") },
    { id: "activities", label: t("staff.teamMembers.detail.tabs.activities", "Activities") },
    { id: "addresses", label: t("staff.teamMembers.detail.tabs.addresses", "Addresses") }
  ], [t]);
  const resolvedInitialValues = initialValues ?? {
    roleIds: [],
    isActive: true
  };
  const displayName = memberRecord?.displayName ?? memberRecord?.display_name ?? resolvedInitialValues.displayName ?? "";
  const teamLabel = memberRecord?.team?.name ?? t("staff.teamMembers.detail.team.unassigned", "Unassigned team");
  const roleLabels = Array.isArray(memberRecord?.roleNames) && memberRecord?.roleNames.length ? memberRecord?.roleNames : [t("staff.teamMembers.detail.roles.unassigned", "No roles assigned")];
  const userEmail = memberRecord?.user?.email ?? null;
  useSetCurrentRecordInjectionContext(
    buildRecordInjectionContext({
      resourceKind: "staff.teamMember",
      resourceId: memberId || null,
      updatedAt: initialValues?.updatedAt ?? null,
      data: initialValues,
      path: pathname
    })
  );
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("staff.teamMembers.form.errors.notFound", "Team member not found."),
        backHref: "/backend/staff/team-members",
        backLabel: t("staff.teamMembers.actions.backToList", "Back to team members")
      }
    ) }) });
  }
  if (error && !initialValues) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(ErrorMessage, { label: error }) }) });
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ jsxs(
          Link,
          {
            href: "/backend/staff/team-members",
            className: "inline-flex items-center text-sm text-muted-foreground hover:text-foreground",
            children: [
              /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: "mr-1 text-base", children: "\u2190" }),
              /* @__PURE__ */ jsx("span", { className: "sr-only", children: t("staff.teamMembers.detail.back", "Back to team members") })
            ]
          }
        ),
        /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
          /* @__PURE__ */ jsx("h1", { className: "text-2xl font-semibold text-foreground", children: displayName || t("staff.teamMembers.detail.untitled", "Unnamed team member") }),
          /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("staff.teamMembers.detail.subtitle", "Team member profile and activity") })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
        memberId ? /* @__PURE__ */ jsx(
          SendObjectMessageDialog,
          {
            object: {
              entityModule: "staff",
              entityType: "team_member",
              entityId: memberId,
              previewData: {
                title: displayName,
                metadata: {
                  [t("staff.teamMembers.detail.fields.team")]: teamLabel,
                  [t("staff.teamMembers.detail.fields.user")]: userEmail ?? t("staff.teamMembers.detail.fields.userEmpty", "No user linked"),
                  [t("staff.teamMembers.detail.fields.roles")]: roleLabels.join(", ")
                }
              }
            },
            viewHref: `/backend/staff/team-members/${memberId}`
          }
        ) : null,
        /* @__PURE__ */ jsx(
          TranslationDrawerAction,
          {
            config: memberId ? {
              entityType: "staff:staff_team_member",
              recordId: memberId,
              baseValues: memberRecord ?? void 0
            } : null
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "border-b", children: /* @__PURE__ */ jsx(
      "nav",
      {
        className: "flex flex-wrap items-center gap-5 text-sm",
        "aria-label": t("staff.teamMembers.detail.tabs.label", "Team member sections"),
        children: panelTabs.map((tab) => /* @__PURE__ */ jsx(
          "button",
          {
            type: "button",
            role: "tab",
            "aria-selected": activePanel === tab.id,
            onClick: () => setActivePanel(tab.id),
            className: `relative -mb-px border-b-2 px-0 py-2 text-sm font-medium transition-colors ${activePanel === tab.id ? "border-accent-indigo text-foreground" : "border-transparent text-muted-foreground hover:text-foreground"}`,
            children: tab.label
          },
          tab.id
        ))
      }
    ) }),
    activePanel === "details" ? /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsxs("div", { className: "grid gap-6 lg:grid-cols-[minmax(0,2fr),minmax(0,1.1fr)]", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
          /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
            /* @__PURE__ */ jsx("h2", { className: "mb-4 text-sm font-semibold uppercase text-muted-foreground", children: t("staff.teamMembers.detail.highlights", "Highlights") }),
            /* @__PURE__ */ jsxs("div", { className: "grid gap-4 sm:grid-cols-2", children: [
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx("p", { className: "text-xs font-medium uppercase text-muted-foreground", children: t("staff.teamMembers.detail.fields.team", "Team") }),
                /* @__PURE__ */ jsx("p", { className: "text-base text-foreground", children: teamLabel })
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx("p", { className: "text-xs font-medium uppercase text-muted-foreground", children: t("staff.teamMembers.detail.fields.roles", "Roles") }),
                /* @__PURE__ */ jsx("p", { className: "text-base text-foreground", children: roleLabels.join(", ") })
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx("p", { className: "text-xs font-medium uppercase text-muted-foreground", children: t("staff.teamMembers.detail.fields.user", "User") }),
                /* @__PURE__ */ jsx("p", { className: "text-base text-foreground", children: userEmail ?? t("staff.teamMembers.detail.fields.userEmpty", "No user linked") })
              ] }),
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx("p", { className: "text-xs font-medium uppercase text-muted-foreground", children: t("staff.teamMembers.detail.fields.status", "Status") }),
                /* @__PURE__ */ jsx("p", { className: "text-base text-foreground", children: memberRecord?.isActive ?? memberRecord?.is_active ? t("staff.teamMembers.detail.status.active", "Active") : t("staff.teamMembers.detail.status.inactive", "Inactive") })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-3", children: [
              /* @__PURE__ */ jsx("div", { className: "flex gap-2", children: tabs.map((tab) => /* @__PURE__ */ jsx(
                "button",
                {
                  type: "button",
                  onClick: () => setActiveTab(tab.id),
                  className: `relative -mb-px border-b-2 px-0 py-1 text-sm font-medium transition-colors ${activeTab === tab.id ? "border-accent-indigo text-foreground" : "border-transparent text-muted-foreground hover:text-foreground"}`,
                  children: tab.label
                },
                tab.id
              )) }),
              sectionAction ? /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  size: "sm",
                  disabled: sectionAction.disabled,
                  onClick: () => sectionAction.onClick(),
                  children: [
                    sectionAction.icon ?? (activeTab === "addresses" ? /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }) : null),
                    sectionAction.label
                  ]
                }
              ) : null
            ] }),
            activeTab === "notes" ? /* @__PURE__ */ jsx(
              NotesSection,
              {
                entityId: memberId ?? null,
                emptyLabel: t("staff.teamMembers.detail.notes.empty", "No notes yet."),
                viewerUserId: null,
                viewerName: null,
                viewerEmail: null,
                addActionLabel: t("staff.teamMembers.detail.notes.add", "Add note"),
                emptyState: {
                  title: t("staff.teamMembers.detail.notes.emptyTitle", "Keep everyone in the loop"),
                  actionLabel: t("staff.teamMembers.detail.notes.emptyAction", "Add a note")
                },
                onActionChange: setSectionAction,
                translator: detailTranslator,
                labelPrefix: "staff.teamMembers.detail.notes",
                inlineLabelPrefix: "staff.teamMembers.detail.inline",
                dataAdapter: notesAdapter,
                renderIcon: renderDictionaryIcon,
                renderColor: renderDictionaryColor,
                iconSuggestions: ICON_SUGGESTIONS
              }
            ) : null,
            activeTab === "activities" ? /* @__PURE__ */ jsx(
              ActivitiesSection,
              {
                entityId: memberId ?? null,
                addActionLabel: t("staff.teamMembers.detail.activities.add", "Log activity"),
                emptyState: {
                  title: t("staff.teamMembers.detail.activities.emptyTitle", "No activities yet"),
                  actionLabel: t("staff.teamMembers.detail.activities.emptyAction", "Add an activity")
                },
                onActionChange: setSectionAction,
                dataAdapter: activitiesAdapter,
                activityTypeLabels,
                loadActivityOptions,
                createActivityOption,
                resolveActivityPresentation,
                renderCustomFields,
                labelPrefix: "staff.teamMembers.detail.activities",
                renderIcon: renderDictionaryIcon,
                renderColor: renderDictionaryColor,
                appearanceLabels,
                manageHref: manageActivityHref,
                customFieldEntityIds: ["staff:staff_team_member_activity"]
              }
            ) : null,
            activeTab === "addresses" ? /* @__PURE__ */ jsx(
              SharedAddressesSection,
              {
                entityId: memberId ?? null,
                emptyLabel: t("staff.teamMembers.detail.addresses.empty", "No addresses yet."),
                addActionLabel: t("staff.teamMembers.detail.addresses.add", "Add address"),
                emptyState: {
                  title: t("staff.teamMembers.detail.addresses.emptyTitle", "No addresses yet"),
                  actionLabel: t("staff.teamMembers.detail.addresses.emptyAction", "Add an address")
                },
                onActionChange: setSectionAction,
                dataAdapter: addressesAdapter,
                addressTypesAdapter,
                labelPrefix: "staff.teamMembers.detail.addresses"
              }
            ) : null
          ] })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "space-y-4", children: /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
          /* @__PURE__ */ jsx("h2", { className: "mb-4 text-sm font-semibold uppercase text-muted-foreground", children: t("staff.teamMembers.detail.details", "Member details") }),
          /* @__PURE__ */ jsx("div", { className: "space-y-2", children: memberRecord?.description ? /* @__PURE__ */ jsx(MarkdownContent, { body: memberRecord.description, format: "markdown", className: MARKDOWN_CLASSNAME }) : /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("staff.teamMembers.detail.descriptionEmpty", "No description provided.") }) })
        ] }) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
        /* @__PURE__ */ jsx("h2", { className: "mb-4 text-sm font-semibold uppercase text-muted-foreground", children: t("staff.teamMembers.detail.formTitle", "Member settings") }),
        /* @__PURE__ */ jsx(
          TeamMemberForm,
          {
            embedded: true,
            title: t("staff.teamMembers.form.editTitle", "Edit team member"),
            backHref: "/backend/staff/team-members",
            cancelHref: "/backend/staff/team-members",
            initialValues: resolvedInitialValues,
            onSubmit: handleSubmit,
            onDelete: handleDelete,
            isLoading: !initialValues,
            loadingMessage: t("staff.teamMembers.form.loading", "Loading team member...")
          }
        )
      ] })
    ] }) : activePanel === "availability" ? /* @__PURE__ */ jsx(
      AvailabilityRulesEditor,
      {
        subjectType: "member",
        subjectId: memberId ?? "",
        labelPrefix: "staff.teamMembers",
        mode: "availability",
        rulesetId: availabilityRuleSetId,
        onRulesetChange: handleRulesetChange,
        allowRuleSetDelete: true,
        buildScheduleItems: ({ availabilityRules, translate: translateLabel }) => buildMemberScheduleItems({ availabilityRules, translate: translateLabel })
      }
    ) : /* @__PURE__ */ jsx("div", { className: "rounded-lg border bg-card p-4", children: /* @__PURE__ */ jsx(JobHistorySection, { memberId: memberId ?? null }) })
  ] }) }) });
}
function normalizeStringList(value) {
  if (!Array.isArray(value)) return [];
  return value.map((entry) => typeof entry === "string" ? entry.trim() : "").filter((entry) => entry.length > 0);
}
function resolvePreferredArray(primary, fallback) {
  if (Array.isArray(primary) && primary.length) return primary;
  if (Array.isArray(fallback) && fallback.length) return fallback;
  return Array.isArray(primary) ? primary : Array.isArray(fallback) ? fallback : void 0;
}
export {
  StaffTeamMemberDetailPage as default
};
//# sourceMappingURL=page.js.map
