import React, { useEffect, useRef } from "react";

/**
 * Hook that detects clicks outside of a referenced element
 * @param callback - Function to call when clicking outside
 * @returns ref - Ref to attach to the element you want to detect clicks outside of
 */
export function useClickOutside<T extends HTMLElement = HTMLElement>(callback: () => void) {
  const ref = useRef<T>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        callback();
      }
    };

    // Add event listener
    document.addEventListener("mousedown", handleClickOutside);

    // Cleanup
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [callback]);

  return ref;
}

export const ClickOutside = ({
  children,
  callback,
}: {
  children: React.ReactNode;
  callback: () => void;
}) => {
  const ref = useClickOutside(callback);
  return React.createElement(
    "div",
    {
      ref,
    },
    children
  );
};
