import { useEffect, useState } from 'react';
import { useInView } from 'react-intersection-observer';

import { AutoplayMode } from 'src/types/stream';

const useAutoplay = () => {
  const [mode, setMode] = useState<AutoplayMode>(AutoplayMode.AUTO);
  const [isTabVisible, setIsTabVisible] = useState(!document.hidden);

  const { ref, inView } = useInView();

  useEffect(() => {
    const handleVisibilityChange = () => {
      setIsTabVisible(!document.hidden);
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);

    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, []);

  const setAlwaysMode = () => {
    setMode(AutoplayMode.ALWAYS);
  };

  const shouldPlayOptions = {
    [AutoplayMode.AUTO]: inView && isTabVisible,
    [AutoplayMode.ALWAYS]: true,
  };

  const shouldPlay = shouldPlayOptions[mode];

  return {
    ref,
    shouldPlay,
    setAlwaysMode,
  };
};

export default useAutoplay;
