import { __name } from './chunk-N2XQF2OL.mjs';
import { createContext, useRef, useState, useEffect, useMemo, useCallback, useContext } from 'react';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { Tabs, TabsList, TabsTrigger, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, Input, Popover, PopoverTrigger, PopoverContent } from '@djangocfg/ui-core/components';
import { cn } from '@djangocfg/ui-core/lib';
import { Clock, CheckCircle2, AlertCircle, HelpCircle, Calendar, Check, Copy, ArrowRight } from 'lucide-react';

// src/tools/CronScheduler/utils/cron-builder.ts
function buildCron(state) {
  if (!state || typeof state !== "object") {
    return "0 0 * * *";
  }
  const { type, hour = 0, minute = 0, weekDays = [], monthDays = [], customCron = "" } = state;
  const h = Math.max(0, Math.min(23, Number(hour) || 0));
  const m = Math.max(0, Math.min(59, Number(minute) || 0));
  const safeWeekDays = Array.isArray(weekDays) ? weekDays : [];
  const safeMonthDays = Array.isArray(monthDays) ? monthDays : [];
  switch (type) {
    case "daily":
      return `${m} ${h} * * *`;
    case "weekly": {
      const sortedDays = [...safeWeekDays].sort((a, b) => a - b);
      const daysStr = sortedDays.length > 0 ? formatNumberList(sortedDays) : "*";
      return `${m} ${h} * * ${daysStr}`;
    }
    case "monthly": {
      const sortedDays = [...safeMonthDays].sort((a, b) => a - b);
      const daysStr = sortedDays.length > 0 ? formatNumberList(sortedDays) : "1";
      return `${m} ${h} ${daysStr} * *`;
    }
    case "custom":
      return (customCron || "").trim() || "* * * * *";
    default:
      return "0 0 * * *";
  }
}
__name(buildCron, "buildCron");
function formatNumberList(nums) {
  if (nums.length === 0) return "";
  if (nums.length === 1) return nums[0].toString();
  const sorted = [...nums].sort((a, b) => a - b);
  const ranges = [];
  let start = sorted[0];
  let end = sorted[0];
  for (let i = 1; i < sorted.length; i++) {
    if (sorted[i] === end + 1) {
      end = sorted[i];
    } else {
      ranges.push(start === end ? `${start}` : `${start}-${end}`);
      start = sorted[i];
      end = sorted[i];
    }
  }
  ranges.push(start === end ? `${start}` : `${start}-${end}`);
  return ranges.join(",");
}
__name(formatNumberList, "formatNumberList");

