"use client";

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

interface DynamicScaleProps {
  children: React.ReactNode;
  className?: string;
}

export function DynamicScale({ children, className }: DynamicScaleProps) {
  const divRef = useRef<HTMLDivElement>(null);
  const [scale, setScale] = useState<number>(1);

  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) setScale(1);
    else {
      const dist = Math.abs(center - divY);
      const normalizedDist = dist / center;
      setScale(1.2 - normalizedDist * 0.2);
    }
  };

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

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

  return (
    <div
      ref={divRef}
      style={{
        scale: scale,
      }}
      className={`h-fit w-fit ${className}`}
    >
      {children}
    </div>
  );
}
