import React, {useEffect, useRef, useState} from "react";
import './scrollContent.scss'


const throttle = (func, limit) => {
  let lastFunc;
  let lastRan;
  return function () {
    const context = this;
    const args = arguments;
    if (!lastRan) {
      func.apply(context, args);
      lastRan = Date.now()
    } else {
      clearTimeout(lastFunc);
      lastFunc = setTimeout(function () {
        if ((Date.now() - lastRan) >= limit) {
          func.apply(context, args);
          lastRan = Date.now()
        }
      }, limit - (Date.now() - lastRan))
    }
  }
};

export const ScrollContent = ({data}) => {

  const [stiky, setStiky] = useState();
  const [scrollStep, setScrollStep] = useState();
  const stikyRef = useRef();


  useEffect(() => {

    setStiky(stikyRef.current);

  }, []);

  useEffect(() => {
    if (stiky) {
      bindEvents();
      setStickyContainerSize()
    }

  }, [stiky, data]);
  useEffect(() => {

    setScrollStep(document.documentElement.scrollTop)

  }, []);

  function bindEvents() {

    // window.addEventListener('wheel', wheelHandler);
    window.onscroll = throttle(scrollHandler, 400);
  }

  function setStickyContainerSize() {
    stiky.setAttribute('style', `height:${stiky.scrollWidth}px`);

  }

  function isElementInViewport(el) {
    if (el) {
      const rect = el.getBoundingClientRect();
      return rect.top <= 0 && rect.bottom > document.documentElement.clientHeight;
    } else {
      return null
    }
  }

  function scrollHandler(evt) {

    const containerInViewPort = isElementInViewport(stiky) && stiky;


    if (!containerInViewPort) {
      return;
    }
    console.log(window.scrollY);
    const body = document.body,
        html = document.documentElement;

    const height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);

    // console.log(height - window.scrollY);
    console.log(containerInViewPort.offsetTop, 'Расстояние от начала документа');
    console.log(document.documentElement.clientHeight, 'Высота Экран');
    console.log(document.documentElement.scrollTop, 'Текущая высота скрола');
    setScrollStep((prev) => prev < 0 ? prev + document.documentElement.scrollTop : prev - document.documentElement.scrollTop)
    console.log(scrollStep, "ASDASD");
    console.log(containerInViewPort.offsetHeight, 'Высота родительского блока для определения горизонтального скрола');

    const isPlaceHolderBelowTop = containerInViewPort.offsetTop < document.documentElement.scrollTop;
    const isPlaceHolderBelowBottom = containerInViewPort.offsetTop + containerInViewPort.offsetHeight > document.documentElement.scrollTop;
    const g_canScrollHorizontally = isPlaceHolderBelowTop && isPlaceHolderBelowBottom;

    // console.log(isPlaceHolderBelowBottom, 'Хуйня');

    if (g_canScrollHorizontally) {

      containerInViewPort.scrollLeft = containerInViewPort.scrollLeft + evt.deltaY;

    }
  }


  return (
      <div className='scroll'>
        <h3 className='scroll__title'>Lorem ipsum dolor sit amet</h3>
        <div className='scroll__content sticky-container' id='scroll_container' ref={stikyRef}>
          <div className="scroll__hiddenWrapper">
            {
              data.map((img, index) =>

                  <div className='scroll__item' key={`scroll-${index}`}>
                    <img className='scroll__image' src={img} alt="scrollContent"/>
                  </div>
              )
            }
          </div>

        </div>


      </div>
  )
};