import { useEffect, useRef, useState } from "@wordpress/element";

const KartografDrawer = (props) => {
  const [listSizeState, setListSizeState] = useState(1);
  const [autosize, setAutosize] = useState(false);
  const startPos = useRef(null);
  const drawerRef = useRef();
  const currentPos = useRef(null);
  const listSizeStateRef = useRef(1);
  listSizeStateRef.current = listSizeState;

  const changeListSize = () => {
    if (drawerRef.current.style.height === "4%") {
      drawerRef.current.style.height = "55%";
    } else {
      drawerRef.current.style.height = "4%";
    }
  };

  useEffect(() => {
    setAutosize(!!props.autosize);

    if (props.autosize) {
      setListSizeState(1);
    }
  }, [props.autosize]);

  const drawerDrag = (e) => {
    if (e.touches) {
      currentPos.current = e.touches[0].clientY;
      // console.log("current:" + currentPos.current);

      drawerRef.current.style.height =
        "calc( 100% - " + currentPos.current + "px )";
    }
  };

  const drawerEndDrag = () => {
    if (
      drawerRef.current.getBoundingClientRect().height >
      window.innerHeight / 2
    ) {
      drawerRef.current.style.height = "55%";
    }
    if (
      drawerRef.current.getBoundingClientRect().height <
      window.innerHeight / 4
    ) {
      drawerRef.current.style.height = "4%";
    }
  };

  return (
    <div
      className={`listArea epaka-d-block`}
      style={{ height: "55%" }}
      ref={drawerRef}
    >
      <div
        className={"listHandle"}
        onClick={changeListSize}
        onMouseUp={drawerEndDrag}
        onMouseMove={drawerDrag}
        onTouchEnd={drawerEndDrag}
        onTouchMove={drawerDrag}
      ></div>
      {props.children}
    </div>
  );
};

export default KartografDrawer;
