import { useState, useEffect } from 'react';

interface Dimensions {
    width: number;
    height: number;
    leftOffset: number;
    topOffset: number;
}

export function useAvailableDimensions(): Dimensions {
    const [dimensions, setDimensions] = useState<Dimensions>(() => calculateDimensions());

    useEffect(() => {
        const adminMenu = document.querySelector('#adminmenuwrap') as HTMLElement;
        const adminBar = document.querySelector('#wpadminbar') as HTMLElement;

        if (!adminMenu || !adminBar) {
            return;
        }

        const resizeObserver = new ResizeObserver(() => {
            setDimensions(calculateDimensions());
        });

        // Observe both elements for size changes
        resizeObserver.observe(adminMenu);
        resizeObserver.observe(adminBar);

        // Also listen to window resize
        const handleResize = () => {
            setDimensions(calculateDimensions());
        };
        window.addEventListener('resize', handleResize);

        return () => {
            resizeObserver.disconnect();
            window.removeEventListener('resize', handleResize);
        };
    }, []);

    return dimensions;
}

function calculateDimensions(): Dimensions {
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;

    const adminMenu = document.querySelector('#adminmenuwrap') as HTMLElement;
    const adminBar = document.querySelector('#wpadminbar') as HTMLElement;

    const menuWidth = adminMenu ? adminMenu.offsetWidth : 0;
    const barHeight = adminBar ? adminBar.offsetHeight : 0;

    return {
        width: viewportWidth - menuWidth,
        height: viewportHeight - barHeight,
        leftOffset: menuWidth,
        topOffset: barHeight,
    };
}

