import {useRef, useEffect, useState, useCallback} from 'react';

/**
 * Hook to detect if text content is truncated with ellipsis
 * @param {Array} deps - Dependencies to trigger re-check (e.g., [text, width])
 * @param {Object} options - Configuration options
 * @param {boolean} options.watchResize - Watch for element resize (default: true)
 * @param {number} options.debounceMs - Debounce delay in ms (default: 100)
 * @returns {[React.RefObject, boolean]} - [ref to attach to element, isEllipsed state]
 */
export default function useIsEllipsed(deps = [], options = {}) {
    const {watchResize = true, debounceMs = 100} = options;
    const ref = useRef(null);
    const [isEllipsed, setIsEllipsed] = useState(false);
    const timeoutRef = useRef(null);

    const checkEllipsis = useCallback(() => {
        const element = ref.current;
        if (!element) {
            setIsEllipsed(false);
            return;
        }

        // Check both dimensions to support single-line and multi-line ellipsis
        const hasHorizontalEllipsis = element.scrollWidth > element.clientWidth;
        const hasVerticalEllipsis = element.scrollHeight > element.clientHeight;

        setIsEllipsed(hasHorizontalEllipsis || hasVerticalEllipsis);
    }, []);

    const debouncedCheck = useCallback(() => {
        if (timeoutRef.current) {
            clearTimeout(timeoutRef.current);
        }
        timeoutRef.current = setTimeout(checkEllipsis, debounceMs);
    }, [checkEllipsis, debounceMs]);

    useEffect(() => {
        checkEllipsis();
    }, [checkEllipsis, ...deps]);

    useEffect(() => {
        if (!watchResize) return;

        const element = ref.current;
        if (!element) return;

        // Use ResizeObserver for responsive detection
        const resizeObserver = new ResizeObserver(debouncedCheck);
        resizeObserver.observe(element);

        return () => {
            resizeObserver.disconnect();
            if (timeoutRef.current) {
                clearTimeout(timeoutRef.current);
            }
        };
    }, [watchResize, debouncedCheck]);

    return [ref, isEllipsed];
}