import React from 'react';

export default class ScrollTop extends React.Component {
  state = {
    listenerAttached: false,
    showTop: false,
    showBottom: false,
  };

  componentDidUpdate() {
    if (this.props.postListNode && !this.state.listenerAttached) {
      this.props.postListNode.addEventListener('scroll', this.scrollListener);

      this.setState({ listenerAttached: true });
    }
  }

  scrollListener = () => {
    const postList = this.props.postListNode;
    const elementEnd =
      postList.scrollTop + postList.offsetHeight >= postList.scrollHeight;

    this.setState({
      showTop: postList.scrollTop > window.innerHeight,
      showBottom: !elementEnd,
    });
  };

  render() {
    const postList = this.props.postListNode;

    return (
      postList && (
        <div className="scroll-to-top">
          {this.state.showTop && (
            <i
              className="scroll-to-top__icon scroll-to-top__icon--top"
              onClick={() => postList.scroll({ top: 0 })}
            />
          )}

          {this.state.showBottom && (
            <i
              className="scroll-to-top__icon scroll-to-top__icon--bottom"
              onClick={() => postList.scroll({ top: postList.scrollHeight })}
            />
          )}
        </div>
      )
    );
  }
}
