import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../../../../tools/namingTools';

import { useDebounceResize } from '../../../../../tools/dimensions/useDebounceResize';

import './styles/HeaderScrim.scss';

const n = createNamespace('HeaderScrim');

const HeaderScrim = ({
    color,
    visible,
    className: extraClass
}) => {
    const scrimRef = useRef(null);

    const positionScrim = () => {
        if (!scrimRef.current) {
            return;
        }
        const scrimElem = scrimRef.current;
        // Hide the scrim before otherwise it might cause an horizontal scrollbar gap
        scrimElem.style.setProperty('display', 'none');
        scrimElem.style.removeProperty('display');
    };
    useDebounceResize(positionScrim);
    useEffect(positionScrim);

    const styleVariables = {
        'scrim-background-color': color
    };
    return (
        <div
            {...n('scrim', !visible && 'hidden')
                .withClass(extraClass)
                .withVariables(styleVariables)
                .withTestId()
                .props}
            ref={scrimRef}
        />
    );
};

HeaderScrim.propTypes = {
    color: PropTypes.string,
    visible: PropTypes.bool,
    className: PropTypes.string
};

HeaderScrim.defaultProps = {
    color: undefined,
    visible: false,
    className: null
};

export default HeaderScrim;
