import { jsxs, jsx } from 'react/jsx-runtime';
import { forwardRef, useId, useRef, useState, useCallback, useEffect } 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-DdHUxIdC.js';
import { d as dateToTimeValue, t as to12Hour, p as padNumber, T as TimePickerPanel, a as parseTimeString } from './TimePickerPanel-CiF0RExY.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 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);
        if (typeof value.toDate ===
            "function") {
            return dateToTimeValue(value.toDate());
        }
        return {
            hours: value.hours,
            minutes: value.minutes,
            seconds: value.seconds ?? 0,
        };
    }, [value]);
    const [internalTime, setInternalTime] = useState(getInitialTime);
    const [inputText, setInputText] = useState("");
    const formatTimeDisplay = useCallback((time) => {
        if (!time)
            return "";
        if (format === "12") {
            const { hour12, period } = to12Hour(time.hours);
            const parts = [padNumber(hour12), padNumber(time.minutes)];
            if (showSeconds)
                parts.push(padNumber(time.seconds ?? 0));
            return `${parts.join(":")} ${period}`;
        }
        const parts = [padNumber(time.hours), padNumber(time.minutes)];
        if (showSeconds)
            parts.push(padNumber(time.seconds ?? 0));
        return parts.join(":");
    }, [format, showSeconds]);
    useEffect(() => {
        const newTime = getInitialTime();
        setInternalTime(newTime);
        setInputText(formatTimeDisplay(newTime));
    }, [getInitialTime, formatTimeDisplay]);
    // Close on outside click
    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 = 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 = (jsxs(Popover, { open: open, children: [jsx(PopoverAnchor, { asChild: true, children: 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 ? (jsx("span", { className: "shrink-0 rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground", children: timezone.toUpperCase() })) : (jsx(Clock, { className: cn("shrink-0 text-muted-foreground", sizeConfig.icon) })), 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: 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-"))) }), 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: jsx(X, { className: sizeConfig.icon }) })] }) }), open && (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: jsx(TimePickerPanel, { value: internalTime ?? undefined, onChange: handlePanelChange, format: format, showSeconds: showSeconds, minuteStep: minuteStep, secondStep: secondStep, disabled: disabled }) }))] }));
    if (!hasField) {
        return (jsx("div", { ref: ref, className: className, children: triggerContent }));
    }
    return (jsxs(Field, { ref: ref, "data-disabled": disabled || undefined, "data-invalid": !!error || undefined, className: className, children: [label && (jsxs(FieldLabel, { ...labelProps, children: [label, required && (jsx("span", { "aria-hidden": "true", className: "text-destructive", children: "*" }))] })), jsxs(FieldContent, { children: [triggerContent, !!error && jsx(FieldError, { id: errorId, children: error }), helpText && (jsx(FieldDescription, { id: helpTextId, children: helpText }))] })] }));
});
TimePicker.displayName = "TimePicker";

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