import type { RefObject } from 'react';
import { useState, useEffect, useCallback } from 'react';

type UseFullscreenOptions = {
  ref?: RefObject<HTMLElement | null>;
};

export const useFullscreen = (options?: UseFullscreenOptions) => {
  const [isFullscreen, setIsFullscreen] = useState(() => !!document.fullscreenElement);

  const getElement = useCallback(() => {
    if (options?.ref?.current) {
      return options.ref.current;
    }
    return document.documentElement;
  }, [options?.ref]);

  useEffect(() => {
    const handleChange = () => {
      setIsFullscreen(!!document.fullscreenElement);
    };

    document.addEventListener('fullscreenchange', handleChange);
    return () => document.removeEventListener('fullscreenchange', handleChange);
  }, []);

  const enterFullscreen = useCallback(async () => {
    const elem = getElement();
    if (!document.fullscreenElement && elem) {
      try {
        await elem.requestFullscreen();
      } catch (err) {
        console.error('Failed to enter fullscreen:', err);
      }
    }
  }, [getElement]);

  const exitFullscreen = useCallback(async () => {
    if (document.fullscreenElement) {
      try {
        await document.exitFullscreen();
      } catch (err) {
        console.error('Failed to exit fullscreen:', err);
      }
    }
  }, []);

  const toggleFullscreen = useCallback(async () => {
    if (document.fullscreenElement) {
      await exitFullscreen();
    } else {
      await enterFullscreen();
    }
  }, [enterFullscreen, exitFullscreen]);

  return {
    isFullscreen,
    fullscreen: enterFullscreen,
    enterFullscreen,
    exitFullscreen,
    toggleFullscreen,
  };
};
