import { CircleAlert, Loader2, X } from "lucide-react"; import { useId, useLayoutEffect, useMemo, useRef, useState } from "react"; import { AutomationRunDialog, type AutomationRunRecord } from "@/components/settings/system/AutomationRunDialog"; import { Button } from "@/components/ui/button"; import { formControlFocusClassName } from "@/components/ui/form-control"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import type { SessionAutomationJob } from "@/lib/types"; import { cn } from "@/lib/utils"; type CalendarEntry = { id: string; job: SessionAutomationJob; startMs: number; kind: "planned" | "recorded"; run: AutomationRunRecord | null; }; type CalendarCopy = { planned: string; recorded: string; running: string; failed: string; more: (count: number) => string; close: string; noEntries: string; completed: string; skipped: string; system: string; }; interface AutomationCalendarProps { token?: string; jobs: SessionAutomationJob[]; month: Date; locale: string; copy: CalendarCopy; onInspect: (job: SessionAutomationJob, trigger: HTMLElement) => void; } function startOfDay(date: Date): Date { return new Date(date.getFullYear(), date.getMonth(), date.getDate()); } function addDays(date: Date, amount: number): Date { return new Date(date.getFullYear(), date.getMonth(), date.getDate() + amount); } function mondayIndex(date: Date): number { return (date.getDay() + 6) % 7; } function dateKey(value: Date | number): string { const date = typeof value === "number" ? new Date(value) : value; return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`; } function entriesForJobs(jobs: SessionAutomationJob[]): CalendarEntry[] { return jobs.flatMap((job) => { const history = job.state.run_history ?? []; const nextRun = job.enabled ? job.state.next_run_at_ms : null; const recordedRuns = history.length || job.state.last_run_at_ms == null || nextRun != null ? history : [{ run_at_ms: job.state.last_run_at_ms, status: job.state.last_status ?? "unknown", error: job.state.last_error, }]; const recorded = recordedRuns.map((run, index) => ({ id: `${job.id}:recorded:${run.run_at_ms}:${index}`, job, startMs: run.run_at_ms, kind: "recorded" as const, run, })); return nextRun == null ? recorded : [ ...recorded, { id: `${job.id}:planned:${nextRun}`, job, startMs: nextRun, kind: "planned" as const, run: null, }, ]; }); } function entryTime(entry: CalendarEntry, locale: string): string { const formatter = new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit" }); return formatter.format(entry.startMs); } function isSameDay(left: Date, right: Date): boolean { return dateKey(left) === dateKey(right); } function CalendarEntryRow({ entry, locale, copy, onInspect, compact = false }: { entry: CalendarEntry; locale: string; copy: CalendarCopy; onInspect: (entry: CalendarEntry, trigger: HTMLElement) => void; compact?: boolean; }) { const name = entry.job.name || entry.job.id; const running = Boolean(entry.job.state.pending) && entry.kind === "planned"; const failed = entry.run?.status === "error"; const completed = entry.run?.status === "ok"; const status = running ? copy.running : failed ? copy.failed : completed ? copy.completed : entry.run?.status === "skipped" ? copy.skipped : entry.kind === "planned" ? copy.planned : copy.recorded; const content = ( <> {name} {running ? : null} {failed ? : null} {entryTime(entry, locale)} {compact || entry.kind === "recorded" ? {status} : null} {entry.job.protected ? {copy.system} : null} ); const actionClass = cn( "flex w-full min-w-0 items-start gap-2 rounded-compact px-2 py-1.5 text-left text-[11px] leading-4", "transition-colors duration-150 hover:bg-foreground/[0.055] motion-reduce:transition-none", formControlFocusClassName, compact && "py-2 text-[12px]", failed && "bg-destructive/[0.045]", ); return ( ); } function CalendarOverflowEntries({ entries, dayLabel, locale, copy, onInspect }: { entries: CalendarEntry[]; dayLabel: string; locale: string; copy: CalendarCopy; onInspect: (entry: CalendarEntry, trigger: HTMLElement) => void; }) { const [open, setOpen] = useState(false); const titleId = useId(); const triggerRef = useRef(null); const pendingSelection = useRef(null); return ( { const entry = pendingSelection.current; pendingSelection.current = null; if (!entry || !triggerRef.current?.isConnected) return; // Hand off after the day popover exits, retaining a mounted return target. event.preventDefault(); onInspect(entry, triggerRef.current); }} >

{dayLabel}

{entries.map((entry) => ( { pendingSelection.current = entry; setOpen(false); }} compact /> ))}
); } export function AutomationCalendar({ token = "", jobs, month, locale, copy, onInspect }: AutomationCalendarProps) { const calendarRef = useRef(null); const runTrigger = useRef(null); const [selectedRun, setSelectedRun] = useState<{ job: SessionAutomationJob; run: AutomationRunRecord } | null>(null); const [runOpen, setRunOpen] = useState(false); const inspectEntry = (entry: CalendarEntry, trigger: HTMLElement) => { if (!entry.run) { onInspect(entry.job, trigger); return; } runTrigger.current = trigger; setSelectedRun({ job: entry.job, run: entry.run }); setRunOpen(true); }; const [wideCalendar, setWideCalendar] = useState(true); const today = startOfDay(new Date()); const gridStart = addDays(month, -mondayIndex(month)); const daysInMonth = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate(); const dayCount = mondayIndex(month) + daysInMonth > 35 ? 42 : 35; const days = Array.from({ length: dayCount }, (_, index) => addDays(gridStart, index)); const gridEndMs = addDays(gridStart, dayCount).getTime(); const allEntries = useMemo(() => entriesForJobs(jobs).sort((left, right) => left.startMs - right.startMs), [jobs]); const visibleEntries = allEntries.filter((entry) => entry.startMs >= gridStart.getTime() && entry.startMs < gridEndMs); const entriesByDay = new Map(); visibleEntries.forEach((entry) => { const key = dateKey(entry.startMs); entriesByDay.set(key, [...(entriesByDay.get(key) ?? []), entry]); }); const monthLabel = new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }).format(month); const weekdayFormatter = new Intl.DateTimeFormat(locale, { weekday: "short" }); const dayFormatter = new Intl.DateTimeFormat(locale, { day: "numeric" }); const agendaDateFormatter = new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", weekday: "short" }); const weekdayLabels = Array.from({ length: 7 }, (_, index) => weekdayFormatter.format(addDays(new Date(2026, 0, 5), index))); useLayoutEffect(() => { const calendar = calendarRef.current; if (!calendar) return; const update = (width: number) => { if (width > 0) setWideCalendar(width >= 704); }; update(calendar.getBoundingClientRect().width); if (typeof ResizeObserver === "undefined") return; const observer = new ResizeObserver(([entry]) => update(entry?.contentRect.width ?? 0)); observer.observe(calendar); return () => observer.disconnect(); }, []); return (
{wideCalendar ?
{weekdayLabels.map((label) =>
{label}
)}
: null}
{wideCalendar ?
{days.map((day) => { const entries = entriesByDay.get(dateKey(day)) ?? []; const currentMonth = day.getMonth() === month.getMonth(); const currentDay = isSameDay(day, today); const dayLabel = new Intl.DateTimeFormat(locale, { dateStyle: "full" }).format(day); return (
{entries.slice(0, 3).map((entry) => ( ))} {entries.length > 3 ? ( ) : null}
); })}
: null} {!wideCalendar ?
{visibleEntries.length ? (
    {days.filter((day) => entriesByDay.has(dateKey(day))).map((day) => (
  1. {(entriesByDay.get(dateKey(day)) ?? []).map((entry) => ( ))}
  2. ))}
) : (
{copy.noEntries}
)}
: null} {selectedRun ? { event.preventDefault(); if (runOpen) return; setSelectedRun(null); const target = runTrigger.current?.isConnected ? runTrigger.current : calendarRef.current; target?.focus({ preventScroll: true }); }} /> : null}
); }