"use client";
import * as React from "react";
import { endOfDay } from "date-fns/endOfDay";
import { startOfDay } from "date-fns/startOfDay";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { computeDurationMinutes } from "../../../lib/calendar/editorPayload.js";
import { findEditorConflictItems } from "../../../lib/calendar/conflicts.js";
import { mapInteractionToCalendarItem } from "../../../lib/calendar/mapItem.js";
import { expandOccurrences } from "../../../lib/calendar/recurrence.js";
import { getFetchWindow } from "../../../lib/calendar/range.js";
import { fetchInteractionWindow } from "../useCalendarItems.js";
import { fetchDealById, fetchRelatedEntityById, findStaffMemberName } from "./lookups.js";
function useEditorLabelResolution(open, form, update) {
  React.useEffect(() => {
    if (!open) return;
    const controller = new AbortController();
    let cancelled = false;
    async function resolveLabels() {
      if (form.relatedTo && form.relatedTo.kind === "unknown") {
        const resolved = await fetchRelatedEntityById(form.relatedTo.id, controller.signal);
        if (!cancelled && resolved) update({ relatedTo: { id: resolved.id, kind: resolved.kind, label: resolved.label } });
      }
      if (form.dealId && !form.dealLabel) {
        const deal = await fetchDealById(form.dealId, controller.signal);
        if (!cancelled && deal) update({ dealLabel: deal.label });
      }
      if (form.assigneeUserId && !form.assigneeName) {
        const name = await findStaffMemberName(form.assigneeUserId, controller.signal);
        if (!cancelled && name) update({ assigneeName: name });
      }
    }
    resolveLabels().catch(() => {
      if (cancelled || controller.signal.aborted || !form.relatedTo || form.relatedTo.kind !== "unknown" || form.relatedTo.label) {
        return;
      }
      update({ relatedTo: { ...form.relatedTo, label: form.relatedTo.id } });
    });
    return () => {
      cancelled = true;
      controller.abort();
    };
  }, [open, form.relatedTo, form.dealId, form.dealLabel, form.assigneeUserId, form.assigneeName, update]);
}
function formatClock(date) {
  return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}
function useConflictProbe(open, form, config, excludeId, draftOwnerUserId, scope, currentUserId) {
  const t = useT();
  const [conflict, setConflict] = React.useState(null);
  const participantsKey = form.participants.map((participant) => participant.userId).join(",");
  React.useEffect(() => {
    if (!open || !form.date) {
      setConflict(null);
      return;
    }
    const isAllDay = config.hasAllDay && form.allDay;
    let start;
    let end;
    if (isAllDay) {
      const dayDate = /* @__PURE__ */ new Date(`${form.date}T00:00:00`);
      if (Number.isNaN(dayDate.getTime())) {
        setConflict(null);
        return;
      }
      start = startOfDay(dayDate);
      end = endOfDay(dayDate);
    } else {
      if (!form.startTime) {
        setConflict(null);
        return;
      }
      start = /* @__PURE__ */ new Date(`${form.date}T${form.startTime}:00`);
      if (Number.isNaN(start.getTime())) {
        setConflict(null);
        return;
      }
      const durationMinutes = config.hasEnd ? computeDurationMinutes(form) ?? 30 : 30;
      end = new Date(start.getTime() + durationMinutes * 6e4);
    }
    const dayStart = startOfDay(start);
    dayStart.setDate(dayStart.getDate() - 1);
    const dayEnd = endOfDay(end);
    dayEnd.setDate(dayEnd.getDate() + 1);
    const fetchWindow = getFetchWindow({ from: dayStart, to: dayEnd });
    const controller = new AbortController();
    let active = true;
    const timer = setTimeout(async () => {
      try {
        const { payloads } = await fetchInteractionWindow(fetchWindow, controller.signal);
        if (!active) return;
        const others = [];
        for (const payload of payloads) {
          const item = mapInteractionToCalendarItem(payload, {});
          if (!item) continue;
          others.push(...expandOccurrences(item, fetchWindow));
        }
        const conflictItems = findEditorConflictItems(
          {
            start,
            end,
            ownerUserId: draftOwnerUserId,
            participants: form.participants.map((participant) => ({ userId: participant.userId, name: participant.name })),
            status: form.status
          },
          others,
          excludeId,
          { scope, currentUserId }
        );
        if (!active) return;
        if (conflictItems.length === 0) {
          setConflict(null);
          return;
        }
        const summary = conflictItems.map((item) => `${formatClock(item.start)}\u2013${formatClock(item.end)}: ${item.title || t("customers.calendar.grid.untitled", "Untitled")}`).join(", ");
        setConflict(summary ? t("customers.calendar.editor.conflictWarning", "Overlaps with: {items}", { items: summary }) : null);
      } catch {
        if (active) setConflict(null);
      }
    }, 500);
    return () => {
      active = false;
      clearTimeout(timer);
      controller.abort();
    };
  }, [open, form.date, form.startTime, form.endDate, form.endTime, form.allDay, form.status, participantsKey, config.hasAllDay, config.hasEnd, excludeId, draftOwnerUserId, scope, currentUserId, t]);
  return conflict;
}
export {
  useConflictProbe,
  useEditorLabelResolution
};
//# sourceMappingURL=hooks.js.map
