"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Users, Phone, Check, Mail, Calendar, X, StickyNote } from "lucide-react";
import { cn } from "@open-mercato/shared/lib/utils";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { validatePhoneNumber } from "@open-mercato/shared/lib/phone";
import { apiCallOrThrow, readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader, extractOptimisticLockConflict } from "@open-mercato/ui/backend/utils/optimisticLock";
import { mapCrudServerErrorToFormErrors } from "@open-mercato/ui/backend/utils/serverErrors";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { Alert, AlertDescription, AlertTitle } from "@open-mercato/ui/primitives/alert";
import { Button } from "@open-mercato/ui/primitives/button";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { Dialog, DialogContent, DialogTitle } from "@open-mercato/ui/primitives/dialog";
import { useDialogKeyHandler } from "@open-mercato/ui/hooks/useDialogKeyHandler";
import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
import { PhoneNumberField, SwitchableMarkdownInput } from "@open-mercato/ui/backend/inputs";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import {
  useScheduleFormState,
  FIELD_VISIBILITY,
  getFieldLabel,
  DateTimeFields,
  ParticipantsField,
  LocationField,
  FooterFields,
  LinkedEntitiesField
} from "./schedule/index.js";
const TYPE_TABS = [
  { type: "meeting", icon: Users, labelKey: "customers.schedule.types.meeting", fallback: "Meeting" },
  { type: "call", icon: Phone, labelKey: "customers.schedule.types.call", fallback: "Call" },
  { type: "task", icon: Check, labelKey: "customers.schedule.types.task", fallback: "Task" },
  { type: "email", icon: Mail, labelKey: "customers.schedule.types.email", fallback: "Email" },
  { type: "note", icon: StickyNote, labelKey: "customers.schedule.types.note", fallback: "Note" }
];
const TYPE_CHROME = {
  meeting: {
    titleKey: "customers.schedule.meeting.title",
    titleFallback: "New meeting",
    subtitleKey: "customers.schedule.meeting.subtitle",
    subtitleFallback: "Block time on the calendar with attendees",
    saveKey: "customers.schedule.meeting.save",
    saveFallback: "Save activity",
    saveIcon: Calendar
  },
  call: {
    titleKey: "customers.schedule.call.title",
    titleFallback: "Log call",
    subtitleKey: "customers.schedule.call.subtitle",
    subtitleFallback: "Log a call you just had or schedule one",
    saveKey: "customers.schedule.call.save",
    saveFallback: "Log call",
    saveIcon: Phone
  },
  task: {
    titleKey: "customers.schedule.task.title",
    titleFallback: "New task",
    subtitleKey: "customers.schedule.task.subtitle",
    subtitleFallback: "Capture something to follow up on",
    saveKey: "customers.schedule.task.save",
    saveFallback: "Save task",
    saveIcon: Check
  },
  email: {
    titleKey: "customers.schedule.email.title",
    titleFallback: "Compose email",
    subtitleKey: "customers.schedule.email.subtitle",
    subtitleFallback: "Compose and send a tracked email",
    saveKey: "customers.schedule.email.save",
    saveFallback: "Send email",
    saveIcon: Mail
  },
  note: {
    titleKey: "customers.schedule.note.title",
    titleFallback: "Add note",
    subtitleKey: "customers.schedule.note.subtitle",
    subtitleFallback: "Write down a note about this interaction",
    saveKey: "customers.schedule.note.save",
    saveFallback: "Save note",
    saveIcon: StickyNote
  }
};
const CALL_DIRECTIONS = [
  { key: "outbound", labelKey: "customers.schedule.call.direction.outbound", labelFallback: "Outbound", dot: "bg-status-info-icon" },
  { key: "inbound", labelKey: "customers.schedule.call.direction.inbound", labelFallback: "Inbound", dot: "bg-status-success-icon" }
];
const CALL_OUTCOMES = [
  { key: "connected", labelKey: "customers.schedule.call.outcome.connected", labelFallback: "Connected", dot: "bg-status-success-icon" },
  { key: "voicemail", labelKey: "customers.schedule.call.outcome.voicemail", labelFallback: "Voicemail", dot: "bg-status-warning-icon" },
  { key: "noanswer", labelKey: "customers.schedule.call.outcome.noAnswer", labelFallback: "No answer", dot: "bg-muted-foreground" },
  { key: "busy", labelKey: "customers.schedule.call.outcome.busy", labelFallback: "Busy", dot: "bg-status-warning-icon" },
  { key: "badnumber", labelKey: "customers.schedule.call.outcome.badNumber", labelFallback: "Bad number", dot: "bg-status-error-icon" }
];
const TASK_PRIORITIES = [
  { key: "low", labelKey: "customers.schedule.task.priority.low", labelFallback: "Low", dot: "bg-muted-foreground" },
  { key: "medium", labelKey: "customers.schedule.task.priority.medium", labelFallback: "Medium", dot: "bg-status-info-icon" },
  { key: "high", labelKey: "customers.schedule.task.priority.high", labelFallback: "High", dot: "bg-status-warning-icon" },
  { key: "urgent", labelKey: "customers.schedule.task.priority.urgent", labelFallback: "Urgent", dot: "bg-status-error-icon" }
];
function ScheduleActivityDialog({
  open,
  onClose,
  entityId,
  dealId = null,
  entityName,
  companyName,
  entityType,
  onActivityCreated,
  editData
}) {
  const t = useT();
  const state = useScheduleFormState({ open, editData: editData ?? null });
  const visibleFields = FIELD_VISIBILITY[state.activityType];
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const isEditing = Boolean(editData?.id);
  const chrome = TYPE_CHROME[state.activityType];
  const SaveIcon = chrome.saveIcon;
  const [callDirection, setCallDirection] = React.useState("outbound");
  const [callOutcome, setCallOutcome] = React.useState(null);
  const [callPhoneNumber, setCallPhoneNumber] = React.useState("");
  const [callPhoneError, setCallPhoneError] = React.useState(null);
  const [taskPriority, setTaskPriority] = React.useState("medium");
  const callPhoneInvalidMessage = React.useMemo(
    () => t(
      "customers.activities.errors.phoneInvalid",
      "Enter a valid phone number with country code (e.g. +1 212 555 1234)"
    ),
    [t]
  );
  const translateErrorMessage = React.useCallback(
    (message, fallback) => {
      const key = typeof message === "string" ? message.trim() : "";
      return key ? t(key, key) : fallback;
    },
    [t]
  );
  React.useEffect(() => {
    if (!open) return;
    const raw = editData;
    const cv = raw?.customValues && typeof raw.customValues === "object" ? raw.customValues : null;
    setCallDirection(typeof cv?.callDirection === "string" && cv.callDirection === "inbound" ? "inbound" : "outbound");
    setCallOutcome(typeof cv?.callOutcome === "string" ? cv.callOutcome : null);
    const seededPhone = typeof raw?.phoneNumber === "string" && raw.phoneNumber.trim().length > 0 ? raw.phoneNumber : typeof cv?.callPhoneNumber === "string" ? cv.callPhoneNumber : "";
    setCallPhoneNumber(seededPhone);
    setCallPhoneError(null);
    setTaskPriority(typeof cv?.taskPriority === "string" ? cv.taskPriority : "medium");
  }, [open, editData]);
  React.useEffect(() => {
    if (!open || isEditing) return;
    setCallDirection("outbound");
    setCallOutcome(null);
    setCallPhoneNumber("");
    setCallPhoneError(null);
    setTaskPriority("medium");
  }, [state.activityType, open, isEditing]);
  const handleCallPhoneChange = React.useCallback((next) => {
    setCallPhoneNumber(next ?? "");
    setCallPhoneError(null);
  }, []);
  const formSnapshot = React.useMemo(() => JSON.stringify({
    activityType: state.activityType,
    title: state.title,
    date: state.date,
    startTime: state.startTime,
    duration: state.duration,
    allDay: state.allDay,
    description: state.description,
    location: state.location,
    reminderMinutes: state.reminderMinutes,
    visibility: state.visibility,
    participants: state.participants,
    linkedEntities: state.linkedEntities,
    recurrenceEnabled: state.recurrenceEnabled,
    recurrenceDays: state.recurrenceDays,
    recurrenceEndType: state.recurrenceEndType,
    recurrenceCount: state.recurrenceCount,
    recurrenceEndDate: state.recurrenceEndDate,
    guestPermissions: state.guestPermissions
  }), [
    state.activityType,
    state.title,
    state.date,
    state.startTime,
    state.duration,
    state.allDay,
    state.description,
    state.location,
    state.reminderMinutes,
    state.visibility,
    state.participants,
    state.linkedEntities,
    state.recurrenceEnabled,
    state.recurrenceDays,
    state.recurrenceEndType,
    state.recurrenceCount,
    state.recurrenceEndDate,
    state.guestPermissions
  ]);
  const initialSnapshotRef = React.useRef(null);
  const snapshotOpenKeyRef = React.useRef(null);
  const snapshotSettleCountRef = React.useRef(0);
  const openKey = open ? `${editData?.id ?? "new"}` : null;
  React.useEffect(() => {
    if (!open) {
      initialSnapshotRef.current = null;
      snapshotOpenKeyRef.current = null;
      snapshotSettleCountRef.current = 0;
      return;
    }
    if (snapshotOpenKeyRef.current !== openKey) {
      snapshotOpenKeyRef.current = openKey;
      snapshotSettleCountRef.current = 0;
      initialSnapshotRef.current = null;
    }
    if (snapshotSettleCountRef.current < 2) {
      initialSnapshotRef.current = formSnapshot;
      snapshotSettleCountRef.current += 1;
    }
  }, [open, openKey, formSnapshot]);
  const isDirty = React.useCallback(() => {
    if (initialSnapshotRef.current == null) return false;
    return initialSnapshotRef.current !== formSnapshot;
  }, [formSnapshot]);
  const guardedClose = React.useCallback(async () => {
    if (!isDirty()) {
      onClose();
      return;
    }
    const ok = await confirm({
      title: t("customers.schedule.discardConfirm.title", "Discard unsaved changes?"),
      description: t(
        "customers.schedule.discardConfirm.description",
        "You have unsaved edits in this activity. Save them first or continue to discard them."
      ),
      confirmText: t("customers.schedule.discardConfirm.confirm", "Discard"),
      cancelText: t("customers.schedule.discardConfirm.cancel", "Keep editing"),
      variant: "destructive"
    });
    if (ok) onClose();
  }, [confirm, isDirty, onClose, t]);
  const mutationContextId = React.useMemo(
    () => `customer-activity:${entityType}:${entityId}`,
    [entityId, entityType]
  );
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const mutationContext = React.useMemo(
    () => ({
      formId: mutationContextId,
      resourceKind: entityType === "company" ? "customers.company" : entityType === "person" ? "customers.person" : "customers.deal",
      resourceId: entityId,
      entityType,
      retryLastMutation
    }),
    [entityId, entityType, mutationContextId, retryLastMutation]
  );
  const runGuardedMutation = React.useCallback(
    async (operation, mutationPayload) => runMutation({
      operation,
      mutationPayload,
      context: mutationContext
    }),
    [mutationContext, runMutation]
  );
  React.useEffect(() => {
    if (!open || state.allDay || !state.date || !state.startTime) {
      state.setConflict(null);
      return;
    }
    const timer = setTimeout(async () => {
      try {
        const localStart = /* @__PURE__ */ new Date(`${state.date}T${state.startTime}:00`);
        const params = new URLSearchParams({
          date: state.date,
          startTime: state.startTime,
          duration: String(state.duration)
        });
        if (editData?.id) {
          params.set("excludeId", editData.id);
        }
        if (!Number.isNaN(localStart.getTime())) {
          params.set("timezoneOffsetMinutes", String(-localStart.getTimezoneOffset()));
        }
        const data = await readApiResultOrThrow(`/api/customers/interactions/conflicts?${params.toString()}`);
        if (data?.hasConflicts && Array.isArray(data.conflicts) && data.conflicts.length > 0) {
          const descriptions = data.conflicts.map((c) => `${c.startTime}\u2013${c.endTime}: ${c.title ?? c.type}`).join(", ");
          state.setConflict(
            t("customers.schedule.conflict.description", "Overlaps with: {{items}}", { items: descriptions })
          );
        } else {
          state.setConflict(null);
        }
      } catch {
        state.setConflict(null);
      }
    }, 500);
    return () => clearTimeout(timer);
  }, [editData?.id, open, state.date, state.startTime, state.duration, state.allDay, t]);
  const trimmedDate = state.date.trim();
  const trimmedStartTime = state.startTime.trim();
  const trimmedCallPhone = callPhoneNumber.trim();
  const isDateMissing = !trimmedDate;
  const isTimeMissing = !state.allDay && !trimmedStartTime;
  const isSubmitDisabled = state.saving || !state.title.trim() || isDateMissing || isTimeMissing;
  const handleSave = React.useCallback(async () => {
    if (!state.title.trim()) return;
    if (isDateMissing) {
      flash(t("customers.activities.errors.dateRequired", "Date is required"), "error");
      return;
    }
    if (isTimeMissing) {
      flash(t("customers.activities.errors.timeRequired", "Time is required"), "error");
      return;
    }
    let phoneNumberForPayload;
    if (state.activityType === "call" && trimmedCallPhone) {
      const phoneValidation = validatePhoneNumber(trimmedCallPhone);
      if (!phoneValidation.valid) {
        setCallPhoneError(callPhoneInvalidMessage);
        flash(callPhoneInvalidMessage, "error");
        return;
      }
      phoneNumberForPayload = phoneValidation.normalized ?? trimmedCallPhone;
      setCallPhoneError(null);
      if (phoneNumberForPayload !== callPhoneNumber) {
        setCallPhoneNumber(phoneNumberForPayload);
      }
    }
    state.setSaving(true);
    try {
      const scheduledAt = state.allDay ? (/* @__PURE__ */ new Date(`${state.date}T00:00:00`)).toISOString() : (/* @__PURE__ */ new Date(`${state.date}T${state.startTime}:00`)).toISOString();
      const recurrenceRule = state.recurrenceEnabled ? buildRecurrenceRule(state.recurrenceDays, state.recurrenceEndType, state.recurrenceCount, state.recurrenceEndDate) : null;
      const isSaveEdit = Boolean(editData?.id);
      const customValues = {};
      if (state.activityType === "call") {
        customValues.callDirection = callDirection;
        if (callOutcome) customValues.callOutcome = callOutcome;
        if (phoneNumberForPayload) customValues.callPhoneNumber = phoneNumberForPayload;
      }
      if (state.activityType === "task") {
        customValues.taskPriority = taskPriority;
      }
      const payload = {
        ...isSaveEdit ? { id: editData.id } : {},
        entityId,
        dealId,
        interactionType: state.activityType,
        title: state.title.trim(),
        body: state.description.trim() || null,
        status: "planned",
        date: trimmedDate,
        time: state.allDay ? "00:00" : trimmedStartTime,
        phoneNumber: state.activityType === "call" ? phoneNumberForPayload : void 0,
        scheduledAt,
        durationMinutes: visibleFields.has("duration") && !state.allDay ? state.duration : null,
        location: visibleFields.has("location") ? state.location.trim() || null : null,
        allDay: visibleFields.has("allDay") ? state.allDay : null,
        recurrenceRule: visibleFields.has("recurrence") ? recurrenceRule : null,
        recurrenceEnd: visibleFields.has("recurrence") && state.recurrenceEndType === "date" && state.recurrenceEndDate ? new Date(state.recurrenceEndDate).toISOString() : null,
        participants: visibleFields.has("participants") && state.participants.length > 0 ? state.participants.map((p) => ({ userId: p.userId, name: p.name, email: p.email, status: p.status ?? "pending" })) : null,
        guestPermissions: visibleFields.has("participants") && state.participants.length > 0 ? state.guestPermissions : null,
        linkedEntities: state.linkedEntities.length > 0 ? state.linkedEntities.map((e) => ({ id: e.id, type: e.type, label: e.label })) : null,
        reminderMinutes: visibleFields.has("reminder") ? state.reminderMinutes : null,
        visibility: visibleFields.has("visibility") ? state.visibility : null,
        ...Object.keys(customValues).length > 0 ? { customValues } : {}
      };
      await runGuardedMutation(
        () => {
          const call = () => apiCallOrThrow("/api/customers/interactions", {
            method: isSaveEdit ? "PUT" : "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify(payload)
          });
          return isSaveEdit ? withScopedApiRequestHeaders(buildOptimisticLockHeader(editData?.updatedAt), call) : call();
        },
        {
          operation: isSaveEdit ? "updateActivity" : "createActivity",
          interactionId: editData?.id ?? null,
          interactionType: state.activityType
        }
      );
      flash(t("customers.schedule.saved", "Activity scheduled"), "success");
      onClose();
      requestAnimationFrame(() => {
        onActivityCreated?.();
      });
    } catch (err) {
      if (extractOptimisticLockConflict(err)) {
        onClose();
        return;
      }
      const { message, fieldErrors } = mapCrudServerErrorToFormErrors(err);
      const phoneFieldError = fieldErrors?.phoneNumber;
      if (state.activityType === "call" && phoneFieldError) {
        const translatedPhoneError = translateErrorMessage(phoneFieldError, callPhoneInvalidMessage);
        setCallPhoneError(translatedPhoneError);
        flash(translatedPhoneError, "error");
        return;
      }
      flash(
        translateErrorMessage(message, t("customers.schedule.error", "Failed to schedule activity")),
        "error"
      );
    } finally {
      state.setSaving(false);
    }
  }, [callDirection, callOutcome, callPhoneInvalidMessage, callPhoneNumber, isDateMissing, isTimeMissing, state.activityType, state.allDay, state.date, state.description, dealId, state.duration, editData, entityId, state.guestPermissions, state.linkedEntities, state.location, onActivityCreated, onClose, state.participants, state.recurrenceCount, state.recurrenceDays, state.recurrenceEnabled, state.recurrenceEndDate, state.recurrenceEndType, state.reminderMinutes, runGuardedMutation, state.startTime, t, taskPriority, state.title, translateErrorMessage, trimmedCallPhone, trimmedDate, trimmedStartTime, state.visibility, visibleFields]);
  const handleKeyDown = useDialogKeyHandler({ onConfirm: handleSave });
  return /* @__PURE__ */ jsxs(Dialog, { open, onOpenChange: (o) => {
    if (!o) void guardedClose();
  }, children: [
    ConfirmDialogElement,
    /* @__PURE__ */ jsxs(DialogContent, { className: "flex max-h-[90vh] flex-col overflow-hidden border-border p-0 shadow-xl sm:max-w-[760px] sm:rounded-xl [&>[data-dialog-close]]:hidden", onKeyDown: handleKeyDown, "aria-describedby": void 0, children: [
      /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx(DialogTitle, { children: isEditing ? t("customers.schedule.editTitle", "Edit activity") : t(chrome.titleKey, chrome.titleFallback) }) }),
      /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-start justify-between gap-3 border-b border-border bg-background px-6 py-5", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
          /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold leading-tight tracking-tight text-foreground", children: isEditing ? t("customers.schedule.editTitle", "Edit activity") : t(chrome.titleKey, chrome.titleFallback) }),
          /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t(chrome.subtitleKey, chrome.subtitleFallback) }),
          entityName ? /* @__PURE__ */ jsxs("p", { className: "mt-0.5 text-xs text-muted-foreground/80", children: [
            t("customers.schedule.context", "On timeline: {{name}}", { name: entityName }),
            companyName ? ` \xB7 ${companyName}` : ""
          ] }) : null
        ] }),
        /* @__PURE__ */ jsx(IconButton, { type: "button", variant: "ghost", size: "sm", onClick: () => {
          void guardedClose();
        }, className: "flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-background", "aria-label": t("customers.schedule.cancel", "Cancel"), children: /* @__PURE__ */ jsx(X, { className: "size-4 text-muted-foreground" }) })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-y-auto", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4 bg-background p-6", children: [
        state.conflict && /* @__PURE__ */ jsxs(Alert, { variant: "warning", className: "rounded-lg", children: [
          /* @__PURE__ */ jsx(AlertTitle, { children: t("customers.schedule.conflict.title", "Calendar conflict") }),
          /* @__PURE__ */ jsx(AlertDescription, { children: state.conflict })
        ] }),
        /* @__PURE__ */ jsx("div", { className: "grid grid-cols-4 gap-2", children: TYPE_TABS.map(({ type, icon: Icon, labelKey, fallback }) => {
          const isActive = state.activityType === type;
          return /* @__PURE__ */ jsxs(
            "button",
            {
              type: "button",
              onClick: () => state.setActivityType(type),
              "aria-pressed": isActive,
              className: cn(
                "flex h-[80px] flex-col items-center justify-center gap-2 rounded-md border text-[14px] font-semibold transition-colors",
                isActive ? "border-transparent bg-foreground text-background" : "border-border bg-card text-muted-foreground hover:border-foreground/40 hover:text-foreground"
              ),
              children: [
                /* @__PURE__ */ jsx(Icon, { className: "size-[18px]" }),
                t(labelKey, fallback)
              ]
            },
            type
          );
        }) }),
        /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
          /* @__PURE__ */ jsx("label", { className: "text-overline font-semibold text-muted-foreground tracking-wider", children: getFieldLabel(state.activityType, "title", t, "customers.schedule.titleLabel", "Title") }),
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "text",
              value: state.title,
              onChange: (e) => state.setTitle(e.target.value),
              placeholder: state.activityType === "email" ? t("customers.schedule.subjectPlaceholder", "Subject...") : t("customers.schedule.titlePlaceholder", "Activity title..."),
              className: "w-full rounded-md border border-border bg-background px-3 py-2.5 text-sm text-foreground outline-none focus:border-foreground",
              autoFocus: true
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          DateTimeFields,
          {
            visible: visibleFields,
            activityType: state.activityType,
            date: state.date,
            setDate: state.setDate,
            startTime: state.startTime,
            setStartTime: state.setStartTime,
            duration: state.duration,
            setDuration: state.setDuration,
            allDay: state.allDay,
            setAllDay: state.setAllDay,
            recurrenceEnabled: state.recurrenceEnabled,
            setRecurrenceEnabled: state.setRecurrenceEnabled,
            recurrenceDays: state.recurrenceDays,
            toggleRecurrenceDay: state.toggleRecurrenceDay,
            recurrenceEndType: state.recurrenceEndType,
            setRecurrenceEndType: state.setRecurrenceEndType,
            recurrenceCount: state.recurrenceCount,
            setRecurrenceCount: state.setRecurrenceCount,
            recurrenceEndDate: state.recurrenceEndDate,
            setRecurrenceEndDate: state.setRecurrenceEndDate
          }
        ),
        state.activityType === "call" && /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("label", { className: "text-overline font-semibold uppercase text-muted-foreground tracking-wider", children: t("customers.schedule.call.directionLabel", "Direction") }),
            /* @__PURE__ */ jsx("div", { className: "mt-2 flex flex-wrap gap-2", children: CALL_DIRECTIONS.map((opt) => {
              const isActive = callDirection === opt.key;
              return /* @__PURE__ */ jsxs(
                "button",
                {
                  type: "button",
                  "aria-pressed": isActive,
                  onClick: () => setCallDirection(opt.key),
                  className: cn(
                    "inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-sm font-medium transition-colors",
                    isActive ? "border-transparent bg-foreground text-background" : "border-border bg-card text-muted-foreground hover:border-foreground/40"
                  ),
                  children: [
                    /* @__PURE__ */ jsx("span", { className: cn("inline-block size-1.5 rounded-full", opt.dot), "aria-hidden": true }),
                    t(opt.labelKey, opt.labelFallback)
                  ]
                },
                opt.key
              );
            }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("label", { className: "text-overline font-semibold uppercase text-muted-foreground tracking-wider", children: t("customers.schedule.call.outcomeLabel", "Outcome") }),
            /* @__PURE__ */ jsx("div", { className: "mt-2 flex flex-wrap gap-2", children: CALL_OUTCOMES.map((opt) => {
              const isActive = callOutcome === opt.key;
              return /* @__PURE__ */ jsxs(
                "button",
                {
                  type: "button",
                  "aria-pressed": isActive,
                  onClick: () => setCallOutcome(isActive ? null : opt.key),
                  className: cn(
                    "inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-sm font-medium transition-colors",
                    isActive ? "border-transparent bg-foreground text-background" : "border-border bg-card text-muted-foreground hover:border-foreground/40"
                  ),
                  children: [
                    /* @__PURE__ */ jsx("span", { className: cn("inline-block size-1.5 rounded-full", opt.dot), "aria-hidden": true }),
                    t(opt.labelKey, opt.labelFallback)
                  ]
                },
                opt.key
              );
            }) })
          ] })
        ] }),
        state.activityType === "task" && /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("label", { className: "text-overline font-semibold uppercase text-muted-foreground tracking-wider", children: t("customers.schedule.task.priorityLabel", "Priority") }),
          /* @__PURE__ */ jsx("div", { className: "mt-2 flex flex-wrap gap-2", children: TASK_PRIORITIES.map((opt) => {
            const isActive = taskPriority === opt.key;
            return /* @__PURE__ */ jsxs(
              "button",
              {
                type: "button",
                "aria-pressed": isActive,
                onClick: () => setTaskPriority(opt.key),
                className: cn(
                  "inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-sm font-medium transition-colors",
                  isActive ? "border-transparent bg-foreground text-background" : "border-border bg-card text-muted-foreground hover:border-foreground/40"
                ),
                children: [
                  /* @__PURE__ */ jsx("span", { className: cn("inline-block size-1.5 rounded-full", opt.dot), "aria-hidden": true }),
                  t(opt.labelKey, opt.labelFallback)
                ]
              },
              opt.key
            );
          }) })
        ] }),
        /* @__PURE__ */ jsx(
          ParticipantsField,
          {
            visible: visibleFields,
            activityType: state.activityType,
            participants: state.participants,
            setParticipants: state.setParticipants,
            removeParticipant: state.removeParticipant,
            guestPermissions: state.guestPermissions,
            setGuestPermissions: state.setGuestPermissions
          }
        ),
        state.activityType === "call" ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
          /* @__PURE__ */ jsx("label", { htmlFor: "schedule-call-phone", className: "text-overline font-semibold uppercase text-muted-foreground tracking-wider", children: t("customers.schedule.call.phoneLabel", "Phone number") }),
          /* @__PURE__ */ jsx(
            PhoneNumberField,
            {
              id: "schedule-call-phone",
              value: callPhoneNumber,
              onValueChange: handleCallPhoneChange,
              placeholder: t("customers.schedule.call.phonePlaceholder", "+1 555 000 0000"),
              externalError: callPhoneError,
              invalidLabel: callPhoneInvalidMessage,
              minDigits: 7
            }
          )
        ] }) : /* @__PURE__ */ jsx(
          LocationField,
          {
            visible: visibleFields,
            activityType: state.activityType,
            location: state.location,
            setLocation: state.setLocation
          }
        ),
        /* @__PURE__ */ jsx(
          LinkedEntitiesField,
          {
            visible: visibleFields,
            activityType: state.activityType,
            linkedEntities: state.linkedEntities,
            setLinkedEntities: state.setLinkedEntities
          }
        ),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("label", { className: "text-overline font-semibold uppercase text-muted-foreground tracking-wider", children: getFieldLabel(state.activityType, "description", t, "customers.schedule.description", "Description") }),
          /* @__PURE__ */ jsx("div", { className: "mt-[8px]", children: /* @__PURE__ */ jsx(
            SwitchableMarkdownInput,
            {
              value: state.description,
              onChange: state.setDescription,
              isMarkdownEnabled: state.markdownEnabled,
              height: 120,
              placeholder: t("customers.schedule.descriptionPlaceholder", "Add details...")
            }
          ) })
        ] }),
        /* @__PURE__ */ jsx(
          FooterFields,
          {
            visible: visibleFields,
            activityType: state.activityType,
            reminderMinutes: state.reminderMinutes,
            setReminderMinutes: state.setReminderMinutes,
            visibility: state.visibility,
            setVisibility: state.setVisibility
          }
        )
      ] }) }),
      /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center justify-end gap-2.5 border-t border-border bg-muted/50 px-6 py-4", children: [
        /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: () => {
          void guardedClose();
        }, className: "rounded-md border border-input bg-background px-5 py-3 text-sm font-semibold text-foreground", children: t("customers.schedule.cancel", "Cancel") }),
        /* @__PURE__ */ jsxs(Button, { type: "button", onClick: handleSave, disabled: isSubmitDisabled, className: "flex items-center gap-2 rounded-md bg-foreground px-5 py-3 text-sm font-semibold text-background hover:bg-foreground/90 disabled:opacity-50", children: [
          /* @__PURE__ */ jsx(SaveIcon, { className: "size-3.5" }),
          state.saving ? t("customers.schedule.saving", "Saving...") : isEditing ? t("customers.schedule.update", "Update activity") : t(chrome.saveKey, chrome.saveFallback)
        ] })
      ] })
    ] })
  ] });
}
function buildRecurrenceRule(days, endType, count, endDate) {
  const dayNames = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"];
  const selectedDays = days.map((active, i) => active ? dayNames[i] : null).filter(Boolean);
  let rule = `FREQ=WEEKLY;BYDAY=${selectedDays.join(",")}`;
  if (endType === "count") rule += `;COUNT=${count}`;
  if (endType === "date" && endDate) rule += `;UNTIL=${endDate.replace(/-/g, "")}T235959Z`;
  return rule;
}
export {
  ScheduleActivityDialog
};
//# sourceMappingURL=ScheduleActivityDialog.js.map
