import React, { useCallback, useRef } from "react";
import { Slot } from "../../utils/components/slot/Slot.js";
import { createStrictContext } from "../../utils/helpers/index.js";
const { Provider: TimelineKeyboardNavStableContextProvider, useContext: useTimelineKeyboardContext, } = createStrictContext({
    name: "TimelineKeyboardNavStableContext",
    errorMessage: "useTimelineKeyboardContext must be used within a TimelineKeyboardNavProvider",
});
const { Provider: TimelineKeyboardNavActiveRowContextProvider, useContext: useTimelineKeyboardActiveRow, } = createStrictContext({
    name: "TimelineKeyboardNavActiveRowContext",
    errorMessage: "useTimelineKeyboardActiveRow must be used within a TimelineKeyboardNavProvider",
});
function TimelineKeyboardNavProvider({ children, }) {
    const [activeRow, setActiveRow] = React.useState(null);
    const activeRowRef = React.useRef(null);
    const timelineElementRef = useRef(null);
    const updateActiveRow = React.useCallback((element) => {
        activeRowRef.current = element;
        setActiveRow(element);
    }, []);
    const handleRowKeyDown = useCallback((event) => {
        var _a, _b, _c;
        const currentActiveRow = activeRowRef.current;
        if (!currentActiveRow) {
            return;
        }
        /* Skip interaction if focus is inside popover */
        if ((_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.closest("[data-timeline-popover]")) {
            return;
        }
        const { key } = event;
        if (key === "ArrowDown" || key === "ArrowUp") {
            const rows = (_b = currentActiveRow.parentElement) === null || _b === void 0 ? void 0 : _b.querySelectorAll("[data-timeline-row]");
            const firstPin = (_c = currentActiveRow.parentElement) === null || _c === void 0 ? void 0 : _c.querySelector("[data-timeline-pin]");
            if (!rows || rows.length === 0) {
                return;
            }
            const currentIndex = Array.from(rows).indexOf(currentActiveRow);
            if (currentIndex === -1) {
                return;
            }
            const atBoundary = currentIndex === 0 && key === "ArrowUp";
            if (atBoundary && firstPin) {
                focusElement(firstPin, event);
                return;
            }
            const nextIndex = key === "ArrowDown" ? currentIndex + 1 : currentIndex - 1;
            /* We want to avoid looping */
            if (nextIndex < 0 || nextIndex >= rows.length) {
                return;
            }
            const nextRow = rows[nextIndex];
            const periods = nextRow === null || nextRow === void 0 ? void 0 : nextRow.querySelectorAll("[data-timeline-period]");
            if ((periods === null || periods === void 0 ? void 0 : periods.length) > 0) {
                focusElement(periods[0], event);
            }
            else if (nextRow) {
                focusElement(nextRow, event);
            }
            return;
        }
        if (key === "ArrowRight" || key === "ArrowLeft") {
            event.preventDefault();
            const periods = currentActiveRow.querySelectorAll("[data-timeline-period]");
            if (periods.length === 0) {
                return;
            }
            const currentIndex = Array.from(periods).indexOf(document.activeElement);
            if (currentIndex === -1) {
                /* If just the row has focus, we want to focus either the first or last period inside based on key */
                focusElement(periods[key === "ArrowRight" ? 0 : periods.length - 1], event);
                return;
            }
            const nextIndex = key === "ArrowRight" ? currentIndex + 1 : currentIndex - 1;
            /* We want to avoid looping */
            if (nextIndex < 0 || nextIndex >= periods.length) {
                return;
            }
            focusElement(periods[nextIndex], event);
        }
    }, []);
    const handlePinKeyDown = useCallback((event) => {
        var _a;
        const timelineElement = timelineElementRef.current;
        if (!timelineElement) {
            return;
        }
        /* Skip interaction if focus is inside popover */
        if ((_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.closest("[data-timeline-popover]")) {
            return;
        }
        const { key } = event;
        if (key === "ArrowDown") {
            const rows = timelineElement.querySelectorAll("[data-timeline-row]");
            if (rows.length === 0) {
                return;
            }
            const rowToFocus = rows[0];
            if (rowToFocus) {
                const periods = rowToFocus === null || rowToFocus === void 0 ? void 0 : rowToFocus.querySelectorAll("[data-timeline-period]");
                if ((periods === null || periods === void 0 ? void 0 : periods.length) > 0) {
                    focusElement(periods[0], event);
                }
                else if (rowToFocus) {
                    focusElement(rowToFocus, event);
                }
            }
        }
        if (key === "ArrowRight" || key === "ArrowLeft") {
            event.preventDefault();
            const pins = timelineElement.querySelectorAll("[data-timeline-pin]");
            if (pins.length === 0) {
                return;
            }
            const currentIndex = Array.from(pins).indexOf(document.activeElement);
            if (currentIndex === -1) {
                return;
            }
            const nextIndex = key === "ArrowRight" ? currentIndex + 1 : currentIndex - 1;
            /* We want to avoid looping */
            if (nextIndex < 0 || nextIndex >= pins.length) {
                return;
            }
            focusElement(pins[nextIndex], event);
        }
    }, []);
    return (React.createElement(TimelineKeyboardNavStableContextProvider, { updateActiveRow: updateActiveRow, handleRowKeyDown: handleRowKeyDown, handlePinKeyDown: handlePinKeyDown },
        React.createElement(TimelineKeyboardNavActiveRowContextProvider, { activeRow: activeRow },
            React.createElement(Slot, { ref: timelineElementRef }, children))));
}
/**
 * Focuses the given element and prevents default behavior of the event if focus is called.
 */
function focusElement(element, event) {
    if (!element) {
        return;
    }
    event.preventDefault();
    element.focus();
}
export { TimelineKeyboardNavProvider, useTimelineKeyboardContext, useTimelineKeyboardActiveRow, };
//# sourceMappingURL=TimelineKeyboardNavProvider.js.map