import { useEffect, useState } from 'react';
import type { TargetRect } from '@/lib/application-tour/position';

function toTargetRect(element: HTMLElement): TargetRect {
    const rect = element.getBoundingClientRect();

    return {
        top: rect.top,
        left: rect.left,
        width: rect.width,
        height: rect.height,
    };
}

export function useTourTargetRect(
    selector: string | null,
    isActive: boolean,
): TargetRect | null {
    const [rect, setRect] = useState<TargetRect | null>(null);

    useEffect(() => {
        if (!isActive || !selector) {
            return;
        }

        const updateRect = () => {
            const element = document.querySelector<HTMLElement>(selector);

            if (!element) {
                setRect(null);

                return;
            }

            setRect(toTargetRect(element));
        };

        updateRect();

        const element = document.querySelector<HTMLElement>(selector);
        const resizeObserver =
            element && typeof ResizeObserver !== 'undefined'
                ? new ResizeObserver(updateRect)
                : null;

        resizeObserver?.observe(element as HTMLElement);

        window.addEventListener('resize', updateRect);
        window.addEventListener('scroll', updateRect, true);

        return () => {
            resizeObserver?.disconnect();
            window.removeEventListener('resize', updateRect);
            window.removeEventListener('scroll', updateRect, true);
            setRect(null);
        };
    }, [isActive, selector]);

    if (!isActive || !selector) {
        return null;
    }

    return rect;
}
