import React, { FC, useEffect, useState, RefObject } from 'react';
import cx from 'classnames';
import { debounce } from 'lodash';

interface Props {
    target: RefObject<HTMLElement>;
}

const SCROLL_DEBOUNCE = 100;
export const CLASSNAME = 'StickyHeader';
export const CLASSNAME_ACTIVE = `${CLASSNAME}-active`;

const StickyHeader: FC<Props> = ({ children, target }) => {
    const [sticky, setSticky] = useState(false);

    const handleScroll = debounce(() => {
        setSticky(
            target.current
                ? target.current.getBoundingClientRect().top <= 0
                : false
        );
    }, SCROLL_DEBOUNCE);

    useEffect(() => {
        window.addEventListener('scroll', handleScroll);
        return () => {
            window.removeEventListener('scroll', () => handleScroll);
        };
    }, []);

    return (
        <div className={cx(CLASSNAME, { [CLASSNAME_ACTIVE]: sticky })}>
            <div className="container-max-1170">
                {children}
            </div>
        </div>
    );
};

export default StickyHeader;
