import { useEffect } from 'react';

export const useBlockBackButton = (enabled: boolean, callback: () => void) => {
  useEffect(() => {
    if (enabled && window) {
      if (window.history.scrollRestoration) {
        window.history.scrollRestoration = 'manual';
      }

      window.history.pushState(null, document.title, window.location.href);
      window.onpopstate = e => {
        e.preventDefault();
        window.history.pushState(null, document.title, window.location.href);
        callback?.();
      };
    }

    return () => {
      if (enabled && window) {
        window.history.back();
        window.onpopstate = null;
        window.history.scrollRestoration = 'auto';
      }
    };
  }, [enabled]);
};
