import {
  Component, h, useEffect, useProp, useState,
} from "atomico";
import style from "./kun-fixed-button.scss";
import { getComponentOrDefine } from "../../hooks/aync-hook/redirect";

// TODO scroll error

const KunFixedButton = () => {
  const [clsName] = useProp<string>("clsName");
  const clintWidth = window.document.body.clientHeight;
  const scrollToTop = (): void => {
    const lL = window.document.getElementsByClassName(clsName);
    const el = lL[0];
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const [show, setShow] = useState(false);
  const checkPosition = (): void => {
    const lL = window.document.getElementsByClassName(clsName);
    const el = lL[0];
    const top = el.scrollTop;
    if (top > clintWidth / 3) {
      setShow(true);
    } else {
      setShow(false);
    }
    console.log("top", top);
  };

  useEffect(() => {
    const lL = window.document.getElementsByClassName(clsName);
    const el = lL[0];
    console.log("el", el);
    if (el != null) {
      // window.addEventListener("scroll", checkPosition);
      el.addEventListener("scroll", checkPosition);
      window.addEventListener("scroll", checkPosition);
    }

    return () => {
      // window.removeEventListener("scroll", checkPosition);
      el.removeEventListener("scroll", checkPosition);
      window.addEventListener("scroll", checkPosition);
    };
  }, []);

  return (
    <host>
      <style>{style}</style>
      <div className={`${show ? "" : "display-none1"}  icon transition-opacity duration-500 ease-in-out hover:bg-orange-400`} onclick={scrollToTop}>
        <div className="icon-up" />
      </div>
    </host>
  );
};

KunFixedButton.props = {
  clsName: {
    type: String,
  },
  message: {
    type: String,
    value: "kun-fixed-button",
    reflect: true,
    event: {
      type: "changeMessage",
    },
  },
};

export default getComponentOrDefine("kun-fixed-button", KunFixedButton);
