import React, { type FC, useEffect, useState, type RefObject } from 'react';
import cx from 'classnames';
import { MAIN_CONTENT_CLASSNAME } from 'src/constants';

interface Props {
    target: RefObject<HTMLElement>;
    children: React.ReactNode;
}

export const CLASSNAME = 'StickyHeader';
export const CLASSNAME_ACTIVE = `${CLASSNAME}-active`;
export const CLASSNAME_STICKY_ITEM = `${CLASSNAME}-sticky-item`;

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

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

        const elem = document
            .getElementsByClassName(MAIN_CONTENT_CLASSNAME)
            .item(0);
        elem?.addEventListener('scroll', handleScroll);
        return () => {
            elem?.removeEventListener('scroll', handleScroll);
        };
    }, [target]);

    return (
        <div className={cx(CLASSNAME, { [CLASSNAME_ACTIVE]: sticky })}>
            <div className={CLASSNAME_STICKY_ITEM}>{children}</div>
        </div>
    );
};

export default StickyHeader;
