
// import logic
import SimpleBar from 'simplebar-react';
import React, { useEffect, useState, useRef } from 'react';

// nft scrollbar
const ComponentScroll = (props = {}) => {
  // refs
  const scrollRef = useRef(null);
  const [scrolled, setScrolled] = useState(false);

  // on scroll
  const onScroll = (e) => {
    // near
    const offset = props.offset || 200;

    // actual height
    const actualHeight = (scrollRef.current.scrollHeight - scrollRef.current.clientHeight);

    // top
    const isAtTop = parseInt(scrollRef.current.scrollTop) === 0;
    const isNearTop = (scrollRef.current.scrollTop - offset) < 0;
    const isAboveTop = scrollRef.current.scrollTop > 0;

    // bottom
    const isAtBottom = parseInt(scrollRef.current.scrollTop) === parseInt(actualHeight);
    const isNearBottom = (scrollRef.current.scrollTop + offset) >= actualHeight;
    const isAboveBottom = scrollRef.current.scrollTop < actualHeight;

    // check hit bottom
    if (props.keepBottom) {
      // scrolled
      setScrolled(isAboveBottom);
      
      // if bottom
      if (props.onEnd && isAtTop) props.onEnd();
      if (props.onNearEnd && isNearTop) props.onNearEnd();
    } else {
      // scrolled
      setScrolled(isAboveTop);
      
      // if bottom
      if (props.onEnd && isAtBottom) props.onEnd();
      if (props.onNearEnd && isNearBottom) props.onNearEnd();
    }
  };

  // use effect
  useEffect(() => {
    // check scroll
    if (!props.keepBottom) return;
    if (!scrollRef.current) return;
    
    // scroll to bottom
    scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [props.updated, scrollRef.current]);

  // use effect
  useEffect(() => {
    // check current
    if (!scrollRef.current) return;

    // check parent
    if (props.loadRef) props.loadRef(scrollRef.current);

    // add listener
    scrollRef.current.addEventListener('scroll', onScroll);

    // remove
    return () => {
      // remove event listener
      scrollRef.current?.removeEventListener('scroll', onScroll);
    };
  }, [scrollRef.current]);

  // return jsx
  return (
    <div className="relative flex-1 min-w-0">
      <div className="absolute top-0 left-0 w-full h-full">
        <SimpleBar
          className="flex-1 w-full min-w-0 h-full"
          scrollableNodeProps={ {
            id    : props.scrollId,
            ref   : scrollRef,
            style : {
              alignItems : props.keepBottom ? 'end' : undefined,
            }
          } }
        >
          { props.children }
        </SimpleBar>
      </div>
    </div>
  );
};

// export default
export default ComponentScroll;