import React, { memo, useEffect, useRef, useState } from 'react';
import { joinClassNames } from '@vizality/util/dom';

export default memo(({ sticky, onStickyChange, className, wrapperClassName, children, ...other }) => {
  const [ _sticky, setSticky ] = useState(sticky);
  const headerRef = useRef(null);

  const handleStickyChange = element => {
    setSticky(element.isIntersecting < 1);
    if (onStickyChange && typeof onStickyChange === 'function') {
      onStickyChange(element.isIntersecting < 1);
    }
  };

  useEffect(() => {
    const header = headerRef?.current;
    const observer = new IntersectionObserver(
      ([ element ]) => handleStickyChange(element),
      { threshold: [ 1 ] }
    );

    if (header) {
      observer.observe(header);
    }

    /**
     * Clean up the observer
     */
    return (() => observer.unobserve(header));
  }, [ headerRef ]);

  return (
    <div
      ref={headerRef}
      className={joinClassNames('vz-sticky-element-wrapper', wrapperClassName)}
      vz-stuck={Boolean(_sticky) && ''}
      {...other}
    >
      <div className={joinClassNames('vz-sticky-element', className)}>
        {children}
      </div>
    </div>
  );
});
