import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useRef, useEffect, forwardRef, useCallback, useState } from 'react';
import { c as cn } from './utils-DdHUxIdC.js';
import { Button } from './primitives/Button.js';
import { ScrollArea } from './primitives/ScrollArea.js';

const COLUMN_HEIGHT = 224;
const ITEM_HEIGHT = 32;
const PERIODS = ["AM", "PM"];

const generateRange = (start, end, step = 1) => {
    const result = [];
    for (let i = start; i <= end; i += step) {
        result.push(i);
    }
    return result;
};
const to12Hour = (hour24) => {
    const period = hour24 >= 12 ? "PM" : "AM";
    const hour12 = hour24 % 12 || 12;
    return { hour12, period };
};
const to24Hour = (hour12, period) => {
    if (period === "AM") {
        return hour12 === 12 ? 0 : hour12;
    }
    return hour12 === 12 ? 12 : hour12 + 12;
};
const dateToTimeValue = (date) => ({
    hours: date.getHours(),
    minutes: date.getMinutes(),
    seconds: date.getSeconds(),
});
const padNumber = (num, length = 2) => String(num).padStart(length, "0");
const parseTimeString = (input, format) => {
    const trimmed = input.trim();
    if (!trimmed)
        return null;
    if (format === "12") {
        // Accept: "2:30 PM", "02:30 PM", "2:3 PM", "2:30:15 PM"
        const match = trimmed.match(/^(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?\s*(AM|PM)$/i);
        if (!match)
            return null;
        const hour12 = parseInt(match[1], 10);
        const minutes = parseInt(match[2], 10);
        const seconds = match[3] ? parseInt(match[3], 10) : 0;
        const period = match[4].toUpperCase();
        if (hour12 < 1 || hour12 > 12 || minutes > 59 || seconds > 59)
            return null;
        return { hours: to24Hour(hour12, period), minutes, seconds };
    }
    // Accept: "14:3", "14:30", "2:5", "14:30:05"
    const match = trimmed.match(/^(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?$/);
    if (!match)
        return null;
    const hours = parseInt(match[1], 10);
    const minutes = parseInt(match[2], 10);
    const seconds = match[3] ? parseInt(match[3], 10) : 0;
    if (hours > 23 || minutes > 59 || seconds > 59)
        return null;
    return { hours, minutes, seconds };
};

const TimeColumn = ({ items, selected, onSelect, disabled = false, className, padStart = 2, }) => {
    const selectedRef = useRef(null);
    useEffect(() => {
        if (selectedRef.current) {
            selectedRef.current.scrollIntoView({
                block: "center",
                behavior: "smooth",
            });
        }
    }, [selected]);
    return (jsx(ScrollArea, { className: cn("w-16", className), style: { height: COLUMN_HEIGHT }, children: jsx("div", { className: "flex flex-col items-center py-2", role: "listbox", "aria-label": "Time selection", children: items.map(item => {
                const isSelected = item === selected;
                const displayValue = typeof item === "number" ? padNumber(item, padStart) : item;
                return (jsx(Button, { ref: isSelected ? selectedRef : undefined, variant: isSelected ? "default" : "ghost", size: "sm", role: "option", "aria-selected": isSelected, disabled: disabled, className: cn("w-12 justify-center font-mono text-sm", !isSelected && "text-muted-foreground"), style: { height: ITEM_HEIGHT }, onClick: () => onSelect(item), children: displayValue }, item));
            }) }) }));
};
TimeColumn.displayName = "TimeColumn";

const TimePickerPanel = forwardRef(({ value, onChange, format = "24", showSeconds = false, minuteStep = 1, secondStep = 1, disabled = false, className, }, ref) => {
    const getInitialTime = useCallback(() => ({
        hours: value?.hours ?? 0,
        minutes: value?.minutes ?? 0,
        seconds: value?.seconds ?? 0,
    }), [value]);
    const [internalTime, setInternalTime] = useState(getInitialTime);
    useEffect(() => {
        setInternalTime(getInitialTime());
    }, [getInitialTime]);
    const hours = format === "12" ? generateRange(1, 12) : generateRange(0, 23);
    const minutes = generateRange(0, 59, minuteStep);
    const seconds = generateRange(0, 59, secondStep);
    const { hour12, period } = format === "12"
        ? to12Hour(internalTime.hours)
        : { hour12: internalTime.hours, period: "AM" };
    const handleHourSelect = (hourValue) => {
        const hour = Number(hourValue);
        const newHours = format === "12" ? to24Hour(hour, period) : hour;
        const newTime = { ...internalTime, hours: newHours };
        setInternalTime(newTime);
        onChange?.(newTime);
    };
    const handleMinuteSelect = (minuteValue) => {
        const newTime = { ...internalTime, minutes: Number(minuteValue) };
        setInternalTime(newTime);
        onChange?.(newTime);
    };
    const handleSecondSelect = (secondValue) => {
        const newTime = { ...internalTime, seconds: Number(secondValue) };
        setInternalTime(newTime);
        onChange?.(newTime);
    };
    const handlePeriodSelect = (newPeriod) => {
        const newHours = to24Hour(hour12, newPeriod);
        const newTime = { ...internalTime, hours: newHours };
        setInternalTime(newTime);
        onChange?.(newTime);
    };
    return (jsxs("div", { ref: ref, className: cn("flex", className), role: "group", "aria-label": "Time picker", children: [jsx(TimeColumn, { items: hours, selected: format === "12" ? hour12 : internalTime.hours, onSelect: handleHourSelect, disabled: disabled }), jsx("div", { className: "border-inline-end border-border" }), jsx(TimeColumn, { items: minutes, selected: internalTime.minutes, onSelect: handleMinuteSelect, disabled: disabled }), showSeconds && (jsxs(Fragment, { children: [jsx("div", { className: "border-inline-end border-border" }), jsx(TimeColumn, { items: seconds, selected: internalTime.seconds ?? 0, onSelect: handleSecondSelect, disabled: disabled })] })), format === "12" && (jsxs(Fragment, { children: [jsx("div", { className: "border-inline-end border-border" }), jsx(TimeColumn, { items: [...PERIODS], selected: period, onSelect: handlePeriodSelect, disabled: disabled, padStart: 0 })] }))] }));
});
TimePickerPanel.displayName = "TimePickerPanel";

export { TimePickerPanel as T, parseTimeString as a, dateToTimeValue as d, padNumber as p, to12Hour as t };
//# sourceMappingURL=TimePickerPanel-CiF0RExY.js.map
