let dotnetRef = null;
let handler = null;
let vvHandler = null;

function debounce(fn, ms) {
    let t;
    return () => {
        clearTimeout(t);
        t = setTimeout(fn, ms);
    };
}

function report() {
    const height = window.innerHeight;
    const width = window.innerWidth;

    // If you care about “actual visible” area (mobile / zoom / browser chrome):
    const vv = window.visualViewport;
    const vvHeight = vv ? Math.round(vv.height) : null;
    const vvWidth = vv ? Math.round(vv.width) : null;

    if (dotnetRef) {
        dotnetRef.invokeMethodAsync("WindowChanged", height, width, vvHeight, vvWidth);
    }
}

export function start(ref, debounceMs = 150) {
    dotnetRef = ref;

    handler = debounce(report, debounceMs);
    window.addEventListener("resize", handler);
    window.addEventListener("orientationchange", handler);

    if (window.visualViewport) {
        vvHandler = debounce(report, debounceMs);
        window.visualViewport.addEventListener("resize", vvHandler);
    }

    // fire immediately
    report();
}

export function stop() {
    if (handler) {
        window.removeEventListener("resize", handler);
        window.removeEventListener("orientationchange", handler);
        handler = null;
    }

    if (window.visualViewport && vvHandler) {
        window.visualViewport.removeEventListener("resize", vvHandler);
        vvHandler = null;
    }

    dotnetRef = null;
}
