import { jsx as _jsx } from "react/jsx-runtime";
import React, { createContext, isValidElement, useContext, } from "react";
import { Box } from "ink";
import { OrderedListItem, OrderedListItemContext } from "./OrderedListItem.js";
const OrderedListContext = createContext({ marker: "" });
export const OrderedList = Object.assign(function OrderedListComponent(props) {
    const { marker: parentMarker } = useContext(OrderedListContext);
    const itemCount = countOrderedListItems(props.children);
    const markerWidth = orderedListMarkerWidth(itemCount);
    let itemIndex = 0;
    return (_jsx(Box, { flexDirection: "column", children: React.Children.map(props.children, (child) => {
            if (!isValidElement(child) || child.type !== OrderedListItem)
                return child;
            itemIndex += 1;
            const marker = `${parentMarker}${formatOrderedListMarker(itemIndex, markerWidth)}`;
            return (_jsx(OrderedListContext.Provider, { value: { marker }, children: _jsx(OrderedListItemContext.Provider, { value: { marker }, children: child }) }));
        }) }));
}, { Item: OrderedListItem });
export function countOrderedListItems(children) {
    return React.Children.toArray(children)
        .filter((child) => isValidElement(child) && child.type === OrderedListItem)
        .length;
}
export function orderedListMarkerWidth(itemCount) {
    return String(Math.max(1, itemCount)).length;
}
export function formatOrderedListMarker(index, markerWidth) {
    return `${String(Math.max(1, index)).padStart(Math.max(1, markerWidth))}.`;
}
