import { jsxs, jsx } from "react/jsx-runtime";
import * as React from "react";
import { ScrollArea } from "../ScrollArea/scroll-area.js";
import { cn } from "../../lib/utils.js";
function isoToTimeParts(iso) {
  if (!iso) return void 0;
  const timeMatch = iso.match(/(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?/);
  if (!timeMatch) return void 0;
  const h = Number(timeMatch[1]);
  const m = Number(timeMatch[2]);
  const s = timeMatch[3] !== void 0 ? Number(timeMatch[3]) : 0;
  if (Number.isNaN(h) || h < 0 || h > 23 || Number.isNaN(m) || m < 0 || m > 59 || Number.isNaN(s) || s < 0 || s > 59) return void 0;
  return { hours: h, minutes: m, seconds: s };
}
function timePartsToString(parts, showSeconds = false) {
  const hh = String(parts.hours).padStart(2, "0");
  const mm = String(parts.minutes).padStart(2, "0");
  if (!showSeconds) return `${hh}:${mm}`;
  const ss = String(parts.seconds).padStart(2, "0");
  return `${hh}:${mm}:${ss}`;
}
function buildRange(max, step) {
  const arr = [];
  for (let v = 0; v < max; v += step) arr.push(v);
  return arr;
}
function TimeColumn({ values, selected, disabledSet, label, onSelect, withDivider }) {
  const listRef = React.useRef(null);
  const isFirstRunRef = React.useRef(true);
  React.useEffect(() => {
    const list = listRef.current;
    if (!list) return;
    const idx = values.indexOf(selected);
    if (idx < 0) return;
    const item = list.children[idx];
    if (!item) return;
    item.scrollIntoView({ block: "center", behavior: isFirstRunRef.current ? "auto" : "smooth" });
    isFirstRunRef.current = false;
  }, [values, selected]);
  const handleKeyDown = (e) => {
    const idx = values.indexOf(selected);
    if (e.key === "ArrowDown") {
      e.preventDefault();
      const next = values.find((_, i) => i > idx && !(disabledSet == null ? void 0 : disabledSet.has(values[i]))) ?? values[idx];
      onSelect(next);
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      let i = idx - 1;
      while (i >= 0 && (disabledSet == null ? void 0 : disabledSet.has(values[i]))) i--;
      if (i >= 0) onSelect(values[i]);
    } else if (e.key === "Home") {
      e.preventDefault();
      const first = values.find((v) => !(disabledSet == null ? void 0 : disabledSet.has(v)));
      if (first !== void 0) onSelect(first);
    } else if (e.key === "End") {
      e.preventDefault();
      for (let i = values.length - 1; i >= 0; i--) {
        if (!(disabledSet == null ? void 0 : disabledSet.has(values[i]))) {
          onSelect(values[i]);
          break;
        }
      }
    }
  };
  return /* @__PURE__ */ jsx(ScrollArea, { className: cn("flex-1 h-full", withDivider && "border-r border-divider"), children: /* @__PURE__ */ jsx(
    "div",
    {
      ref: listRef,
      role: "listbox",
      "aria-label": label,
      tabIndex: 0,
      onKeyDown: handleKeyDown,
      className: "flex flex-col py-2 focus-visible:outline-2 focus-visible:outline-ring focus-visible:outline-offset-[-2px]",
      children: values.map((v) => {
        const isSelected = v === selected;
        const isDisabled = (disabledSet == null ? void 0 : disabledSet.has(v)) ?? false;
        return /* @__PURE__ */ jsx(
          "button",
          {
            type: "button",
            role: "option",
            "aria-selected": isSelected,
            disabled: isDisabled,
            tabIndex: -1,
            onClick: () => onSelect(v),
            className: cn(
              "w-full h-field-sm text-body tabular-nums",
              "flex items-center justify-center",
              "cursor-pointer transition-colors",
              "hover:bg-neutral-hover",
              isSelected && "bg-neutral-selected text-foreground hover:bg-neutral-selected",
              isDisabled && "text-fg-disabled cursor-not-allowed hover:bg-transparent"
            ),
            children: String(v).padStart(2, "0")
          },
          v
        );
      })
    }
  ) });
}
function TimeColumns({
  value,
  onChange,
  showSeconds = false,
  minuteStep = 1,
  secondStep = 1,
  disabled,
  className,
  leadingDivider = false
}) {
  const safeValue = value ?? { hours: 0, minutes: 0, seconds: 0 };
  const hourValues = React.useMemo(() => buildRange(24, 1), []);
  const minuteValues = React.useMemo(() => buildRange(60, minuteStep), [minuteStep]);
  const secondValues = React.useMemo(() => buildRange(60, secondStep), [secondStep]);
  const disabledSets = React.useMemo(() => ({
    hours: (disabled == null ? void 0 : disabled.hours) ? new Set(disabled.hours) : void 0,
    minutes: (disabled == null ? void 0 : disabled.minutes) ? new Set(disabled.minutes) : void 0,
    seconds: (disabled == null ? void 0 : disabled.seconds) ? new Set(disabled.seconds) : void 0
  }), [disabled == null ? void 0 : disabled.hours, disabled == null ? void 0 : disabled.minutes, disabled == null ? void 0 : disabled.seconds]);
  const widthClass = showSeconds ? "w-60" : "w-40";
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: cn(
        "flex flex-row",
        widthClass,
        leadingDivider && "border-l border-divider",
        className
      ),
      children: [
        /* @__PURE__ */ jsx(
          TimeColumn,
          {
            values: hourValues,
            selected: safeValue.hours,
            disabledSet: disabledSets.hours,
            label: "hours",
            onSelect: (h) => onChange({ ...safeValue, hours: h }),
            withDivider: true
          }
        ),
        /* @__PURE__ */ jsx(
          TimeColumn,
          {
            values: minuteValues,
            selected: safeValue.minutes,
            disabledSet: disabledSets.minutes,
            label: "minutes",
            onSelect: (m) => onChange({ ...safeValue, minutes: m }),
            withDivider: showSeconds
          }
        ),
        showSeconds && /* @__PURE__ */ jsx(
          TimeColumn,
          {
            values: secondValues,
            selected: safeValue.seconds,
            disabledSet: disabledSets.seconds,
            label: "seconds",
            onSelect: (s) => onChange({ ...safeValue, seconds: s })
          }
        )
      ]
    }
  );
}
export {
  TimeColumns,
  isoToTimeParts,
  timePartsToString
};
//# sourceMappingURL=time-columns.js.map
