'use strict';

var jsxRuntime = require('react/jsx-runtime');
var React = require('react');
var primitives_Popover = require('./primitives/Popover.js');
var primitives_Field = require('./primitives/Field.js');
var utils = require('./utils-BhM0B89p.js');
var TimePickerPanel = require('./TimePickerPanel-DnQUpCam.js');
var createLucideIcon = require('./createLucideIcon-D0tRgV6l.js');
var x = require('./x-Brw3FJst.js');

/**
 * @license lucide-react v0.577.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */


const __iconNode = [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["path", { d: "M12 6v6l4 2", key: "mmk7yg" }]
];
const Clock = createLucideIcon.createLucideIcon("clock", __iconNode);

const SIZE_CONFIG = {
  small: { trigger: "h-7 text-xs", icon: "size-3.5" },
  medium: { trigger: "h-8 text-sm", icon: "size-4" },
  large: { trigger: "h-10 text-sm", icon: "size-4" }
};
const TimePicker = React.forwardRef(
  ({
    value,
    onChange,
    format = "24",
    showSeconds = false,
    minuteStep = 1,
    secondStep = 1,
    disabled = false,
    placeholder,
    label,
    error,
    helpText,
    size = "medium",
    required = false,
    timezone,
    labelProps,
    className
  }, ref) => {
    const generatedId = React.useId();
    const errorId = `error_${generatedId}`;
    const helpTextId = `helpText_${generatedId}`;
    const containerRef = React.useRef(null);
    const inputRef = React.useRef(null);
    const cursorPosRef = React.useRef(null);
    const popoverContentId = React.useRef(
      `timepicker-popover-${generatedId}`
    ).current;
    const [open, setOpen] = React.useState(false);
    const getInitialTime = React.useCallback(() => {
      if (!value) return null;
      if (value instanceof Date) return TimePickerPanel.dateToTimeValue(value);
      const dayjsLike = value;
      if (typeof dayjsLike.hour === "function") {
        return {
          hours: dayjsLike.hour(),
          minutes: dayjsLike.minute(),
          seconds: dayjsLike.second?.() ?? 0
        };
      }
      if (typeof dayjsLike.toDate === "function") {
        return TimePickerPanel.dateToTimeValue(dayjsLike.toDate());
      }
      const timeValue = value;
      return {
        hours: timeValue.hours,
        minutes: timeValue.minutes,
        seconds: timeValue.seconds ?? 0
      };
    }, [value]);
    const [internalTime, setInternalTime] = React.useState(
      getInitialTime
    );
    const [inputText, setInputText] = React.useState("");
    const displayTime = React.useCallback(
      (time) => TimePickerPanel.formatTimeDisplay(time, format, showSeconds),
      [format, showSeconds]
    );
    React.useEffect(() => {
      const newTime = getInitialTime();
      setInternalTime(newTime);
      if (!open) setInputText(displayTime(newTime));
    }, [getInitialTime, displayTime, open]);
    React.useEffect(() => {
      if (!open) return;
      const handlePointerDown = (e) => {
        const target = e.target;
        if (containerRef.current?.contains(target)) return;
        const popoverEl = document.getElementById(popoverContentId);
        if (popoverEl?.contains(target)) return;
        setOpen(false);
        setInputText(displayTime(internalTime));
      };
      document.addEventListener("pointerdown", handlePointerDown);
      return () => document.removeEventListener("pointerdown", handlePointerDown);
    }, [open, internalTime, displayTime]);
    const maskFormatStr = React.useMemo(() => {
      if (format === "12") {
        return showSeconds ? "hh:mm:ss AA" : "hh:mm AA";
      }
      return showSeconds ? "HH:mm:ss" : "HH:mm";
    }, [format, showSeconds]);
    const maskTemplate = React.useMemo(
      () => TimePickerPanel.buildMaskTemplate(maskFormatStr),
      [maskFormatStr]
    );
    const defaultPlaceholder = showSeconds ? format === "12" ? "hh:mm:ss AA" : "HH:mm:ss" : format === "12" ? "hh:mm AA" : "HH:mm";
    const emitChange = (time) => {
      onChange?.(TimePickerPanel.timeValueToDayjs(time), displayTime(time));
    };
    const handlePanelChange = (time) => {
      setInternalTime(time);
      setInputText(displayTime(time));
      emitChange(time);
    };
    React.useLayoutEffect(() => {
      if (cursorPosRef.current !== null && inputRef.current && document.activeElement === inputRef.current) {
        inputRef.current.setSelectionRange(
          cursorPosRef.current,
          cursorPosRef.current
        );
        cursorPosRef.current = null;
      }
    });
    const handleInputChange = (e) => {
      const masked = TimePickerPanel.applyMask(
        e.target.value,
        maskTemplate,
        inputText,
        e.target.selectionStart
      );
      const text = masked.text;
      cursorPosRef.current = masked.cursorPosition;
      setInputText(text);
      const parsed = TimePickerPanel.parseTimeString(text, format);
      if (parsed) {
        setInternalTime(parsed);
        emitChange(parsed);
      }
    };
    const handleInputKeyDown = (e) => {
      if (e.key !== "Enter" && e.key !== "Escape") return;
      setInputText(displayTime(internalTime));
      setOpen(false);
    };
    const handleInputFocus = () => {
      if (!open) setOpen(true);
    };
    const handleClear = (e) => {
      e.stopPropagation();
      e.preventDefault();
      const cleared = { hours: 0, minutes: 0, seconds: 0 };
      setInternalTime(null);
      setInputText("");
      emitChange(cleared);
    };
    const hasField = !!(label || error || helpText);
    const sizeConfig = SIZE_CONFIG[size];
    const ariaDescribedBy = [error ? errorId : null, helpText ? helpTextId : null].filter(Boolean).join(" ") || void 0;
    const triggerContent = /* @__PURE__ */ jsxRuntime.jsxs(primitives_Popover.Popover, { open, children: [
      /* @__PURE__ */ jsxRuntime.jsx(primitives_Popover.PopoverAnchor, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsxs(
        "div",
        {
          ref: containerRef,
          className: utils.cn(
            "relative flex w-full items-center gap-2 rounded-md border border-input bg-background pe-8 ps-3",
            "focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",
            disabled && "cursor-not-allowed opacity-50",
            !!error && "border-destructive ring-destructive/20 ring-3",
            sizeConfig.trigger,
            !hasField && className
          ),
          children: [
            timezone ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "shrink-0 rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground", children: timezone.toUpperCase() }) : /* @__PURE__ */ jsxRuntime.jsx(
              Clock,
              {
                className: utils.cn(
                  "shrink-0 text-muted-foreground",
                  sizeConfig.icon
                )
              }
            ),
            /* @__PURE__ */ jsxRuntime.jsx(
              "input",
              {
                ref: inputRef,
                type: "text",
                disabled,
                "aria-label": label || "Pick a time",
                "aria-describedby": ariaDescribedBy,
                "aria-invalid": !!error || void 0,
                placeholder: placeholder ?? defaultPlaceholder,
                value: inputText,
                onChange: handleInputChange,
                onKeyDown: handleInputKeyDown,
                onFocus: handleInputFocus,
                className: utils.cn(
                  "min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-foreground",
                  "disabled:cursor-not-allowed",
                  sizeConfig.trigger.split(" ").find((c) => c.startsWith("text-"))
                )
              }
            ),
            /* @__PURE__ */ jsxRuntime.jsx(
              "button",
              {
                type: "button",
                onPointerDown: (e) => e.preventDefault(),
                onClick: handleClear,
                className: utils.cn(
                  "absolute inset-y-0 end-2 flex items-center text-muted-foreground hover:text-foreground focus:outline-none",
                  !(inputText && !disabled) && "invisible"
                ),
                "aria-label": "Clear time",
                tabIndex: -1,
                children: /* @__PURE__ */ jsxRuntime.jsx(x.X, { className: sizeConfig.icon })
              }
            )
          ]
        }
      ) }),
      open && /* @__PURE__ */ jsxRuntime.jsx(
        primitives_Popover.PopoverContent,
        {
          id: popoverContentId,
          className: "w-auto p-0",
          align: "start",
          onOpenAutoFocus: (e) => e.preventDefault(),
          onCloseAutoFocus: (e) => e.preventDefault(),
          onPointerDownOutside: (e) => e.preventDefault(),
          onInteractOutside: (e) => e.preventDefault(),
          children: /* @__PURE__ */ jsxRuntime.jsx(
            TimePickerPanel.TimePickerPanel,
            {
              value: internalTime ?? void 0,
              onChange: handlePanelChange,
              format,
              showSeconds,
              minuteStep,
              secondStep,
              disabled
            }
          )
        }
      )
    ] });
    if (!hasField) {
      return /* @__PURE__ */ jsxRuntime.jsx("div", { ref, className, children: triggerContent });
    }
    return /* @__PURE__ */ jsxRuntime.jsxs(
      primitives_Field.Field,
      {
        ref,
        "data-disabled": disabled || void 0,
        "data-invalid": !!error || void 0,
        className,
        children: [
          label && /* @__PURE__ */ jsxRuntime.jsxs(
            primitives_Field.FieldLabel,
            {
              ...labelProps,
              children: [
                label,
                required && /* @__PURE__ */ jsxRuntime.jsx("span", { "aria-hidden": "true", className: "text-destructive", children: "*" })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntime.jsxs(primitives_Field.FieldContent, { children: [
            triggerContent,
            !!error && /* @__PURE__ */ jsxRuntime.jsx(primitives_Field.FieldError, { id: errorId, children: error }),
            helpText && /* @__PURE__ */ jsxRuntime.jsx(primitives_Field.FieldDescription, { id: helpTextId, children: helpText })
          ] })
        ]
      }
    );
  }
);
TimePicker.displayName = "TimePicker";

exports.TimePicker = TimePicker;
//# sourceMappingURL=TimePicker-D6grsL0y.js.map
