"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { addDays } from "date-fns/addDays";
import { format } from "date-fns/format";
import { isSameMonth } from "date-fns/isSameMonth";
import { isToday } from "date-fns/isToday";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { cn } from "@open-mercato/shared/lib/utils";
import { Button } from "@open-mercato/ui/primitives/button";
import { getVisibleRange } from "../../lib/calendar/range.js";
import { eventDisplayTitle } from "../../lib/calendar/labels.js";
const MAX_PILLS_PER_DAY = 2;
const SOFT_TINT_ALPHA = "1A";
function dayKeyOf(date) {
  return format(date, "yyyy-MM-dd");
}
function formatTime(date) {
  return date.toLocaleTimeString(void 0, { hour: "numeric", minute: "2-digit" });
}
function fullDateLabel(date) {
  return date.toLocaleDateString(void 0, { weekday: "long", year: "numeric", month: "long", day: "numeric" });
}
function isWeekend(date) {
  const weekday = date.getDay();
  return weekday === 0 || weekday === 6;
}
function buildWeeks(anchor) {
  const range = getVisibleRange("month", anchor, 0);
  const weeks = [];
  let cursor = range.from;
  while (cursor.getTime() <= range.to.getTime()) {
    const week = [];
    for (let dayIndex = 0; dayIndex < 7; dayIndex += 1) {
      week.push(cursor);
      cursor = addDays(cursor, 1);
    }
    weeks.push(week);
  }
  return weeks;
}
function groupItemsByDay(items) {
  const sorted = [...items].sort((first, second) => first.start.getTime() - second.start.getTime());
  const byDay = /* @__PURE__ */ new Map();
  for (const item of sorted) {
    const key = dayKeyOf(item.start);
    const bucket = byDay.get(key);
    if (bucket) bucket.push(item);
    else byDay.set(key, [item]);
  }
  return byDay;
}
function MonthPill({ item, onItemClick }) {
  const t = useT();
  const canceled = item.status === "canceled";
  const title = eventDisplayTitle(item.title, t("customers.calendar.grid.untitled", "Untitled"));
  const timeLabel = item.allDay ? "" : ` \xB7 ${formatTime(item.start)} \u2013 ${formatTime(item.end)}`;
  const tintStyle = item.color ? { backgroundColor: `${item.color}${SOFT_TINT_ALPHA}`, color: item.color } : void 0;
  return /* @__PURE__ */ jsxs(
    Button,
    {
      type: "button",
      variant: "ghost",
      "aria-label": `${title}${timeLabel}`,
      onClick: (event) => {
        event.stopPropagation();
        onItemClick(item);
      },
      className: cn(
        "h-4 w-full min-w-0 justify-center gap-0 rounded-full p-0 pr-2",
        !item.color && "bg-muted text-muted-foreground",
        canceled && "opacity-60"
      ),
      style: tintStyle,
      children: [
        /* @__PURE__ */ jsx("span", { "aria-hidden": "true", className: "flex size-4 shrink-0 items-center justify-center", children: /* @__PURE__ */ jsx(
          "span",
          {
            className: cn("size-1.5 rounded-full", !item.color && "bg-muted-foreground"),
            style: item.color ? { backgroundColor: item.color } : void 0
          }
        ) }),
        /* @__PURE__ */ jsx(
          "span",
          {
            className: cn(
              "min-w-0 truncate text-overline font-medium uppercase tracking-wide",
              canceled && "line-through"
            ),
            children: title
          }
        )
      ]
    }
  );
}
function MonthDayCell({
  day,
  anchor,
  items,
  onItemClick,
  onDayOpen
}) {
  const t = useT();
  const inMonth = isSameMonth(day, anchor);
  const today = isToday(day);
  const visibleItems = items.slice(0, MAX_PILLS_PER_DAY);
  const hiddenCount = items.length - visibleItems.length;
  const dayLabel = fullDateLabel(day);
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: cn(
        "relative flex h-full min-w-0 flex-1 flex-col items-start gap-1 overflow-hidden border-r border-border p-2 text-left last:border-r-0",
        isWeekend(day) ? "bg-muted/40" : "bg-background"
      ),
      children: [
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "ghost",
            "aria-label": dayLabel,
            onClick: () => onDayOpen(day),
            className: "absolute inset-0 z-0 h-full w-full rounded-none p-0 hover:bg-muted/50",
            children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: dayLabel })
          }
        ),
        today ? /* @__PURE__ */ jsx("span", { className: "pointer-events-none relative z-10 flex items-center justify-center rounded-full bg-primary px-1.5 py-0.5 text-xs font-semibold text-primary-foreground", children: day.getDate() }) : /* @__PURE__ */ jsx("span", { className: cn("pointer-events-none relative z-10 text-xs font-medium", inMonth ? "text-foreground" : "text-muted-foreground"), children: day.getDate() }),
        /* @__PURE__ */ jsxs("span", { className: "relative z-20 hidden w-full flex-col gap-1 sm:flex", children: [
          visibleItems.map((item) => /* @__PURE__ */ jsx(MonthPill, { item, onItemClick }, item.id)),
          hiddenCount > 0 ? /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              className: "h-auto self-start p-0 text-overline font-medium text-muted-foreground hover:bg-transparent hover:underline",
              onClick: (event) => {
                event.stopPropagation();
                onDayOpen(day);
              },
              children: t("customers.calendar.grid.more", "+{count} more", { count: hiddenCount })
            }
          ) : null
        ] }),
        items.length > 0 ? /* @__PURE__ */ jsxs("span", { "aria-hidden": "true", className: "pointer-events-none relative z-10 flex w-full flex-wrap items-center gap-0.5 sm:hidden", children: [
          items.slice(0, 4).map((item) => /* @__PURE__ */ jsx(
            "span",
            {
              className: cn("size-1.5 rounded-full", !item.color && "bg-muted-foreground"),
              style: item.color ? { backgroundColor: item.color } : void 0
            },
            item.id
          )),
          items.length > 4 ? /* @__PURE__ */ jsxs("span", { className: "text-overline font-medium leading-none text-muted-foreground", children: [
            "+",
            items.length - 4
          ] }) : null
        ] }) : null
      ]
    }
  );
}
function MonthGrid({ anchor, items, onItemClick, onDayOpen }) {
  const t = useT();
  const weeks = React.useMemo(() => buildWeeks(anchor), [anchor]);
  const itemsByDay = React.useMemo(() => groupItemsByDay(items), [items]);
  return /* @__PURE__ */ jsxs("div", { className: "relative flex h-full w-full flex-col overflow-hidden border border-border bg-background", children: [
    /* @__PURE__ */ jsx("div", { className: "flex h-9 w-full shrink-0 border-b border-border", children: weeks[0]?.map((day) => {
      const label = day.toLocaleDateString(void 0, { weekday: "short" }).toUpperCase();
      return /* @__PURE__ */ jsx(
        "div",
        {
          className: "flex min-w-0 flex-1 items-center justify-center border-r border-border last:border-r-0 sm:justify-start sm:pl-2.5",
          children: /* @__PURE__ */ jsxs("span", { className: "truncate text-overline font-medium uppercase tracking-widest text-muted-foreground", children: [
            /* @__PURE__ */ jsx("span", { className: "sm:hidden", children: label.charAt(0) }),
            /* @__PURE__ */ jsx("span", { className: "hidden sm:inline", children: label })
          ] })
        },
        dayKeyOf(day)
      );
    }) }),
    weeks.map((week) => /* @__PURE__ */ jsx(
      "div",
      {
        className: "flex w-full flex-1 border-b border-border last:border-b-0 min-h-14 sm:min-h-[86px]",
        children: week.map((day) => /* @__PURE__ */ jsx(
          MonthDayCell,
          {
            day,
            anchor,
            items: itemsByDay.get(dayKeyOf(day)) ?? [],
            onItemClick,
            onDayOpen
          },
          dayKeyOf(day)
        ))
      },
      dayKeyOf(week[0])
    ))
  ] });
}
export {
  MonthGrid
};
//# sourceMappingURL=MonthGrid.js.map
