import { darkLine } from '@/styles/colors';
import { getScrollRange } from '@/styles/dimensions';
import styled from '@emotion/styled';
import { useLayoutEffect, useRef } from 'react';

const VariableManager = styled.div`
  --scroll-anim-background-color: rgb(255, 255, 255, 1);
  --scroll-anim-border-color: ${darkLine}ff;
  --scroll-anim-percentage: 1;
  display: contents;
`;

const AnimationVariableManager = ({ children }: { children: React.ReactNode[] | React.ReactNode }) => {
  const variableManagerRef = useRef<HTMLDivElement>(null);
  useLayoutEffect(() => {
    const handleScroll = () => {
      if (variableManagerRef.current) {
        const scrollPosition = window.scrollY;
        const scrollRange = getScrollRange();
        const scrollPercentage = Math.max(0, Math.min(1, scrollPosition / scrollRange));
        variableManagerRef.current.style.setProperty(
          '--scroll-anim-background-color',
          `rgba(255,255,255,${scrollPercentage})`
        );
        variableManagerRef.current.style.setProperty(
          '--scroll-anim-border-color',
          `${darkLine}${Math.round(scrollPercentage * 255)
            .toString(16)
            .padStart(2, '0')}`
        );
        variableManagerRef.current.style.setProperty('--scroll-anim-percentage', `${0.75 + 0.25 * scrollPercentage}`);
      }
    };
    handleScroll();
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);
  return <VariableManager ref={variableManagerRef}>{children}</VariableManager>;
};

export default AnimationVariableManager;
