"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Check, ChevronLeft, ChevronRight, Clock, X } from "lucide-react";
import { cva } from "class-variance-authority";
import { cn } from "@open-mercato/shared/lib/utils";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "./button.js";
import { Popover, PopoverContent, PopoverTrigger } from "./popover.js";
function padTwo(input) {
  return String(input).padStart(2, "0");
}
function parseTime(value) {
  if (!value) return null;
  const parts = value.split(":");
  if (parts.length < 2) return null;
  const hour = parseInt(parts[0] ?? "0", 10);
  const minute = parseInt(parts[1] ?? "0", 10);
  if (!Number.isFinite(hour) || !Number.isFinite(minute)) return null;
  return {
    hour: Math.max(0, Math.min(23, hour)),
    minute: Math.max(0, Math.min(59, minute))
  };
}
function formatSlotDisplay(value, format) {
  const parsed = parseTime(value);
  if (!parsed) return { main: value, suffix: null };
  if (format === "24h") {
    return { main: `${padTwo(parsed.hour)}:${padTwo(parsed.minute)}`, suffix: null };
  }
  const hour12 = parsed.hour === 0 ? 12 : parsed.hour > 12 ? parsed.hour - 12 : parsed.hour;
  const suffix = parsed.hour < 12 ? "AM" : "PM";
  return { main: `${padTwo(hour12)}:${padTwo(parsed.minute)}`, suffix };
}
function generateSlots(startTime, endTime, intervalMinutes) {
  const start = parseTime(startTime);
  const end = parseTime(endTime);
  if (!start || !end) return [];
  const step = intervalMinutes > 0 ? intervalMinutes : 30;
  const out = [];
  const startTotal = start.hour * 60 + start.minute;
  const endTotal = end.hour * 60 + end.minute;
  if (endTotal < startTotal) return [];
  for (let m = startTotal; m <= endTotal; m += step) {
    const h = Math.floor(m / 60);
    const min = m % 60;
    out.push(`${padTwo(h)}:${padTwo(min)}`);
  }
  return out;
}
function formatTimePickerDisplay(value, format = "12h") {
  return formatSlotDisplay(value, format);
}
function formatDuration(minutes, options) {
  const short = options?.short ?? true;
  if (!Number.isFinite(minutes) || minutes <= 0) return short ? "0 min" : "0 minutes";
  if (minutes < 60) return short ? `${minutes} min` : `${minutes} minutes`;
  if (minutes % (24 * 60) === 0) {
    const days = minutes / (24 * 60);
    return short ? days === 1 ? "1 day" : `${days} days` : days === 1 ? "1 day" : `${days} days`;
  }
  if (minutes % 60 === 0) {
    const hours2 = minutes / 60;
    return short ? hours2 === 1 ? "1 hour" : `${hours2} hours` : hours2 === 1 ? "1 hour" : `${hours2} hours`;
  }
  const hours = Math.floor(minutes / 60);
  const rest = minutes - hours * 60;
  return short ? `${hours}h ${rest}m` : `${hours} hour${hours === 1 ? "" : "s"} ${rest} minute${rest === 1 ? "" : "s"}`;
}
const defaultStatusLabels = {
  available: "Available",
  busy: "Busy",
  "in-meeting": "In meeting",
  offline: "Offline"
};
const statusColorMap = {
  available: {
    dot: "bg-status-success-icon",
    bgSoft: "bg-status-success-bg",
    border: "border-status-success-border",
    text: "text-status-success-text"
  },
  busy: {
    dot: "bg-status-error-icon",
    bgSoft: "bg-status-error-bg",
    border: "border-status-error-border",
    text: "text-status-error-text"
  },
  "in-meeting": {
    dot: "bg-status-warning-icon",
    bgSoft: "bg-status-warning-bg",
    border: "border-status-warning-border",
    text: "text-status-warning-text"
  },
  offline: {
    dot: "bg-muted-foreground",
    bgSoft: "bg-muted",
    border: "border-border",
    text: "text-muted-foreground"
  }
};
const slotVariants = cva(
  "flex h-9 w-full items-center gap-2.5 rounded-md px-3 py-2 text-sm font-medium transition-colors text-left",
  {
    variants: {
      state: {
        default: "bg-background hover:bg-muted/50 text-muted-foreground cursor-pointer",
        hover: "bg-muted/50 text-muted-foreground cursor-pointer",
        active: "bg-brand-violet/10 text-brand-violet cursor-pointer",
        disabled: "bg-background text-muted-foreground/40 cursor-not-allowed"
      }
    },
    defaultVariants: { state: "default" }
  }
);
const TimePickerSlot = React.forwardRef(
  ({
    value,
    label,
    rightText,
    state,
    selected,
    disabled,
    format = "12h",
    onSelect,
    className,
    "aria-label": ariaLabel
  }, ref) => {
    const effectiveState = disabled ? "disabled" : selected ? "active" : state ?? "default";
    const display = label != null ? { main: label, suffix: null } : formatSlotDisplay(value, format);
    const right = rightText ? formatSlotDisplay(rightText, format) : null;
    const isInteractive = effectiveState !== "disabled";
    return /* @__PURE__ */ jsxs(
      "button",
      {
        ref,
        type: "button",
        className: cn(slotVariants({ state: effectiveState }), className),
        onClick: isInteractive ? () => onSelect?.(value) : void 0,
        disabled: !isInteractive,
        "aria-label": ariaLabel ?? value,
        "aria-pressed": effectiveState === "active",
        "data-slot": "time-picker-slot",
        "data-state": effectiveState,
        children: [
          /* @__PURE__ */ jsxs("span", { className: "flex min-w-0 flex-1 items-center gap-1", children: [
            /* @__PURE__ */ jsx("span", { children: display.main }),
            display.suffix ? /* @__PURE__ */ jsx("span", { className: effectiveState === "active" ? "text-brand-violet/60" : "text-muted-foreground/60", children: display.suffix }) : null
          ] }),
          right ? /* @__PURE__ */ jsxs("span", { className: "flex min-w-0 items-center justify-end gap-1", children: [
            /* @__PURE__ */ jsx("span", { children: right.main }),
            right.suffix ? /* @__PURE__ */ jsx("span", { className: effectiveState === "active" ? "text-brand-violet/60" : "text-muted-foreground/60", children: right.suffix }) : null
          ] }) : null,
          effectiveState === "active" ? /* @__PURE__ */ jsx(Check, { className: "size-3.5 shrink-0 text-brand-violet", "aria-hidden": "true" }) : null
        ]
      }
    );
  }
);
TimePickerSlot.displayName = "TimePickerSlot";
const durationChipVariants = cva(
  "inline-flex h-7 items-center justify-center gap-1.5 rounded-lg px-2.5 text-sm font-medium transition-colors whitespace-nowrap",
  {
    variants: {
      state: {
        default: "bg-background border border-border shadow-xs text-muted-foreground hover:bg-muted/40 cursor-pointer",
        hover: "bg-muted/40 border border-border text-muted-foreground cursor-pointer",
        active: "bg-brand-violet/10 text-brand-violet cursor-pointer",
        disabled: "bg-background border border-border text-muted-foreground/40 cursor-not-allowed shadow-xs"
      }
    },
    defaultVariants: { state: "default" }
  }
);
const TimePickerDurationChip = React.forwardRef(
  ({ value, label, state, selected, disabled, onSelect, className }, ref) => {
    const effectiveState = disabled ? "disabled" : selected ? "active" : state ?? "default";
    const isInteractive = effectiveState !== "disabled";
    const displayLabel = label ?? formatDuration(value);
    return /* @__PURE__ */ jsxs(
      "button",
      {
        ref,
        type: "button",
        className: cn(durationChipVariants({ state: effectiveState }), className),
        onClick: isInteractive ? () => onSelect?.(value) : void 0,
        disabled: !isInteractive,
        "aria-pressed": effectiveState === "active",
        "data-slot": "time-picker-duration-chip",
        "data-state": effectiveState,
        children: [
          effectiveState === "active" ? /* @__PURE__ */ jsx(Check, { className: "size-3 shrink-0", "aria-hidden": "true" }) : null,
          /* @__PURE__ */ jsx("span", { children: displayLabel })
        ]
      }
    );
  }
);
TimePickerDurationChip.displayName = "TimePickerDurationChip";
const statusChipBaseVariants = cva(
  "inline-flex h-7 items-center justify-center gap-1.5 rounded-lg px-2.5 text-sm font-medium transition-colors whitespace-nowrap border",
  {
    variants: {
      state: {
        default: "",
        hover: "",
        selected: "",
        disabled: "cursor-not-allowed opacity-60"
      }
    },
    defaultVariants: { state: "default" }
  }
);
const TimePickerStatusChip = React.forwardRef(
  ({ variant, label, state, selected, disabled, icon, onSelect, className }, ref) => {
    const effectiveState = disabled ? "disabled" : selected ? "selected" : state ?? "default";
    const colors = statusColorMap[variant];
    const isInteractive = effectiveState !== "disabled";
    const displayLabel = label ?? defaultStatusLabels[variant];
    const stateClasses = effectiveState === "selected" ? cn(colors.bgSoft, colors.border, colors.text) : effectiveState === "hover" ? cn("bg-muted/30 border-border", colors.text, "cursor-pointer") : effectiveState === "disabled" ? cn("bg-background border-border", colors.text) : cn("bg-background border-border text-muted-foreground hover:bg-muted/30 cursor-pointer");
    return /* @__PURE__ */ jsxs(
      "button",
      {
        ref,
        type: "button",
        className: cn(statusChipBaseVariants({ state: effectiveState }), stateClasses, className),
        onClick: isInteractive ? () => onSelect?.(variant) : void 0,
        disabled: !isInteractive,
        "aria-pressed": effectiveState === "selected",
        "data-slot": "time-picker-status-chip",
        "data-state": effectiveState,
        "data-variant": variant,
        children: [
          icon ?? /* @__PURE__ */ jsx(
            "span",
            {
              className: cn("inline-block size-1.5 shrink-0 rounded-full", colors.dot),
              "aria-hidden": "true"
            }
          ),
          /* @__PURE__ */ jsx("span", { children: displayLabel })
        ]
      }
    );
  }
);
TimePickerStatusChip.displayName = "TimePickerStatusChip";
function HorizontalScrollRow({
  className,
  contentClassName,
  children,
  ariaLabel,
  arrowSize = "default",
  scrollLeftAriaLabel = "Scroll left",
  scrollRightAriaLabel = "Scroll right"
}) {
  const scrollRef = React.useRef(null);
  const [canScrollLeft, setCanScrollLeft] = React.useState(false);
  const [canScrollRight, setCanScrollRight] = React.useState(false);
  const refreshScrollState = React.useCallback(() => {
    const el = scrollRef.current;
    if (!el) return;
    const { scrollLeft, scrollWidth, clientWidth } = el;
    setCanScrollLeft(scrollLeft > 1);
    setCanScrollRight(scrollLeft + clientWidth < scrollWidth - 1);
  }, []);
  React.useEffect(() => {
    refreshScrollState();
    const el = scrollRef.current;
    if (!el) return;
    el.addEventListener("scroll", refreshScrollState, { passive: true });
    const ro = new ResizeObserver(refreshScrollState);
    ro.observe(el);
    return () => {
      el.removeEventListener("scroll", refreshScrollState);
      ro.disconnect();
    };
  }, [refreshScrollState]);
  const scrollBy = React.useCallback((direction) => {
    const el = scrollRef.current;
    if (!el) return;
    const amount = Math.max(80, Math.floor(el.clientWidth * 0.6));
    el.scrollBy({ left: direction === "left" ? -amount : amount, behavior: "smooth" });
  }, []);
  const arrowButtonClass = arrowSize === "sm" ? "size-6 [&_svg]:size-3.5" : "size-7 [&_svg]:size-4";
  return /* @__PURE__ */ jsxs("div", { className: cn("relative", className), "data-slot": "time-picker-scroll-row", children: [
    /* @__PURE__ */ jsx(
      "div",
      {
        className: cn(
          "transition-[padding]",
          canScrollLeft ? "pl-9" : "pl-4",
          canScrollRight ? "pr-9" : "pr-4"
        ),
        children: /* @__PURE__ */ jsx(
          "div",
          {
            ref: scrollRef,
            className: cn(
              "flex items-center gap-2 overflow-x-auto py-3.5",
              "[scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden",
              contentClassName
            ),
            role: "group",
            "aria-label": ariaLabel,
            children
          }
        )
      }
    ),
    canScrollLeft ? /* @__PURE__ */ jsx(
      "div",
      {
        "aria-hidden": "true",
        className: "pointer-events-none absolute inset-y-0 left-9 w-6 bg-gradient-to-r from-background to-transparent"
      }
    ) : null,
    canScrollRight ? /* @__PURE__ */ jsx(
      "div",
      {
        "aria-hidden": "true",
        className: "pointer-events-none absolute inset-y-0 right-9 w-6 bg-gradient-to-l from-background to-transparent"
      }
    ) : null,
    canScrollLeft ? /* @__PURE__ */ jsx(
      "button",
      {
        type: "button",
        onClick: () => scrollBy("left"),
        "aria-label": scrollLeftAriaLabel,
        className: cn(
          "absolute left-1 top-1/2 z-10 flex -translate-y-1/2 items-center justify-center rounded-full border border-border bg-background text-muted-foreground shadow-xs transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",
          arrowButtonClass
        ),
        "data-slot": "time-picker-scroll-left",
        children: /* @__PURE__ */ jsx(ChevronLeft, { "aria-hidden": "true" })
      }
    ) : null,
    canScrollRight ? /* @__PURE__ */ jsx(
      "button",
      {
        type: "button",
        onClick: () => scrollBy("right"),
        "aria-label": scrollRightAriaLabel,
        className: cn(
          "absolute right-1 top-1/2 z-10 flex -translate-y-1/2 items-center justify-center rounded-full border border-border bg-background text-muted-foreground shadow-xs transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",
          arrowButtonClass
        ),
        "data-slot": "time-picker-scroll-right",
        children: /* @__PURE__ */ jsx(ChevronRight, { "aria-hidden": "true" })
      }
    ) : null
  ] });
}
function useControllable(controlled, defaultValue, onChange) {
  const [internal, setInternal] = React.useState(defaultValue);
  const isControlled = controlled !== void 0;
  const value = isControlled ? controlled : internal;
  const setValue = React.useCallback(
    (next) => {
      if (!isControlled) setInternal(next);
      onChange?.(next);
    },
    [isControlled, onChange]
  );
  return [value, setValue];
}
function TimePickerCard({
  value,
  setValue,
  showHeader,
  headerIcon,
  headerTitle,
  headerPlaceholder,
  onClose,
  closeAriaLabel,
  format,
  durationOptions,
  activeDuration,
  setActiveDuration,
  onDurationChange,
  durationsAriaLabel,
  scrollLeftAriaLabel,
  scrollRightAriaLabel,
  statusOptions,
  activeStatus,
  setActiveStatus,
  onStatusChange,
  statusLabel,
  slotList,
  slotLabel,
  slotRightText,
  maxHeight,
  showFooter,
  cancelLabel,
  applyLabel,
  handleCancel,
  handleApply,
  legacyFooterActions,
  pinnedTopActions,
  disabled,
  className,
  ariaLabel,
  slotListRef
}) {
  const headerDisplay = React.useMemo(() => {
    if (headerTitle != null) return { main: headerTitle, suffix: null };
    if (value) return formatSlotDisplay(value, format);
    return { main: headerPlaceholder, suffix: null };
  }, [headerTitle, value, format, headerPlaceholder]);
  const handleSlotKeyDown = React.useCallback(
    (event) => {
      if (disabled) return;
      const target = event.target;
      const slotButton = target.closest('[data-slot="time-picker-slot"]');
      if (!slotButton) return;
      const container = slotListRef.current;
      if (!container) return;
      const all = Array.from(
        container.querySelectorAll('[data-slot="time-picker-slot"]:not(:disabled)')
      );
      const currentIndex = all.indexOf(slotButton);
      if (currentIndex === -1) return;
      if (event.key === "ArrowDown") {
        event.preventDefault();
        const next = all[Math.min(all.length - 1, currentIndex + 1)];
        next?.focus();
      } else if (event.key === "ArrowUp") {
        event.preventDefault();
        const prev = all[Math.max(0, currentIndex - 1)];
        prev?.focus();
      } else if (event.key === "Home") {
        event.preventDefault();
        all[0]?.focus();
      } else if (event.key === "End") {
        event.preventDefault();
        all[all.length - 1]?.focus();
      }
    },
    [disabled, slotListRef]
  );
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: cn(
        "flex w-[348px] flex-col overflow-hidden rounded-[20px] border border-border bg-background",
        "shadow-[0px_1px_2px_0px_rgba(10,13,20,0.03),0px_24px_24px_-12px_rgba(51,51,51,0.04),0px_12px_12px_-6px_rgba(51,51,51,0.04)]",
        className
      ),
      role: "dialog",
      "aria-label": ariaLabel,
      "aria-disabled": disabled || void 0,
      "data-slot": "time-picker",
      children: [
        showHeader ? /* @__PURE__ */ jsxs(
          "div",
          {
            className: "flex items-center gap-2 border-b border-border px-4 py-3.5",
            "data-slot": "time-picker-header",
            children: [
              /* @__PURE__ */ jsx("span", { className: "flex shrink-0 items-center text-muted-foreground", "aria-hidden": "true", children: headerIcon ?? /* @__PURE__ */ jsx(Clock, { className: "size-5", "aria-hidden": "true" }) }),
              /* @__PURE__ */ jsxs("p", { className: "flex-1 min-w-0 truncate text-base font-medium text-muted-foreground", children: [
                /* @__PURE__ */ jsx("span", { children: headerDisplay.main }),
                headerDisplay.suffix ? /* @__PURE__ */ jsx("span", { className: "ml-1 text-muted-foreground/60", children: headerDisplay.suffix }) : null
              ] }),
              onClose ? /* @__PURE__ */ jsx(
                "button",
                {
                  type: "button",
                  onClick: onClose,
                  disabled,
                  className: "inline-flex size-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring/40 disabled:pointer-events-none disabled:opacity-60",
                  "aria-label": closeAriaLabel,
                  "data-slot": "time-picker-close",
                  children: /* @__PURE__ */ jsx(X, { className: "size-4", "aria-hidden": "true" })
                }
              ) : null
            ]
          }
        ) : null,
        durationOptions && durationOptions.length > 0 ? /* @__PURE__ */ jsx(
          HorizontalScrollRow,
          {
            className: "border-b border-border",
            ariaLabel: durationsAriaLabel,
            scrollLeftAriaLabel,
            scrollRightAriaLabel,
            children: durationOptions.map((option) => /* @__PURE__ */ jsx(
              TimePickerDurationChip,
              {
                value: option.value,
                label: option.label,
                disabled: disabled || option.disabled,
                selected: activeDuration === option.value,
                onSelect: (next) => {
                  setActiveDuration(next);
                  onDurationChange?.(next);
                }
              },
              option.value
            ))
          }
        ) : null,
        statusOptions && statusOptions.length > 0 ? /* @__PURE__ */ jsxs(
          "div",
          {
            className: "flex flex-col gap-2 border-b border-border px-4 py-3.5",
            "data-slot": "time-picker-status-row",
            children: [
              /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-muted-foreground", children: statusLabel }),
              /* @__PURE__ */ jsx("div", { className: "flex flex-wrap items-center gap-2", children: statusOptions.map((option) => /* @__PURE__ */ jsx(
                TimePickerStatusChip,
                {
                  variant: option.variant,
                  label: option.label,
                  disabled: disabled || option.disabled,
                  selected: activeStatus === option.variant,
                  onSelect: (next) => {
                    setActiveStatus(next);
                    onStatusChange?.(next);
                  }
                },
                option.variant
              )) })
            ]
          }
        ) : null,
        pinnedTopActions && pinnedTopActions.length > 0 ? /* @__PURE__ */ jsx(
          "div",
          {
            className: "flex flex-col gap-0.5 border-b border-border p-2",
            "data-slot": "time-picker-pinned-top",
            children: pinnedTopActions.map((action) => /* @__PURE__ */ jsxs(
              "button",
              {
                type: "button",
                onClick: action.onClick,
                disabled,
                className: "flex h-9 w-full items-center gap-2.5 rounded-md px-3 py-2 text-sm font-medium text-brand-violet transition-colors hover:bg-brand-violet/10 cursor-pointer disabled:pointer-events-none disabled:opacity-60",
                "data-slot": "time-picker-pinned-action",
                children: [
                  action.icon ? /* @__PURE__ */ jsx("span", { className: "flex shrink-0 items-center [&_svg]:size-4", "aria-hidden": "true", children: action.icon }) : null,
                  /* @__PURE__ */ jsx("span", { className: "flex-1 text-left", children: action.label }),
                  action.rightText ? /* @__PURE__ */ jsx("span", { className: "text-brand-violet/60", children: action.rightText }) : null
                ]
              },
              action.label
            ))
          }
        ) : null,
        /* @__PURE__ */ jsxs(
          "div",
          {
            className: "flex flex-col gap-0.5 overflow-y-auto p-2",
            style: { maxHeight },
            ref: slotListRef,
            onKeyDown: handleSlotKeyDown,
            "data-slot": "time-picker-slots",
            children: [
              slotLabel ? /* @__PURE__ */ jsx("p", { className: "px-3 pt-1 pb-2 text-sm font-medium text-muted-foreground", children: slotLabel }) : null,
              slotList.length === 0 ? /* @__PURE__ */ jsx("p", { className: "px-3 py-4 text-center text-sm text-muted-foreground", children: "No time slots available." }) : slotList.map((slot) => /* @__PURE__ */ jsx(
                TimePickerSlot,
                {
                  value: slot,
                  format,
                  rightText: slotRightText?.(slot),
                  selected: value === slot,
                  disabled,
                  onSelect: (next) => setValue(next)
                },
                slot
              ))
            ]
          }
        ),
        showFooter ? /* @__PURE__ */ jsxs(
          "div",
          {
            className: "flex flex-wrap items-center justify-end gap-2 border-t border-border px-4 py-3",
            "data-slot": "time-picker-footer",
            children: [
              legacyFooterActions && legacyFooterActions.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "mr-auto flex items-center gap-1", children: [
                legacyFooterActions.map((action) => /* @__PURE__ */ jsx(
                  Button,
                  {
                    type: "button",
                    variant: action.variant === "muted" ? "muted" : "ghost",
                    size: "sm",
                    onClick: action.onClick,
                    disabled,
                    "data-slot": "time-picker-legacy-action",
                    children: action.label
                  },
                  action.label
                )),
                /* @__PURE__ */ jsx("span", { "aria-hidden": "true", className: "ml-2 mr-1 h-5 w-px bg-border" })
              ] }) : null,
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  variant: "outline",
                  size: "sm",
                  onClick: handleCancel,
                  disabled,
                  "data-slot": "time-picker-cancel",
                  children: cancelLabel
                }
              ),
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  variant: "default",
                  size: "sm",
                  onClick: handleApply,
                  disabled,
                  "data-slot": "time-picker-apply",
                  children: applyLabel
                }
              )
            ]
          }
        ) : null
      ]
    }
  );
}
function TimePicker({
  value: valueProp,
  defaultValue = null,
  onChange,
  showHeader = true,
  headerIcon,
  headerTitle,
  headerPlaceholder,
  onClose,
  durations,
  activeDuration: activeDurationProp,
  defaultActiveDuration,
  onDurationChange,
  statuses,
  activeStatus: activeStatusProp,
  defaultActiveStatus,
  onStatusChange,
  statusLabel,
  slots: slotsProp,
  startTime = "00:00",
  endTime = "23:30",
  intervalMinutes = 30,
  format = "12h",
  slotRightText,
  slotLabel,
  maxHeight = 280,
  showFooter = true,
  cancelLabel,
  applyLabel,
  onCancel,
  onApply,
  legacyFooterActions,
  pinnedTopActions,
  trigger,
  open: openProp,
  defaultOpen = false,
  onOpenChange,
  popoverAlign = "start",
  popoverSide = "bottom",
  className,
  disabled = false,
  "aria-label": ariaLabel
}) {
  const t = useT();
  const resolvedHeaderPlaceholder = headerPlaceholder ?? t("ui.timePicker.placeholder", "Pick a time");
  const resolvedStatusLabel = statusLabel ?? t("ui.timePicker.statusLabel", "Select status");
  const resolvedCancelLabel = cancelLabel ?? t("ui.timePicker.cancelButton", "Cancel");
  const resolvedApplyLabel = applyLabel ?? t("ui.timePicker.applyButton", "Apply");
  const resolvedAriaLabel = ariaLabel ?? t("ui.timePicker.label", "Time picker");
  const resolvedCloseAriaLabel = t("ui.timePicker.closeButton", "Close");
  const resolvedDurationsAriaLabel = t("ui.timePicker.durationsRowLabel", "Quick duration");
  const resolvedScrollLeftAriaLabel = t("ui.timePicker.scrollLeft", "Scroll left");
  const resolvedScrollRightAriaLabel = t("ui.timePicker.scrollRight", "Scroll right");
  const [value, setValue] = useControllable(valueProp, defaultValue, onChange);
  const [activeDuration, setActiveDuration] = useControllable(
    activeDurationProp,
    defaultActiveDuration
  );
  const [activeStatus, setActiveStatus] = useControllable(
    activeStatusProp,
    defaultActiveStatus
  );
  const [open, setOpen] = useControllable(openProp, defaultOpen, onOpenChange);
  const openSnapshotRef = React.useRef(value);
  const slotListRef = React.useRef(null);
  const slotList = React.useMemo(() => {
    if (slotsProp && slotsProp.length > 0) return slotsProp;
    return generateSlots(startTime, endTime, intervalMinutes);
  }, [slotsProp, startTime, endTime, intervalMinutes]);
  const setOpenWithSnapshot = React.useCallback(
    (next) => {
      if (next && !open) {
        openSnapshotRef.current = value;
      }
      setOpen(next);
    },
    [open, setOpen, value]
  );
  const handleApply = React.useCallback(() => {
    onApply?.(value);
    if (trigger) setOpenWithSnapshot(false);
  }, [onApply, setOpenWithSnapshot, trigger, value]);
  const handleCancel = React.useCallback(() => {
    onCancel?.();
    if (trigger) {
      setValue(openSnapshotRef.current);
      setOpenWithSnapshot(false);
    }
  }, [onCancel, setOpenWithSnapshot, setValue, trigger]);
  const handleKeyDown = React.useCallback(
    (event) => {
      if (event.key === "Escape") {
        handleCancel();
      } else if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();
        handleApply();
      }
    },
    [handleApply, handleCancel]
  );
  const card = /* @__PURE__ */ jsx("div", { onKeyDown: handleKeyDown, children: /* @__PURE__ */ jsx(
    TimePickerCard,
    {
      value,
      setValue,
      showHeader,
      headerIcon,
      headerTitle,
      headerPlaceholder: resolvedHeaderPlaceholder,
      onClose,
      closeAriaLabel: resolvedCloseAriaLabel,
      format,
      durationOptions: durations,
      activeDuration,
      setActiveDuration,
      onDurationChange,
      durationsAriaLabel: resolvedDurationsAriaLabel,
      scrollLeftAriaLabel: resolvedScrollLeftAriaLabel,
      scrollRightAriaLabel: resolvedScrollRightAriaLabel,
      statusOptions: statuses,
      activeStatus,
      setActiveStatus,
      onStatusChange,
      statusLabel: resolvedStatusLabel,
      slotList,
      slotLabel,
      slotRightText,
      maxHeight,
      showFooter,
      cancelLabel: resolvedCancelLabel,
      applyLabel: resolvedApplyLabel,
      handleCancel,
      handleApply,
      legacyFooterActions,
      pinnedTopActions,
      disabled,
      className,
      ariaLabel: resolvedAriaLabel,
      slotListRef
    }
  ) });
  if (!trigger) return card;
  return /* @__PURE__ */ jsxs(Popover, { open, onOpenChange: setOpenWithSnapshot, children: [
    /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: trigger }),
    /* @__PURE__ */ jsx(
      PopoverContent,
      {
        align: popoverAlign,
        side: popoverSide,
        className: "w-auto border-none bg-transparent p-0 shadow-none",
        children: card
      }
    )
  ] });
}
export {
  HorizontalScrollRow,
  TimePicker,
  TimePickerDurationChip,
  TimePickerSlot,
  TimePickerStatusChip,
  formatDuration,
  formatTimePickerDisplay
};
//# sourceMappingURL=time-picker.js.map
