'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-CTr7wn5d.js');
var TimePickerPanel = require('./TimePickerPanel-DGNr97cj.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 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);
        if (typeof value.toDate ===
            "function") {
            return TimePickerPanel.dateToTimeValue(value.toDate());
        }
        return {
            hours: value.hours,
            minutes: value.minutes,
            seconds: value.seconds ?? 0,
        };
    }, [value]);
    const [internalTime, setInternalTime] = React.useState(getInitialTime);
    const [inputText, setInputText] = React.useState("");
    const formatTimeDisplay = React.useCallback((time) => {
        if (!time)
            return "";
        if (format === "12") {
            const { hour12, period } = TimePickerPanel.to12Hour(time.hours);
            const parts = [TimePickerPanel.padNumber(hour12), TimePickerPanel.padNumber(time.minutes)];
            if (showSeconds)
                parts.push(TimePickerPanel.padNumber(time.seconds ?? 0));
            return `${parts.join(":")} ${period}`;
        }
        const parts = [TimePickerPanel.padNumber(time.hours), TimePickerPanel.padNumber(time.minutes)];
        if (showSeconds)
            parts.push(TimePickerPanel.padNumber(time.seconds ?? 0));
        return parts.join(":");
    }, [format, showSeconds]);
    React.useEffect(() => {
        const newTime = getInitialTime();
        setInternalTime(newTime);
        setInputText(formatTimeDisplay(newTime));
    }, [getInitialTime, formatTimeDisplay]);
    // Close on outside click
    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(formatTimeDisplay(internalTime));
        };
        document.addEventListener("pointerdown", handlePointerDown);
        return () => document.removeEventListener("pointerdown", handlePointerDown);
    }, [open, internalTime, formatTimeDisplay]);
    const defaultPlaceholder = showSeconds
        ? format === "12"
            ? "hh:mm:ss AA"
            : "HH:mm:ss"
        : format === "12"
            ? "hh:mm AA"
            : "HH:mm";
    const handlePanelChange = (time) => {
        setInternalTime(time);
        setInputText(formatTimeDisplay(time));
        onChange?.(time);
    };
    const handleInputChange = (e) => {
        const text = e.target.value;
        setInputText(text);
        const parsed = TimePickerPanel.parseTimeString(text, format);
        if (parsed) {
            setInternalTime(parsed);
            onChange?.(parsed);
        }
    };
    const handleInputKeyDown = (e) => {
        if (e.key === "Enter") {
            setInputText(formatTimeDisplay(internalTime));
            setOpen(false);
        }
        else if (e.key === "Escape") {
            setInputText(formatTimeDisplay(internalTime));
            setOpen(false);
        }
    };
    const handleInputFocus = () => {
        if (!open)
            setOpen(true);
    };
    const handleClear = (e) => {
        e.stopPropagation();
        e.preventDefault();
        setInternalTime(null);
        setInputText("");
        onChange?.({ hours: 0, minutes: 0, seconds: 0 });
    };
    const hasField = !!(label || error || helpText);
    const sizeConfig = SIZE_CONFIG[size];
    const ariaDescribedBy = [error ? errorId : null, helpText ? helpTextId : null]
        .filter(Boolean)
        .join(" ") || undefined;
    const triggerContent = (jsxRuntime.jsxs(primitives_Popover.Popover, { open: open, children: [jsxRuntime.jsx(primitives_Popover.PopoverAnchor, { asChild: true, children: 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 ? (jsxRuntime.jsx("span", { className: "shrink-0 rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground", children: timezone.toUpperCase() })) : (jsxRuntime.jsx(Clock, { className: utils.cn("shrink-0 text-muted-foreground", sizeConfig.icon) })), jsxRuntime.jsx("input", { type: "text", disabled: disabled, "aria-label": label || "Pick a time", "aria-describedby": ariaDescribedBy, "aria-invalid": !!error || undefined, 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-"))) }), 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: jsxRuntime.jsx(x.X, { className: sizeConfig.icon }) })] }) }), open && (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: jsxRuntime.jsx(TimePickerPanel.TimePickerPanel, { value: internalTime ?? undefined, onChange: handlePanelChange, format: format, showSeconds: showSeconds, minuteStep: minuteStep, secondStep: secondStep, disabled: disabled }) }))] }));
    if (!hasField) {
        return (jsxRuntime.jsx("div", { ref: ref, className: className, children: triggerContent }));
    }
    return (jsxRuntime.jsxs(primitives_Field.Field, { ref: ref, "data-disabled": disabled || undefined, "data-invalid": !!error || undefined, className: className, children: [label && (jsxRuntime.jsxs(primitives_Field.FieldLabel, { ...labelProps, children: [label, required && (jsxRuntime.jsx("span", { "aria-hidden": "true", className: "text-destructive", children: "*" }))] })), jsxRuntime.jsxs(primitives_Field.FieldContent, { children: [triggerContent, !!error && jsxRuntime.jsx(primitives_Field.FieldError, { id: errorId, children: error }), helpText && (jsxRuntime.jsx(primitives_Field.FieldDescription, { id: helpTextId, children: helpText }))] })] }));
});
TimePicker.displayName = "TimePicker";

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