import { CSSProperties, useEffect, useState } from 'react';

export const useFixedButtonPosition = () => {
  const [buttonStyle, setButtonStyle] = useState<CSSProperties | undefined>();

  const updateButtonPosition = () => {
    const viewport = window.visualViewport;
    const viewportHeight = viewport?.height;
    const viewportOffsetTop = viewport?.offsetTop ?? 0;

    if (viewportHeight && viewportHeight < window.innerHeight) {
      setButtonStyle({ bottom: `${window.innerHeight - viewportHeight - viewportOffsetTop + 15}px` });
    } else {
      setButtonStyle(undefined);
    }
  };

  useEffect(() => {
    const handleResize = () => {
      updateButtonPosition();
    };

    visualViewport?.addEventListener('resize', handleResize);
    window.addEventListener('resize', handleResize); // fallback for window resize

    return () => {
      visualViewport?.removeEventListener('resize', handleResize);
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  useEffect(() => {
    const handleScroll = () => {
      updateButtonPosition();
    };

    window.addEventListener('scroll', handleScroll);

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

  return buttonStyle;
};