// src/tools/CronScheduler/utils/cron-parser.ts
function parseCron(cron) {
  if (!cron || typeof cron !== "string") return null;
  const parts = cron.trim().split(/\s+/);
  if (parts.length !== 5) return null;
  const [minutePart, hourPart, dayOfMonthPart, monthPart, dayOfWeekPart] = parts;
  if (!isValidCronField(minutePart, 0, 59)) return null;
  if (!isValidCronField(hourPart, 0, 23)) return null;
  if (!isValidCronField(dayOfMonthPart, 1, 31)) return null;
  if (!isValidCronField(monthPart, 1, 12)) return null;
  if (!isValidCronField(dayOfWeekPart, 0, 6)) return null;
  const minute = parseField(minutePart);
  const hour = parseField(hourPart);
  const result = detectScheduleType(
    minutePart,
    hourPart,
    dayOfMonthPart,
    monthPart,
    dayOfWeekPart
  );
  return {
    type: result.type,
    hour: hour ?? 0,
    minute: minute ?? 0,
    weekDays: result.weekDays,
    monthDays: result.monthDays,
    customCron: cron,
    isValid: true
  };
}
__name(parseCron, "parseCron");
function isSimpleField(part) {
  return part === "*" || /^\d+$/.test(part);
}
__name(isSimpleField, "isSimpleField");
function detectScheduleType(minutePart, hourPart, dayOfMonthPart, monthPart, dayOfWeekPart) {
  let type = "custom";
  let weekDays = [1, 2, 3, 4, 5];
  let monthDays = [1];
  if (!isSimpleField(minutePart) || !isSimpleField(hourPart)) {
    return { type: "custom", weekDays, monthDays };
  }
  if (dayOfMonthPart === "*" && monthPart === "*" && dayOfWeekPart === "*") {
    type = "daily";
  } else if (dayOfMonthPart === "*" && monthPart === "*" && dayOfWeekPart !== "*") {
    type = "weekly";
    weekDays = parseWeekDays(dayOfWeekPart);
  } else if (dayOfMonthPart !== "*" && monthPart === "*" && dayOfWeekPart === "*") {
    type = "monthly";
    monthDays = parseMonthDays(dayOfMonthPart);
  }
  return { type, weekDays, monthDays };
}
__name(detectScheduleType, "detectScheduleType");
function isValidCronField(part, min, max) {
  if (part === "*") return true;
  if (part.includes("/")) {
    const [base, step] = part.split("/");
    if (!step || !/^\d+$/.test(step)) return false;
    if (base === "*") return true;
    return isValidCronField(base, min, max);
  }
  if (part.includes("-") && !part.includes(",")) {
    const [start, end] = part.split("-").map((s) => parseInt(s, 10));
    return !isNaN(start) && !isNaN(end) && start >= min && end <= max && start <= end;
  }
  if (part.includes(",")) {
    return part.split(",").every((p) => isValidCronField(p.trim(), min, max));
  }
  if (/^\d+$/.test(part)) {
    const num = parseInt(part, 10);
    return num >= min && num <= max;
  }
  return false;
}
__name(isValidCronField, "isValidCronField");
function parseField(part, _min, _max) {
  if (/^\d+$/.test(part)) {
    return parseInt(part, 10);
  }
  return null;
}
__name(parseField, "parseField");
function parseWeekDays(part) {
  const result = [];
  if (part.includes("-")) {
    const [start, end] = part.split("-").map((s) => parseInt(s, 10));
    if (!isNaN(start) && !isNaN(end)) {
      for (let i = start; i <= end && i <= 6; i++) {
        if (i >= 0) result.push(i);
      }
    }
    return result.length > 0 ? result : [1, 2, 3, 4, 5];
  }
  for (const segment of part.split(",")) {
    const num = parseInt(segment.trim(), 10);
    if (!isNaN(num) && num >= 0 && num <= 6) {
      result.push(num);
    }
  }
  return result.length > 0 ? result : [1, 2, 3, 4, 5];
}
__name(parseWeekDays, "parseWeekDays");
function parseMonthDays(part) {
  const result = [];
  if (part.includes("-")) {
    const [start, end] = part.split("-").map((s) => parseInt(s, 10));
    if (!isNaN(start) && !isNaN(end)) {
      for (let i = start; i <= end && i <= 31; i++) {
        if (i >= 1) result.push(i);
      }
    }
    return result.length > 0 ? result : [1];
  }
  for (const segment of part.split(",")) {
    const num = parseInt(segment.trim(), 10);
    if (!isNaN(num) && num >= 1 && num <= 31) {
      result.push(num);
    }
  }
  return result.length > 0 ? result : [1];
}
__name(parseMonthDays, "parseMonthDays");
function isValidCron(cron) {
  if (!cron || typeof cron !== "string") return false;
  const parts = cron.trim().split(/\s+/);
  if (parts.length !== 5) return false;
  const [minutePart, hourPart, dayOfMonthPart, monthPart, dayOfWeekPart] = parts;
  return isValidCronField(minutePart, 0, 59) && isValidCronField(hourPart, 0, 23) && isValidCronField(dayOfMonthPart, 1, 31) && isValidCronField(monthPart, 1, 12) && isValidCronField(dayOfWeekPart, 0, 6);
}
__name(isValidCron, "isValidCron");

