import { jsxs, jsx } from 'react/jsx-runtime';
import { forwardRef, useId, useRef, useState, useCallback, useEffect, useMemo, useLayoutEffect } from 'react';
import { Popover, PopoverAnchor, PopoverContent } from './primitives/Popover.js';
import { Field, FieldLabel, FieldContent, FieldError, FieldDescription } from './primitives/Field.js';
import { c as cn } from './utils-BJnb9o5c.js';
import { d as dateToTimeValue, f as formatTimeDisplay, b as buildMaskTemplate, T as TimePickerPanel, a as applyMask, p as parseTimeString, t as timeValueToDayjs } from './TimePickerPanel-SQBEEJko.js';
import { c as createLucideIcon } from './createLucideIcon-C8ycilSN.js';
import { X } from './x-_o2T3n6D.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("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 = 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 = useId();
    const errorId = `error_${generatedId}`;
    const helpTextId = `helpText_${generatedId}`;
    const containerRef = useRef(null);
    const inputRef = useRef(null);
    const cursorPosRef = useRef(null);
    const popoverContentId = useRef(
      `timepicker-popover-${generatedId}`
    ).current;
    const [open, setOpen] = useState(false);
    const getInitialTime = useCallback(() => {
      if (!value) return null;
      if (value instanceof Date) return 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 dateToTimeValue(dayjsLike.toDate());
      }
      const timeValue = value;
      return {
        hours: timeValue.hours,
        minutes: timeValue.minutes,
        seconds: timeValue.seconds ?? 0
      };
    }, [value]);
    const [internalTime, setInternalTime] = useState(
      getInitialTime
    );
    const [inputText, setInputText] = useState("");
    const displayTime = useCallback(
      (time) => formatTimeDisplay(time, format, showSeconds),
      [format, showSeconds]
    );
    useEffect(() => {
      const newTime = getInitialTime();
      setInternalTime(newTime);
      if (!open) setInputText(displayTime(newTime));
    }, [getInitialTime, displayTime, open]);
    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 = useMemo(() => {
      if (format === "12") {
        return showSeconds ? "hh:mm:ss AA" : "hh:mm AA";
      }
      return showSeconds ? "HH:mm:ss" : "HH:mm";
    }, [format, showSeconds]);
    const maskTemplate = useMemo(
      () => 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?.(timeValueToDayjs(time), displayTime(time));
    };
    const handlePanelChange = (time) => {
      setInternalTime(time);
      setInputText(displayTime(time));
      emitChange(time);
    };
    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 = applyMask(
        e.target.value,
        maskTemplate,
        inputText,
        e.target.selectionStart
      );
      const text = masked.text;
      cursorPosRef.current = masked.cursorPosition;
      setInputText(text);
      const parsed = 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__ */ jsxs(Popover, { open, children: [
      /* @__PURE__ */ jsx(PopoverAnchor, { asChild: true, children: /* @__PURE__ */ jsxs(
        "div",
        {
          ref: containerRef,
          className: 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__ */ jsx("span", { className: "shrink-0 rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground", children: timezone.toUpperCase() }) : /* @__PURE__ */ jsx(
              Clock,
              {
                className: cn(
                  "shrink-0 text-muted-foreground",
                  sizeConfig.icon
                )
              }
            ),
            /* @__PURE__ */ 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: 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__ */ jsx(
              "button",
              {
                type: "button",
                onPointerDown: (e) => e.preventDefault(),
                onClick: handleClear,
                className: 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__ */ jsx(X, { className: sizeConfig.icon })
              }
            )
          ]
        }
      ) }),
      open && /* @__PURE__ */ jsx(
        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__ */ jsx(
            TimePickerPanel,
            {
              value: internalTime ?? void 0,
              onChange: handlePanelChange,
              format,
              showSeconds,
              minuteStep,
              secondStep,
              disabled
            }
          )
        }
      )
    ] });
    if (!hasField) {
      return /* @__PURE__ */ jsx("div", { ref, className, children: triggerContent });
    }
    return /* @__PURE__ */ jsxs(
      Field,
      {
        ref,
        "data-disabled": disabled || void 0,
        "data-invalid": !!error || void 0,
        className,
        children: [
          label && /* @__PURE__ */ jsxs(
            FieldLabel,
            {
              ...labelProps,
              children: [
                label,
                required && /* @__PURE__ */ jsx("span", { "aria-hidden": "true", className: "text-destructive", children: "*" })
              ]
            }
          ),
          /* @__PURE__ */ jsxs(FieldContent, { children: [
            triggerContent,
            !!error && /* @__PURE__ */ jsx(FieldError, { id: errorId, children: error }),
            helpText && /* @__PURE__ */ jsx(FieldDescription, { id: helpTextId, children: helpText })
          ] })
        ]
      }
    );
  }
);
TimePicker.displayName = "TimePicker";

export { TimePicker as T };
//# sourceMappingURL=TimePicker-WTEf9ZY9.js.map
