"use client";

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

interface DynamicRotateProps {
  opposite: boolean;
  children: React.ReactNode;
  className?: string;
  start: number;
  end: number;
}

export function DynamicRotate({
  opposite,
  children,
  className,
  start,
  end,
}: DynamicRotateProps) {
  const divRef = useRef<HTMLDivElement>(null);
  const [rotation, setRotation] = useState<number>(start);

  const handleScroll = () => {
    if (!divRef.current) return;
    const windowH = window.innerHeight;
    const center = windowH / 2;

    const divY = divRef.current.getBoundingClientRect().y;
    if (divY > windowH || divY < 0) setRotation(start);
    else {
      const dist = Math.abs(center - divY);
      const normalizedDist = dist / center;
      setRotation(start - normalizedDist * (start - end));
    }
  };

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  return (
    <div
      ref={divRef}
      style={{
        transform: `rotate(${opposite ? -rotation : rotation}deg)`,
      }}
      className={`h-fit w-fit ${className}`}
    >
      {children}
    </div>
  );
}
