import { useEffect, useMemo } from 'react';
import { useIsMounted } from '../useIsMounted/index.js';
import { useSyncedRef } from '../useSyncedRef/index.js';
import { hasOwnProperty, off, on } from '../util/misc.js';
export function useEventListener(target, ...params) {
    const isMounted = useIsMounted();
    const listenerRef = useSyncedRef(params[1]);
    const eventListener = useMemo(() => function (...args) {
        if (!isMounted())
            return;
        if (typeof listenerRef.current === 'function') {
            listenerRef.current.apply(this, args);
        }
        else if (typeof listenerRef.current.handleEvent === 'function') {
            listenerRef.current.handleEvent.apply(this, args);
        }
    }, []);
    useEffect(() => {
        const tgt = isRefObject(target) ? target.current : target;
        if (!tgt)
            return;
        const restParams = params.slice(2);
        on(tgt, params[0], eventListener, ...restParams);
        return () => {
            off(tgt, params[0], eventListener, ...restParams);
        };
    }, [target, params[0]]);
}
function isRefObject(target) {
    return target !== null && typeof target === 'object' && hasOwnProperty(target, 'current');
}
