import { useEffect, useMemo, useState } from "react";

import { mobileAndTabletCheck } from "@/assets/three/helpers/CameraControl";
import { QUIZ_STEPS, QUIZ_STEPS_VARIANTS } from "@/config/data";
import { useWindowSize } from "@/hooks";
import { useStore } from "@/store";

import styles from "./styles.module.scss";

interface BoundSize {
  width: number;
  height: number;
}

const Object3dBounds = ({ children }: { children?: React.ReactNode }) => {
  const [boundSize, setBoundSize] = useState<BoundSize>({
    width: 0,
    height: 0,
  });
  const windowSize = useWindowSize();
  const step = useStore.use.step();

  const isMobile = mobileAndTabletCheck();

  const cs = useMemo(() => {
    const root = document.querySelector(":root");
    return (root && getComputedStyle(root)) || null;
  }, []);

  const footerHeight = useMemo(() => {
    return parseInt(cs?.getPropertyValue("--footer-height") || "48px");
  }, [cs]);

  useEffect(() => {
    const resultsUIElement = document.getElementById("results-ui");
    const boundsUI = resultsUIElement?.getBoundingClientRect();
    const isResultsStep = QUIZ_STEPS[step]?.id === QUIZ_STEPS_VARIANTS.results;
    const halfHeight = windowSize.height / 2;
    const mobileHeight = halfHeight * 0.85;
    const boundsUIHeight = boundsUI?.height || halfHeight;
    const uiResultsHeight =
      boundsUIHeight > halfHeight - footerHeight
        ? windowSize.height - footerHeight - boundsUIHeight
        : halfHeight;

    const size =
      (isResultsStep ? uiResultsHeight : isMobile ? mobileHeight : halfHeight) -
      footerHeight;
    setBoundSize({ width: size, height: size });
  }, [windowSize, footerHeight, step]);

  return (
    <div
      style={{ width: `${boundSize.width}px`, height: `${boundSize.height}px` }}
      className={styles.object3dBounds}
    >
      {children}
    </div>
  );
};

export default Object3dBounds;
