'use client';

import { RefObject, useEffect } from 'react';

export function useClickOutside(
  ref: RefObject<HTMLDivElement | null>,
  fn: (event: Event) => void,
) {
  useEffect(() => {
    const handleClickOutside = (event: Event) => {
      const el = ref?.current;
      if (event instanceof MouseEvent && window !== undefined) {
        const x = event?.offsetX || 0;
        const width = window?.innerWidth - 18;
        if (x >= width) {
          return;
        }
      }
      if (!el || el.contains((event?.target as Node) || null)) {
        return;
      }
      fn(event);
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [ref, fn]);
}
