"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.useTimelineKeyboardActiveRow = exports.useTimelineKeyboardContext = void 0;
exports.TimelineKeyboardNavProvider = TimelineKeyboardNavProvider;
const react_1 = __importStar(require("react"));
const Slot_1 = require("../../utils/components/slot/Slot");
const helpers_1 = require("../../utils/helpers");
const { Provider: TimelineKeyboardNavStableContextProvider, useContext: useTimelineKeyboardContext, } = (0, helpers_1.createStrictContext)({
    name: "TimelineKeyboardNavStableContext",
    errorMessage: "useTimelineKeyboardContext must be used within a TimelineKeyboardNavProvider",
});
exports.useTimelineKeyboardContext = useTimelineKeyboardContext;
const { Provider: TimelineKeyboardNavActiveRowContextProvider, useContext: useTimelineKeyboardActiveRow, } = (0, helpers_1.createStrictContext)({
    name: "TimelineKeyboardNavActiveRowContext",
    errorMessage: "useTimelineKeyboardActiveRow must be used within a TimelineKeyboardNavProvider",
});
exports.useTimelineKeyboardActiveRow = useTimelineKeyboardActiveRow;
function TimelineKeyboardNavProvider({ children, }) {
    const [activeRow, setActiveRow] = react_1.default.useState(null);
    const activeRowRef = react_1.default.useRef(null);
    const timelineElementRef = (0, react_1.useRef)(null);
    const updateActiveRow = react_1.default.useCallback((element) => {
        activeRowRef.current = element;
        setActiveRow(element);
    }, []);
    const handleRowKeyDown = (0, react_1.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 = (0, react_1.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_1.default.createElement(TimelineKeyboardNavStableContextProvider, { updateActiveRow: updateActiveRow, handleRowKeyDown: handleRowKeyDown, handlePinKeyDown: handlePinKeyDown },
        react_1.default.createElement(TimelineKeyboardNavActiveRowContextProvider, { activeRow: activeRow },
            react_1.default.createElement(Slot_1.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();
}
//# sourceMappingURL=TimelineKeyboardNavProvider.js.map