"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Button } from "@open-mercato/ui/primitives/button";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { CalendarDays, ChevronLeft, ChevronRight } from "lucide-react";
function getMonday(date) {
  const result = new Date(date);
  const day = result.getDay();
  const diff = day === 0 ? -6 : 1 - day;
  result.setDate(result.getDate() + diff);
  result.setHours(0, 0, 0, 0);
  return result;
}
function getWeekNumber(date) {
  const target = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
  target.setUTCDate(target.getUTCDate() + 4 - (target.getUTCDay() || 7));
  const yearStart = new Date(Date.UTC(target.getUTCFullYear(), 0, 1));
  return Math.ceil(((target.getTime() - yearStart.getTime()) / 864e5 + 1) / 7);
}
function isSameDay(first, second) {
  return first.getFullYear() === second.getFullYear() && first.getMonth() === second.getMonth() && first.getDate() === second.getDate();
}
function isSameWeek(first, second) {
  return isSameDay(getMonday(first), getMonday(second));
}
function buildWeeks(year, month) {
  const firstDay = new Date(year, month, 1);
  const start = getMonday(firstDay);
  const weeks = [];
  const current = new Date(start);
  for (let weekIdx = 0; weekIdx < 6; weekIdx++) {
    const week = [];
    for (let dayIdx = 0; dayIdx < 7; dayIdx++) {
      week.push(new Date(current));
      current.setDate(current.getDate() + 1);
    }
    weeks.push(week);
    if (current.getMonth() !== month && weekIdx >= 3) break;
  }
  return weeks;
}
function getLocalizedDayHeaders() {
  const baseMonday = new Date(2024, 0, 1);
  return Array.from({ length: 7 }, (_, idx) => {
    const date = new Date(baseMonday);
    date.setDate(date.getDate() + idx);
    return date.toLocaleDateString(void 0, { weekday: "narrow" });
  });
}
function CalendarPicker({ selectedWeekStart, onWeekSelect }) {
  const t = useT();
  const [open, setOpen] = React.useState(false);
  const [viewYear, setViewYear] = React.useState(selectedWeekStart.getFullYear());
  const [viewMonth, setViewMonth] = React.useState(selectedWeekStart.getMonth());
  const containerRef = React.useRef(null);
  const dayHeaders = React.useMemo(() => getLocalizedDayHeaders(), []);
  React.useEffect(() => {
    function handleClickOutside(event) {
      if (containerRef.current && !containerRef.current.contains(event.target)) {
        setOpen(false);
      }
    }
    if (open) document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [open]);
  React.useEffect(() => {
    setViewYear(selectedWeekStart.getFullYear());
    setViewMonth(selectedWeekStart.getMonth());
  }, [selectedWeekStart]);
  const weeks = React.useMemo(() => buildWeeks(viewYear, viewMonth), [viewYear, viewMonth]);
  const monthLabel = React.useMemo(() => {
    return new Date(viewYear, viewMonth, 1).toLocaleString(void 0, { month: "long", year: "numeric" });
  }, [viewYear, viewMonth]);
  const today = React.useMemo(() => /* @__PURE__ */ new Date(), []);
  const handleWeekClick = React.useCallback((monday) => {
    onWeekSelect(monday);
    setOpen(false);
  }, [onWeekSelect]);
  const goToPrevMonth = React.useCallback(() => {
    setViewMonth((prev) => {
      if (prev === 0) {
        setViewYear((yr) => yr - 1);
        return 11;
      }
      return prev - 1;
    });
  }, []);
  const goToNextMonth = React.useCallback(() => {
    setViewMonth((prev) => {
      if (prev === 11) {
        setViewYear((yr) => yr + 1);
        return 0;
      }
      return prev + 1;
    });
  }, []);
  return /* @__PURE__ */ jsxs("div", { ref: containerRef, className: "relative inline-block", children: [
    /* @__PURE__ */ jsx(
      IconButton,
      {
        variant: "outline",
        size: "sm",
        type: "button",
        onClick: () => setOpen((prev) => !prev),
        "aria-label": t("staff.timesheets.my.calendar.open", "Open calendar"),
        children: /* @__PURE__ */ jsx(CalendarDays, { className: "size-4" })
      }
    ),
    open && /* @__PURE__ */ jsxs("div", { className: "absolute left-0 z-20 mt-1 w-[280px] rounded-lg border bg-popover p-3 shadow-lg", children: [
      /* @__PURE__ */ jsxs("div", { className: "mb-3 flex gap-2 border-b pb-2", children: [
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "sm",
            className: "h-auto px-2 py-1 text-xs",
            onClick: () => handleWeekClick(getMonday(/* @__PURE__ */ new Date())),
            children: t("staff.timesheets.my.calendar.thisWeek", "This week")
          }
        ),
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "sm",
            className: "h-auto px-2 py-1 text-xs",
            onClick: () => {
              const lastWeek = /* @__PURE__ */ new Date();
              lastWeek.setDate(lastWeek.getDate() - 7);
              handleWeekClick(getMonday(lastWeek));
            },
            children: t("staff.timesheets.my.calendar.lastWeek", "Last week")
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "mb-2 flex items-center justify-between", children: [
        /* @__PURE__ */ jsx(
          IconButton,
          {
            variant: "ghost",
            size: "xs",
            type: "button",
            onClick: goToPrevMonth,
            "aria-label": t("staff.timesheets.my.calendar.prevMonth", "Previous month"),
            children: /* @__PURE__ */ jsx(ChevronLeft, { className: "size-3.5" })
          }
        ),
        /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: monthLabel }),
        /* @__PURE__ */ jsx(
          IconButton,
          {
            variant: "ghost",
            size: "xs",
            type: "button",
            onClick: goToNextMonth,
            "aria-label": t("staff.timesheets.my.calendar.nextMonth", "Next month"),
            children: /* @__PURE__ */ jsx(ChevronRight, { className: "size-3.5" })
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[32px_repeat(7,1fr)] gap-0 mb-1", children: [
        /* @__PURE__ */ jsx("div", {}),
        dayHeaders.map((day, idx) => /* @__PURE__ */ jsx("div", { className: "text-center text-[11px] font-medium text-muted-foreground py-1", children: day }, idx))
      ] }),
      weeks.map((week) => {
        const monday = week[0];
        const weekNum = getWeekNumber(monday);
        const isSelected = isSameWeek(monday, selectedWeekStart);
        return /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "ghost",
            className: `grid grid-cols-[32px_repeat(7,1fr)] gap-0 w-full h-auto rounded-md px-0 py-0 hover:bg-muted
                  ${isSelected ? "bg-primary text-primary-foreground hover:bg-primary/90" : ""}`,
            onClick: () => handleWeekClick(monday),
            children: [
              /* @__PURE__ */ jsx("span", { className: `text-[10px] font-medium py-1.5 text-center ${isSelected ? "text-primary-foreground/70" : "text-muted-foreground"}`, children: weekNum }),
              week.map((date) => {
                const inMonth = date.getMonth() === viewMonth;
                const isTodayDate = isSameDay(date, today);
                return /* @__PURE__ */ jsx(
                  "span",
                  {
                    className: `text-xs py-1.5 text-center
                        ${!inMonth && !isSelected ? "text-muted-foreground/40" : ""}
                        ${isTodayDate && !isSelected ? "font-bold text-primary" : ""}
                        ${isTodayDate && isSelected ? "font-bold underline" : ""}`,
                    children: date.getDate()
                  },
                  date.toISOString()
                );
              })
            ]
          },
          monday.toISOString()
        );
      })
    ] })
  ] });
}
export {
  CalendarPicker
};
//# sourceMappingURL=CalendarPicker.js.map
