import * as React from "react";
import {useEffect, useRef, useState} from "react";

interface AnchoringProps {
  text: string, // Default: Découvrez-en plus !
  linkTo: string // Default: #main-page
}

export const Anchoring = ({ data }: { data: AnchoringProps }) => {
  const [opacity, setOpacity] = useState(1);
  const anchoringRef = useRef(null);

  const handleScroll = () => {
    const scrollTop = window.scrollY || window.pageYOffset;
    const elementHeight = anchoringRef.current.clientHeight;
    const newOpacity = (elementHeight - scrollTop) / elementHeight;
    setOpacity(newOpacity);
  };

  useEffect(() => {
    handleScroll(); // Initialize opacity on mount

    window.addEventListener('scroll', handleScroll);

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

  const anchoringStyle = {
    opacity: opacity,
    transition: 'opacity 0.3s', // You can add a transition for a smooth effect
  };

  return (
      <div className="mx-auto">
        <div
            className="anchoring"
            ref={anchoringRef}
            style={anchoringStyle}
        >
          <a href={`${ data.linkTo }`}>
            <h1>{ data.text }</h1>
            <img
                src="data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMjQgMjQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0ibTExLjI1OCAxNi4yNDItNi02YTEuMDUgMS4wNSAwIDEgMSAxLjQ4NC0xLjQ4NEwxMiAxNC4wMTVsNS4yNTgtNS4yNTdhMS4wNSAxLjA1IDAgMSAxIDEuNDg0IDEuNDg0bC02IDZhMS4wNSAxLjA1IDAgMCAxLTEuNDg0IDBaIiBmaWxsPSIjZmZmZmZmIiBmaWxsLXJ1bGU9Im5vbnplcm8iIGNsYXNzPSJmaWxsLTAwMDAwMCI+PC9wYXRoPjwvc3ZnPg=="/>
          </a>
        </div>
      </div>
  );
};
