"use client"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { useIsMobile } from "@suphark/ui/hooks/use-mobile"; import { useMounted } from "@suphark/ui/hooks/use-mounted"; import { cn } from "@suphark/ui/lib/utils"; import { Check, ChevronLeftIcon, ChevronRightIcon } from "lucide-react"; import { type ReactNode, useMemo, useState } from "react"; /** บริบทของช่องวันที่ให้ `renderDay`/`dayLabel` */ export interface CalendarDayContext { day: number; date: Date; items: T[]; isToday: boolean; isSelected: boolean; isWeekend: boolean; } export interface CalendarDayState { /** ทุกรายการของวันนั้นเสร็จแล้ว → `data-complete` + ✓ (เมื่อไม่มี renderDay) */ complete?: boolean; hasItems?: boolean; } export interface CalendarMonthGridProps { /** เดือนที่แสดง `"YYYY-MM"` */ month: string; /** วันที่ที่เลือก (1–31) */ selectedDay?: number | null; onSelectDay?: (day: number, date: Date) => void; /** รายการต่อวัน (key = วันที่ 1–31) */ itemsByDay?: Record; /** เนื้อหาใต้เลขวัน (จุดสถานะ ฯลฯ) — ไม่ส่ง หรือคืน null/undefined = ✓ ของแพ็กเกจเมื่อ complete */ renderDay?: (ctx: CalendarDayContext) => ReactNode; /** สถานะของช่องจากรายการ → data-attribute ให้ CSS ของแอปแต่งได้ */ dayState?: (items: T[], ctx: Omit, "items">) => CalendarDayState; /** วันเริ่มสัปดาห์: 0 = อาทิตย์ (ค่าเริ่มต้น, ไทย), 1 = จันทร์ */ weekStartsOn?: 0 | 1; /** ชื่อวัน 7 ตัวเริ่มที่อาทิตย์เสมอ (ค่าเริ่มต้นไทย) */ weekdayLabels?: readonly string[]; /** "วันนี้" — ไม่ส่ง = อ่านจาก browser หลัง mount (server ไม่รู้โซนเวลาผู้ใช้) */ today?: Date; /** aria-label ของปุ่มวัน (ค่าเริ่มต้น "วันที่ N มี M รายการ") */ dayLabel?: (ctx: CalendarDayContext) => string; /** คำอธิบายสัญลักษณ์ใต้ตาราง */ legend?: ReactNode; className?: string; /** class เพิ่มของปุ่มวัน */ dayClassName?: string | ((ctx: CalendarDayContext) => string | undefined); /** * `month` (ค่าเริ่มต้น) ตารางทั้งเดือน · `week` แถบ 7 วัน ช่อง 44px + รายการของวันที่เลือกด้านล่าง (`renderDayItems`) * · `auto` = สัปดาห์บนจอ < 768px เดือนบนจอกว้าง — สัปดาห์เลื่อนได้ภายในเดือนนี้ (เปลี่ยนเดือนด้วย MonthStepper เหมือนเดิม) */ view?: "month" | "week" | "auto"; /** แสดงปุ่มสลับเดือน/สัปดาห์ (ผู้ใช้สลับเองได้) */ viewToggle?: boolean; onViewChange?: (view: "month" | "week") => void; /** โหมดสัปดาห์: รายการของวันที่เลือกใต้แถบวัน (ไม่ส่ง = ไม่มีส่วนนี้) */ renderDayItems?: (ctx: CalendarDayContext) => ReactNode; /** * โหมดสัปดาห์: เลื่อนสัปดาห์ข้ามเดือนได้ — ถึงขอบเดือนแล้วกดต่อ = เรียกพร้อม `"YYYY-MM"` ของเดือนใหม่ (แอปเปลี่ยน `month` + โหลดข้อมูล) * ไม่ส่ง = เลื่อนได้ภายในเดือนนี้เท่านั้น · วันของเดือนข้างเคียงในแถบแสดงจาง ๆ กดไม่ได้ */ onMonthChange?: (month: string) => void; } export const WEEKDAYS_TH = ["อา", "จ", "อ", "พ", "พฤ", "ศ", "ส"] as const; export const WEEKDAYS_EN = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] as const; function parseMonth(month: string): { year: number; monthIndex: number } { const [y, m] = month.split("-"); const year = Number(y); const monthIndex = Number(m) - 1; if (!Number.isFinite(year) || !Number.isFinite(monthIndex) || monthIndex < 0 || monthIndex > 11) { throw new Error(`CalendarMonthGrid: month ต้องเป็น "YYYY-MM" ได้ "${month}"`); } return { year, monthIndex }; } /** * ตารางเดือน (ปฏิทินเลือกวัน) ที่แอปคุมเนื้อหาต่อวันเอง — ยกจาก DueBell/Pi Done ให้ใช้ร่วม * ปุ่มวันมี `aria-pressed` + data-attribute แบบ boolean (มี/ไม่มี ไม่มีค่า "true"): `data-selected`, `data-today`, * `data-has-items`, `data-complete`, `data-weekend` → CSS ของแอปใช้ `[data-selected]` / Tailwind `data-selected:` * SSR ได้: "วันนี้" อ่านจาก browser หลัง mount (หรือส่ง `today`) */ export function CalendarMonthGrid({ month, selectedDay = null, onSelectDay, itemsByDay = {}, renderDay, dayState, weekStartsOn = 0, weekdayLabels = WEEKDAYS_TH, today: todayProp, dayLabel, legend, className, dayClassName, view = "month", viewToggle = false, onViewChange, renderDayItems, onMonthChange, }: CalendarMonthGridProps) { const mounted = useMounted(); const text = useUiText().calendarView; const isMobile = useIsMobile(); const [chosenView, setChosenView] = useState<"month" | "week" | null>(null); const resolvedView = chosenView ?? (view === "auto" ? (isMobile ? "week" : "month") : view); // วันที่ยึดของแถบสัปดาห์ ผูกกับเดือน — แอปเปลี่ยนเดือนเอง (MonthStepper) แล้วไม่ค้างวันของเดือนเก่า const [anchor, setAnchor] = useState<{ month: string; day: number } | null>(null); const weekAnchor = anchor?.month === month ? anchor.day : null; const setWeekAnchor = (day: number, forMonth = month) => setAnchor({ month: forMonth, day }); const { year, monthIndex } = parseMonth(month); // today: prop > browser หลัง mount > ไม่มี (server) — ไม่ใช้ new Date() ตอน render บน server const today = todayProp ?? (mounted ? new Date() : null); const isThisMonth = !!today && today.getFullYear() === year && today.getMonth() === monthIndex; const { headers, blanks, days } = useMemo(() => { const firstWeekday = new Date(year, monthIndex, 1).getDay(); // 0 = อาทิตย์ const daysInMonth = new Date(year, monthIndex + 1, 0).getDate(); const offset = (firstWeekday - weekStartsOn + 7) % 7; const headers = Array.from({ length: 7 }, (_, i) => { const weekday = (i + weekStartsOn) % 7; return { weekday, label: weekdayLabels[weekday] ?? "" }; }); return { headers, blanks: Array.from({ length: offset }, (_, i) => i), days: Array.from({ length: daysInMonth }, (_, i) => i + 1), }; }, [year, monthIndex, weekStartsOn, weekdayLabels]); const dayButton = (day: number, variant: "month" | "week") => { const date = new Date(year, monthIndex, day); const items = itemsByDay[day] ?? []; const weekday = date.getDay(); const base = { day, date, isToday: isThisMonth && today?.getDate() === day, isSelected: selectedDay === day, isWeekend: weekday === 0 || weekday === 6, }; const ctx: CalendarDayContext = { ...base, items }; const state = dayState?.(items, base) ?? {}; const hasItems = state.hasItems ?? items.length > 0; const complete = state.complete ?? false; const extra = typeof dayClassName === "function" ? dayClassName(ctx) : dayClassName; return ( ); }; const header = (
{headers.map((h) => ( {h.label} ))}
); const toggle = viewToggle ? (
{(["month", "week"] as const).map((v) => ( ))}
) : null; if (resolvedView === "week") { // สัปดาห์ที่มีวันอ้างอิง (เลื่อนแล้ว > วันที่เลือก > วันนี้ในเดือนนี้ > วันที่ 1) const anchor = weekAnchor ?? selectedDay ?? (isThisMonth && today ? today.getDate() : 1); const firstWeekday = new Date(year, monthIndex, 1).getDay(); const offset = (firstWeekday - weekStartsOn + 7) % 7; const weekIndex = Math.floor((anchor - 1 + offset) / 7); const weekStart = weekIndex * 7 - offset + 1; const cells = Array.from({ length: 7 }, (_, i) => weekStart + i); const lastWeekIndex = Math.floor((days.length - 1 + offset) / 7); const prevMonthDays = new Date(year, monthIndex, 0).getDate(); const shiftMonth = (delta: number) => { const d = new Date(year, monthIndex + delta, 1); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`; }; const selectedInWeek = selectedDay !== null && cells.includes(selectedDay) ? selectedDay : null; const selectedCtx = selectedInWeek !== null ? (() => { const date = new Date(year, monthIndex, selectedInWeek); const weekday = date.getDay(); return { day: selectedInWeek, date, items: itemsByDay[selectedInWeek] ?? [], isToday: isThisMonth && today?.getDate() === selectedInWeek, isSelected: true, isWeekend: weekday === 0 || weekday === 6, } satisfies CalendarDayContext; })() : null; const navButton = "flex size-8 items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring/50 disabled:opacity-30 pointer-coarse:size-11 [&_svg]:size-4"; return (
{toggle}
{header}
{cells.map((day) => day >= 1 && day <= days.length ? ( dayButton(day, "week") ) : ( ), )}
{renderDayItems && (
{selectedCtx ? ( <>

{(text?.items ?? "{count} รายการ").replace( "{count}", String(selectedCtx.items.length), )}

{selectedCtx.items.length > 0 ? ( renderDayItems(selectedCtx) ) : (

{text?.noItems ?? "ไม่มีรายการ"}

)} ) : null}
)} {legend &&
{legend}
}
); } return (
{toggle &&
{toggle}
} {header}
{blanks.map((b) => ( {legend &&
{legend}
}
); }