// src/tools/CronScheduler/utils/cron-humanize.ts
var WEEKDAY_SHORT = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
function humanizeCron(cron) {
  if (!cron || typeof cron !== "string") return "Invalid schedule";
  const parts = cron.trim().split(/\s+/);
  if (parts.length !== 5) return "Invalid schedule";
  const [minutePart, hourPart, dayOfMonthPart, monthPart, dayOfWeekPart] = parts;
  const minute = parseInt(minutePart, 10);
  const hour = parseInt(hourPart, 10);
  const timeStr = formatTime(hour, minute);
  if (minutePart === "*" && hourPart === "*" && dayOfMonthPart === "*" && monthPart === "*" && dayOfWeekPart === "*") {
    return "Every minute";
  }
  if (minutePart.startsWith("*/")) {
    const interval = parseInt(minutePart.slice(2), 10);
    if (hourPart === "*") {
      return `Every ${interval} minute${interval > 1 ? "s" : ""}`;
    }
    return `Every ${interval} minute${interval > 1 ? "s" : ""} at hour ${hour}`;
  }
  if (!isNaN(minute) && hourPart === "*" && dayOfMonthPart === "*" && monthPart === "*" && dayOfWeekPart === "*") {
    return `Every hour at minute ${minute}`;
  }
  if (dayOfMonthPart === "*" && monthPart === "*" && dayOfWeekPart === "*") {
    return `Every day at ${timeStr}`;
  }
  if (dayOfMonthPart === "*" && monthPart === "*" && dayOfWeekPart !== "*") {
    const days = parseWeekDays2(dayOfWeekPart);
    if (days.length === 7) {
      return `Every day at ${timeStr}`;
    }
    if (days.length === 5 && isWeekdays(days)) {
      return `Weekdays at ${timeStr}`;
    }
    if (days.length === 2 && isWeekend(days)) {
      return `Weekends at ${timeStr}`;
    }
    const dayNames = days.map((d) => WEEKDAY_SHORT[d]).join(", ");
    return `${dayNames} at ${timeStr}`;
  }
  if (dayOfMonthPart !== "*" && monthPart === "*" && dayOfWeekPart === "*") {
    const days = parseMonthDays2(dayOfMonthPart);
    if (days.length === 1) {
      return `${ordinal(days[0])} of every month at ${timeStr}`;
    }
    if (days.length <= 3) {
      const dayStr = days.map((d) => ordinal(d)).join(", ");
      return `${dayStr} of every month at ${timeStr}`;
    }
    return `${days.length} days per month at ${timeStr}`;
  }
  return `Custom schedule`;
}
__name(humanizeCron, "humanizeCron");
function formatTime(hour, minute) {
  const h = isNaN(hour) ? 0 : Math.max(0, Math.min(23, hour));
  const m = isNaN(minute) ? 0 : Math.max(0, Math.min(59, minute));
  return `${h.toString().padStart(2, "0")}:${m.toString().padStart(2, "0")}`;
}
__name(formatTime, "formatTime");
function parseWeekDays2(part) {
  const result = [];
  if (part.includes("-") && !part.includes(",")) {
    const [start, end] = part.split("-").map((s) => parseInt(s, 10));
    if (!isNaN(start) && !isNaN(end)) {
      for (let i = start; i <= end && i <= 6; i++) {
        if (i >= 0) result.push(i);
      }
    }
    return result;
  }
  for (const segment of part.split(",")) {
    if (segment.includes("-")) {
      const [start, end] = segment.split("-").map((s) => parseInt(s, 10));
      if (!isNaN(start) && !isNaN(end)) {
        for (let i = start; i <= end && i <= 6; i++) {
          if (i >= 0) result.push(i);
        }
      }
    } else {
      const num = parseInt(segment.trim(), 10);
      if (!isNaN(num) && num >= 0 && num <= 6) {
        result.push(num);
      }
    }
  }
  return result.sort((a, b) => a - b);
}
__name(parseWeekDays2, "parseWeekDays");
function parseMonthDays2(part) {
  const result = [];
  if (part.includes("-") && !part.includes(",")) {
    const [start, end] = part.split("-").map((s) => parseInt(s, 10));
    if (!isNaN(start) && !isNaN(end)) {
      for (let i = start; i <= end && i <= 31; i++) {
        if (i >= 1) result.push(i);
      }
    }
    return result;
  }
  for (const segment of part.split(",")) {
    const num = parseInt(segment.trim(), 10);
    if (!isNaN(num) && num >= 1 && num <= 31) {
      result.push(num);
    }
  }
  return result.sort((a, b) => a - b);
}
__name(parseMonthDays2, "parseMonthDays");
function isWeekdays(days) {
  const sorted = [...days].sort((a, b) => a - b);
  return sorted.join(",") === "1,2,3,4,5";
}
__name(isWeekdays, "isWeekdays");
function isWeekend(days) {
  const sorted = [...days].sort((a, b) => a - b);
  return sorted.join(",") === "0,6";
}
__name(isWeekend, "isWeekend");
function ordinal(n) {
  const s = ["th", "st", "nd", "rd"];
  const v = n % 100;
  return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
__name(ordinal, "ordinal");
var CronSchedulerContext = createContext(null);
var DEFAULT_STATE = {
  type: "daily",
  hour: 9,
  minute: 0,
  weekDays: [1, 2, 3, 4, 5],
  // Mon-Fri
  monthDays: [1],
  customCron: "* * * * *",
  isValid: true
};
function CronSchedulerProvider({
  children,
  value,
  onChange,
  defaultType = "daily"
}) {
  const isInitialMount = useRef(true);
  const onChangeRef = useRef(onChange);
  onChangeRef.current = onChange;
  const [initialValue] = useState(() => value || null);
  const [state, setState] = useState(() => {
    try {
      if (value) {
        const parsed = parseCron(value);
        if (parsed) return parsed;
      }
    } catch {
    }
    return { ...DEFAULT_STATE, type: defaultType };
  });
  useEffect(() => {
    try {
      if (value) {
        const parsed = parseCron(value);
        if (parsed) {
          const currentCron = buildCron(state);
          if (value !== currentCron) {
            setState(parsed);
          }
        }
      }
    } catch {
    }
  }, [value]);
  const cronExpression = useMemo(() => buildCron(state), [state]);
  const humanDescription = useMemo(() => humanizeCron(cronExpression), [cronExpression]);
  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      return;
    }
    onChangeRef.current?.(cronExpression);
  }, [cronExpression]);
  const setType = useCallback((type) => {
    setState((s) => ({ ...s, type }));
  }, []);
  const setTime = useCallback((hour, minute) => {
    setState((s) => ({
      ...s,
      hour: Math.max(0, Math.min(23, hour)),
      minute: Math.max(0, Math.min(59, minute))
    }));
  }, []);
  const toggleWeekDay = useCallback((day) => {
    setState((s) => {
      const hasDay = s.weekDays.includes(day);
      if (hasDay && s.weekDays.length === 1) return s;
      const newDays = hasDay ? s.weekDays.filter((d) => d !== day) : [...s.weekDays, day];
      return {
        ...s,
        weekDays: newDays.sort((a, b) => a - b)
      };
    });
  }, []);
  const setWeekDays = useCallback((days) => {
    setState((s) => ({
      ...s,
      weekDays: days.length > 0 ? [...days].sort((a, b) => a - b) : [1]
      // Default to Monday if empty
    }));
  }, []);
  const toggleMonthDay = useCallback((day) => {
    setState((s) => {
      const hasDay = s.monthDays.includes(day);
      if (hasDay && s.monthDays.length === 1) return s;
      const newDays = hasDay ? s.monthDays.filter((d) => d !== day) : [...s.monthDays, day];
      return {
        ...s,
        monthDays: newDays.sort((a, b) => a - b)
      };
    });
  }, []);
  const setMonthDays = useCallback((days) => {
    setState((s) => ({
      ...s,
      monthDays: days.length > 0 ? [...days].sort((a, b) => a - b) : [1]
      // Default to 1st if empty
    }));
  }, []);
  const setCustomCron = useCallback((customCron) => {
    const parsed = parseCron(customCron);
    setState((s) => ({
      ...s,
      customCron,
      isValid: parsed !== null
    }));
  }, []);
  const reset = useCallback(() => {
    setState({ ...DEFAULT_STATE, type: defaultType });
  }, [defaultType]);
  const contextValue = useMemo(
    () => ({
      // State
      ...state,
      // Computed
      cronExpression,
      humanDescription,
      initialValue,
      // Actions
      setType,
      setTime,
      toggleWeekDay,
      setWeekDays,
      toggleMonthDay,
      setMonthDays,
      setCustomCron,
      reset
    }),
    [
      state,
      cronExpression,
      humanDescription,
      initialValue,
      setType,
      setTime,
      toggleWeekDay,
      setWeekDays,
      toggleMonthDay,
      setMonthDays,
      setCustomCron,
      reset
    ]
  );
  return /* @__PURE__ */ jsx(CronSchedulerContext.Provider, { value: contextValue, children });
}
__name(CronSchedulerProvider, "CronSchedulerProvider");
function useCronSchedulerContext() {
  const context = useContext(CronSchedulerContext);
  if (!context) {
    throw new Error(
      "useCronSchedulerContext must be used within CronSchedulerProvider"
    );
  }
  return context;
}
__name(useCronSchedulerContext, "useCronSchedulerContext");
function useCronType() {
  const { type, setType } = useCronSchedulerContext();
  return useMemo(() => ({ type, setType }), [type, setType]);
}
__name(useCronType, "useCronType");
function useCronTime() {
  const { hour, minute, setTime } = useCronSchedulerContext();
  return useMemo(() => ({ hour, minute, setTime }), [hour, minute, setTime]);
}
__name(useCronTime, "useCronTime");
function useCronWeekDays() {
  const { weekDays, toggleWeekDay, setWeekDays } = useCronSchedulerContext();
  return useMemo(
    () => ({ weekDays, toggleWeekDay, setWeekDays }),
    [weekDays, toggleWeekDay, setWeekDays]
  );
}
__name(useCronWeekDays, "useCronWeekDays");
function useCronMonthDays() {
  const { monthDays, toggleMonthDay, setMonthDays } = useCronSchedulerContext();
  return useMemo(
    () => ({ monthDays, toggleMonthDay, setMonthDays }),
    [monthDays, toggleMonthDay, setMonthDays]
  );
}
__name(useCronMonthDays, "useCronMonthDays");
function useCronCustom() {
  const { customCron, isValid, setCustomCron } = useCronSchedulerContext();
  return useMemo(
    () => ({ customCron, isValid, setCustomCron }),
    [customCron, isValid, setCustomCron]
  );
}
__name(useCronCustom, "useCronCustom");
function useCronPreview() {
  const { cronExpression, humanDescription, isValid, initialValue } = useCronSchedulerContext();
  return useMemo(
    () => ({ cronExpression, humanDescription, isValid, initialValue }),
    [cronExpression, humanDescription, isValid, initialValue]
  );
}
__name(useCronPreview, "useCronPreview");
function useCronScheduler() {
  return useCronSchedulerContext();
}
__name(useCronScheduler, "useCronScheduler");
var SCHEDULE_TYPES = [
  { value: "daily", label: "Daily" },
  { value: "weekly", label: "Weekly" },
  { value: "monthly", label: "Monthly" },
  { value: "custom", label: "Custom" }
];
function ScheduleTypeSelector({
  disabled,
  className
}) {
  const { type, setType } = useCronType();
  const triggerClassName = cn(
    "text-xs font-medium px-2 py-1.5",
    "data-[state=active]:shadow-sm",
    "transition-all duration-150"
  );
  const triggers = SCHEDULE_TYPES.map(({ value, label }) => ({
    value,
    label,
    disabled,
    className: triggerClassName
  }));
  return /* @__PURE__ */ jsx(
    Tabs,
    {
      value: type,
      onValueChange: (v) => setType(v),
      className: cn("w-full", className),
      children: /* @__PURE__ */ jsx(TabsList, { className: "grid w-full grid-cols-4 h-9 p-0.5", children: triggers.map((trigger) => /* @__PURE__ */ jsx(
        TabsTrigger,
        {
          value: trigger.value,
          disabled: trigger.disabled,
          className: trigger.className,
          children: trigger.label
        },
        trigger.value
      )) })
    }
  );
}
__name(ScheduleTypeSelector, "ScheduleTypeSelector");
var HOURS = Array.from({ length: 24 }, (_, i) => i);
var MINUTES = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
function TimeSelector({
  format = "24h",
  disabled,
  className
}) {
  const { hour, minute, setTime } = useCronTime();
  const is24h = format === "24h";
  const displayHour = is24h ? hour : hour % 12 || 12;
  const isPM = hour >= 12;
  const handleHourChange = /* @__PURE__ */ __name((value) => {
    let newHour = parseInt(value, 10);
    if (!is24h) {
      if (isPM && newHour !== 12) newHour += 12;
      else if (!isPM && newHour === 12) newHour = 0;
    }
    setTime(newHour, minute);
  }, "handleHourChange");
  const handleMinuteChange = /* @__PURE__ */ __name((value) => {
    setTime(hour, parseInt(value, 10));
  }, "handleMinuteChange");
  const handlePeriodChange = /* @__PURE__ */ __name((value) => {
    const newIsPM = value === "PM";
    let newHour = hour;
    if (newIsPM && hour < 12) newHour = hour + 12;
    else if (!newIsPM && hour >= 12) newHour = hour - 12;
    setTime(newHour, minute);
  }, "handlePeriodChange");
  const hours = is24h ? HOURS : Array.from({ length: 12 }, (_, i) => i + 1);
  return /* @__PURE__ */ jsxs("div", { className: cn("flex items-center gap-3", className), children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-muted-foreground", children: [
      /* @__PURE__ */ jsx(Clock, { className: "h-4 w-4" }),
      /* @__PURE__ */ jsx("span", { className: "text-sm", children: "Run at" })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5 flex-1", children: [
      /* @__PURE__ */ jsxs(
        Select,
        {
          value: displayHour.toString(),
          onValueChange: handleHourChange,
          disabled,
          children: [
            /* @__PURE__ */ jsx(SelectTrigger, { className: "w-[70px] h-9", children: /* @__PURE__ */ jsx(SelectValue, { children: displayHour.toString().padStart(2, "0") }) }),
            /* @__PURE__ */ jsx(SelectContent, { className: "max-h-48", children: hours.map((h) => /* @__PURE__ */ jsx(SelectItem, { value: h.toString(), children: h.toString().padStart(2, "0") }, h)) })
          ]
        }
      ),
      /* @__PURE__ */ jsx("span", { className: "text-muted-foreground font-medium", children: ":" }),
      /* @__PURE__ */ jsxs(
        Select,
        {
          value: minute.toString(),
          onValueChange: handleMinuteChange,
          disabled,
          children: [
            /* @__PURE__ */ jsx(SelectTrigger, { className: "w-[70px] h-9", children: /* @__PURE__ */ jsx(SelectValue, { children: minute.toString().padStart(2, "0") }) }),
            /* @__PURE__ */ jsx(SelectContent, { className: "max-h-48", children: MINUTES.map((m) => /* @__PURE__ */ jsx(SelectItem, { value: m.toString(), children: m.toString().padStart(2, "0") }, m)) })
          ]
        }
      ),
      !is24h && /* @__PURE__ */ jsxs(
        Select,
        {
          value: isPM ? "PM" : "AM",
          onValueChange: handlePeriodChange,
          disabled,
          children: [
            /* @__PURE__ */ jsx(SelectTrigger, { className: "w-[70px] h-9", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
            /* @__PURE__ */ jsxs(SelectContent, { children: [
              /* @__PURE__ */ jsx(SelectItem, { value: "AM", children: "AM" }),
              /* @__PURE__ */ jsx(SelectItem, { value: "PM", children: "PM" })
            ] })
          ]
        }
      )
    ] })
  ] });
}
__name(TimeSelector, "TimeSelector");
var DAYS = [
  { value: 1, label: "Mon" },
  { value: 2, label: "Tue" },
  { value: 3, label: "Wed" },
  { value: 4, label: "Thu" },
  { value: 5, label: "Fri" },
  { value: 6, label: "Sat" },
  { value: 0, label: "Sun" }
];
function DayChips({
  disabled,
  showPresets = true,
  className
}) {
  const { weekDays, toggleWeekDay, setWeekDays } = useCronWeekDays();
  const safeWeekDays = Array.isArray(weekDays) ? weekDays : [];
  const isWeekdays2 = safeWeekDays.length === 5 && [1, 2, 3, 4, 5].every((d) => safeWeekDays.includes(d));
  const isWeekendPreset = safeWeekDays.length === 2 && [0, 6].every((d) => safeWeekDays.includes(d));
  const isEveryday = safeWeekDays.length === 7;
  const dayButtons = DAYS.map(({ value, label }) => {
    const isSelected = safeWeekDays.includes(value);
    const isWeekendDay = value === 0 || value === 6;
    return {
      value,
      label,
      isSelected,
      isWeekendDay,
      className: cn(
        "flex flex-col items-center justify-center",
        "py-2.5 rounded-lg text-xs font-medium",
        "transition-all duration-150",
        "focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",
        "active:scale-[0.97]",
        isSelected ? "bg-primary text-primary-foreground shadow-sm" : cn(
          "bg-muted/50 hover:bg-muted",
          isWeekendDay ? "text-muted-foreground/70" : "text-muted-foreground"
        ),
        disabled && "opacity-50 cursor-not-allowed pointer-events-none"
      )
    };
  });
  const presets = [
    { label: "Weekdays", isActive: isWeekdays2, days: [1, 2, 3, 4, 5] },
    { label: "Weekends", isActive: isWeekendPreset, days: [0, 6] },
    { label: "Every day", isActive: isEveryday, days: [0, 1, 2, 3, 4, 5, 6] }
  ];
  return /* @__PURE__ */ jsxs("div", { className: cn("space-y-3", className), children: [
    /* @__PURE__ */ jsx("div", { className: "grid grid-cols-7 gap-1", children: dayButtons.map((day) => /* @__PURE__ */ jsx(
      "button",
      {
        type: "button",
        disabled,
        onClick: () => toggleWeekDay(day.value),
        "aria-pressed": day.isSelected,
        className: day.className,
        children: /* @__PURE__ */ jsx("span", { children: day.label })
      },
      day.value
    )) }),
    showPresets && /* @__PURE__ */ jsx("div", { className: "flex gap-2", children: presets.map((preset) => /* @__PURE__ */ jsx(
      PresetButton,
      {
        label: preset.label,
        isActive: preset.isActive,
        onClick: () => setWeekDays(preset.days),
        disabled
      },
      preset.label
    )) })
  ] });
}
__name(DayChips, "DayChips");
function PresetButton({ label, isActive, onClick, disabled }) {
  return /* @__PURE__ */ jsx(
    "button",
    {
      type: "button",
      disabled,
      onClick,
      className: cn(
        "flex-1 px-3 py-1.5 rounded-md text-xs font-medium",
        "transition-colors duration-150",
        "focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",
        isActive ? "bg-primary/15 text-primary border border-primary/30" : "bg-muted/30 text-muted-foreground hover:bg-muted/50 border border-transparent",
        disabled && "opacity-50 cursor-not-allowed"
      ),
      children: label
    }
  );
}
__name(PresetButton, "PresetButton");
Array.from({ length: 31 }, (_, i) => i + 1);
var GRID_SIZE = 35;
function MonthDayGrid({
  disabled,
  showPresets = true,
  className
}) {
  const { monthDays, toggleMonthDay, setMonthDays } = useCronMonthDays();
  const safeMonthDays = Array.isArray(monthDays) ? monthDays : [];
  const is1st = safeMonthDays.length === 1 && safeMonthDays[0] === 1;
  const is15th = safeMonthDays.length === 1 && safeMonthDays[0] === 15;
  const is1stAnd15th = safeMonthDays.length === 2 && safeMonthDays.includes(1) && safeMonthDays.includes(15);
  const presets = [
    { label: "1st", isActive: is1st, days: [1] },
    { label: "15th", isActive: is15th, days: [15] },
    { label: "1st & 15th", isActive: is1stAnd15th, days: [1, 15] }
  ];
  const gridCells = Array.from({ length: GRID_SIZE }, (_, i) => {
    const day = i + 1;
    const isValidDay = day <= 31;
    const isSelected = isValidDay && safeMonthDays.includes(day);
    const isPartialMonth = day > 28;
    if (!isValidDay) {
      return { type: "empty", key: i };
    }
    return {
      type: "day",
      key: day,
      day,
      isSelected,
      className: cn(
        "aspect-square flex items-center justify-center",
        "rounded-lg text-sm font-medium",
        "transition-all duration-150",
        "focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",
        "active:scale-[0.95]",
        isSelected ? "bg-primary text-primary-foreground shadow-sm" : cn(
          "bg-muted/30 hover:bg-muted/60",
          isPartialMonth ? "text-muted-foreground/50" : "text-muted-foreground"
        ),
        disabled && "opacity-50 cursor-not-allowed pointer-events-none"
      )
    };
  });
  const selectionCount = safeMonthDays.length;
  return /* @__PURE__ */ jsxs("div", { className: cn("space-y-3", className), children: [
    showPresets && /* @__PURE__ */ jsx("div", { className: "flex gap-2", children: presets.map((preset) => /* @__PURE__ */ jsx(
      PresetButton2,
      {
        label: preset.label,
        isActive: preset.isActive,
        onClick: () => setMonthDays(preset.days),
        disabled
      },
      preset.label
    )) }),
    /* @__PURE__ */ jsx("div", { className: "grid grid-cols-7 gap-1", children: gridCells.map((cell) => {
      if (cell.type === "empty") {
        return /* @__PURE__ */ jsx("div", { className: "aspect-square" }, cell.key);
      }
      return /* @__PURE__ */ jsx(
        "button",
        {
          type: "button",
          disabled,
          onClick: () => toggleMonthDay(cell.day),
          "aria-pressed": cell.isSelected,
          "aria-label": `Day ${cell.day}`,
          className: cell.className,
          children: cell.day
        },
        cell.key
      );
    }) }),
    selectionCount > 1 && /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground text-center", children: [
      selectionCount,
      " days selected"
    ] })
  ] });
}
__name(MonthDayGrid, "MonthDayGrid");
function PresetButton2({ label, isActive, onClick, disabled }) {
  return /* @__PURE__ */ jsx(
    "button",
    {
      type: "button",
      disabled,
      onClick,
      className: cn(
        "flex-1 px-3 py-1.5 rounded-md text-xs font-medium",
        "transition-colors duration-150",
        "focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",
        isActive ? "bg-primary/15 text-primary border border-primary/30" : "bg-muted/30 text-muted-foreground hover:bg-muted/50 border border-transparent",
        disabled && "opacity-50 cursor-not-allowed"
      ),
      children: label
    }
  );
}
__name(PresetButton2, "PresetButton");
function CustomInput({ disabled, className }) {
  const { customCron, isValid, setCustomCron } = useCronCustom();
  const [localValue, setLocalValue] = useState(customCron);
  const [localValid, setLocalValid] = useState(isValid);
  useEffect(() => {
    setLocalValue(customCron);
    setLocalValid(isValid);
  }, [customCron, isValid]);
  const handleChange = /* @__PURE__ */ __name((e) => {
    const value = e.target.value;
    setLocalValue(value);
    const valid = isValidCron(value);
    setLocalValid(valid);
    setCustomCron(value);
  }, "handleChange");
  return /* @__PURE__ */ jsxs("div", { className: cn("space-y-2", className), children: [
    /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: "Cron expression" }),
    /* @__PURE__ */ jsxs("div", { className: "relative", children: [
      /* @__PURE__ */ jsx(
        Input,
        {
          type: "text",
          value: localValue,
          onChange: handleChange,
          disabled,
          placeholder: "* * * * *",
          className: cn(
            "font-mono text-base pr-10 h-11",
            !localValid && localValue.trim() && "border-destructive focus-visible:ring-destructive/50"
          )
        }
      ),
      /* @__PURE__ */ jsx("div", { className: "absolute right-3 top-1/2 -translate-y-1/2", children: localValue.trim() && (localValid ? /* @__PURE__ */ jsx(CheckCircle2, { className: "h-5 w-5 text-green-500" }) : /* @__PURE__ */ jsx(AlertCircle, { className: "h-5 w-5 text-destructive" })) })
    ] })
  ] });
}
__name(CustomInput, "CustomInput");
function CronCheatsheet({ className }) {
  return /* @__PURE__ */ jsxs(Popover, { children: [
    /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
      "button",
      {
        type: "button",
        className: cn(
          "p-1 rounded hover:bg-muted/50 transition-colors",
          className
        ),
        "aria-label": "Cron syntax help",
        children: /* @__PURE__ */ jsx(HelpCircle, { className: "h-4 w-4 text-muted-foreground" })
      }
    ) }),
    /* @__PURE__ */ jsx(PopoverContent, { className: "w-72 p-3", align: "end", children: /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsx("p", { className: "font-medium text-sm", children: "Cron Format" }),
      /* @__PURE__ */ jsx("code", { className: "block text-xs bg-muted px-2 py-1.5 rounded font-mono text-center", children: "min hour day month weekday" }),
      /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-x-4 gap-y-1 text-xs", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
          /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "minute" }),
          /* @__PURE__ */ jsx("span", { children: "0-59" })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
          /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "hour" }),
          /* @__PURE__ */ jsx("span", { children: "0-23" })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
          /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "day" }),
          /* @__PURE__ */ jsx("span", { children: "1-31" })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
          /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "month" }),
          /* @__PURE__ */ jsx("span", { children: "1-12" })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex justify-between col-span-2", children: [
          /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "weekday" }),
          /* @__PURE__ */ jsx("span", { children: "0-6 (Sun-Sat)" })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "pt-2 border-t border-border space-y-1.5", children: [
        /* @__PURE__ */ jsx("p", { className: "text-xs font-medium", children: "Special characters" }),
        /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-1.5 text-xs", children: [
          /* @__PURE__ */ jsxs("span", { children: [
            /* @__PURE__ */ jsx("code", { className: "bg-muted px-1 rounded", children: "*" }),
            " any value"
          ] }),
          /* @__PURE__ */ jsxs("span", { children: [
            /* @__PURE__ */ jsx("code", { className: "bg-muted px-1 rounded", children: "," }),
            " list (1,3,5)"
          ] }),
          /* @__PURE__ */ jsxs("span", { children: [
            /* @__PURE__ */ jsx("code", { className: "bg-muted px-1 rounded", children: "-" }),
            " range (1-5)"
          ] }),
          /* @__PURE__ */ jsxs("span", { children: [
            /* @__PURE__ */ jsx("code", { className: "bg-muted px-1 rounded", children: "/" }),
            " step (*/15)"
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "pt-2 border-t border-border space-y-1.5", children: [
        /* @__PURE__ */ jsx("p", { className: "text-xs font-medium", children: "Examples" }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-1 text-xs", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex justify-between font-mono", children: [
            /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "0 9 * * *" }),
            /* @__PURE__ */ jsx("span", { children: "daily at 9am" })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex justify-between font-mono", children: [
            /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "0 9 * * 1-5" }),
            /* @__PURE__ */ jsx("span", { children: "weekdays 9am" })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex justify-between font-mono", children: [
            /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "*/15 * * * *" }),
            /* @__PURE__ */ jsx("span", { children: "every 15 min" })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex justify-between font-mono", children: [
            /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "0 0 1 * *" }),
            /* @__PURE__ */ jsx("span", { children: "1st of month" })
          ] })
        ] })
      ] })
    ] }) })
  ] });
}
__name(CronCheatsheet, "CronCheatsheet");
function SchedulePreview({
  showCronExpression = true,
  allowCopy = false,
  showInitialValue = true,
  className
}) {
  const { cronExpression, humanDescription, isValid, initialValue } = useCronPreview();
  const hasChanged = useMemo(
    () => showInitialValue && initialValue && initialValue !== cronExpression,
    [showInitialValue, initialValue, cronExpression]
  );
  const [copied, setCopied] = useState(false);
  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(cronExpression);
      setCopied(true);
      setTimeout(() => setCopied(false), 2e3);
    } catch (err) {
      console.error("Failed to copy:", err);
    }
  }, [cronExpression]);
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: cn(
        "px-3 py-2.5 rounded-lg border",
        "bg-muted/30 border-border/50",
        !isValid && "border-destructive/30 bg-destructive/5",
        className
      ),
      children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 min-w-0", children: [
            /* @__PURE__ */ jsx(
              Calendar,
              {
                className: cn(
                  "h-4 w-4 shrink-0",
                  isValid ? "text-primary" : "text-destructive"
                )
              }
            ),
            /* @__PURE__ */ jsx(
              "span",
              {
                className: cn(
                  "text-sm",
                  isValid ? "text-foreground" : "text-destructive"
                ),
                children: humanDescription
              }
            )
          ] }),
          allowCopy && /* @__PURE__ */ jsx(
            "button",
            {
              type: "button",
              onClick: handleCopy,
              disabled: !isValid,
              className: cn(
                "p-1 rounded transition-colors duration-150",
                "hover:bg-muted focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",
                "disabled:opacity-50 disabled:cursor-not-allowed"
              ),
              title: copied ? "Copied!" : "Copy cron expression",
              children: copied ? /* @__PURE__ */ jsx(Check, { className: "h-3.5 w-3.5 text-green-500" }) : /* @__PURE__ */ jsx(Copy, { className: "h-3.5 w-3.5 text-muted-foreground" })
            }
          )
        ] }),
        showCronExpression && /* @__PURE__ */ jsxs("div", { className: "mt-1.5 pt-1.5 border-t border-border/30 flex items-center justify-between", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5 min-w-0", children: [
            hasChanged && /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx("code", { className: "text-xs font-mono text-muted-foreground/60 line-through", children: initialValue }),
              /* @__PURE__ */ jsx(ArrowRight, { className: "h-3 w-3 text-muted-foreground/40 shrink-0" })
            ] }),
            /* @__PURE__ */ jsx("code", { className: "text-xs font-mono text-muted-foreground", children: cronExpression })
          ] }),
          /* @__PURE__ */ jsx(CronCheatsheet, {})
        ] })
      ]
    }
  );
}
__name(SchedulePreview, "SchedulePreview");

export { CronSchedulerProvider, CustomInput, DayChips, MonthDayGrid, SchedulePreview, ScheduleTypeSelector, TimeSelector, buildCron, humanizeCron, isValidCron, parseCron, useCronCustom, useCronMonthDays, useCronPreview, useCronScheduler, useCronSchedulerContext, useCronTime, useCronType, useCronWeekDays };
//# sourceMappingURL=chunk-PVAX67JG.mjs.map
//# sourceMappingURL=chunk-PVAX67JG.mjs.map