
import { useEffect, useState } from 'react';

/**
 * Since we have no way in slick to know which slide is active as a prop, we need to
 * check each slide's parent list to see if it is active/inactive, and therefore should have
 * its inner tab-indexes to be -1
 * */
const SLICK_SLIDE_ACTIVE_CLASS = 'slick-active';

const checkItem = node => {
    const p = node && node.parentNode;
    if (p) {
        if (p.ariaHidden === false || p.classList?.contains(SLICK_SLIDE_ACTIVE_CLASS)) {
            return true;
        }
        return checkItem(p);
    }
    return false;
};

/**
 Determines if the current slide is visible on screen or not
 @param {object} nodeRef the current slide's node
 @returns {Array} [
     the boolean value if the slide is visible on screen,
     the tabIndex value based on the visibility of slide
    ]
*/
export const useCarouselA11yVisible = nodeRef => {
    const [isA11yVisible, setIsA11yVisible] = useState(true);
    useEffect(() => {
        if (nodeRef && nodeRef.current) {
            const isActive = checkItem(nodeRef.current);
            setIsA11yVisible(isActive);
        }
    }, [nodeRef]);
    const tabIndex = isA11yVisible ? 0 : -1;
    return [isA11yVisible, tabIndex];
};
