let footerMetrics = { width: 88, bottom: 0, revision: -1, generation: -1 };
let pageHandlesFooter = false;
let legacyStyle = null;
let legacyFooter = null;
let legacyLast = '';
let legacyCandidate = '';
let legacyAttempts = 0;
let legacySequence = 0;
let legacyFrame = 0;
const legacySizes = new ResizeObserver(() => scheduleLegacy());
const scheduleLegacy = () => {
    if (!legacyFrame) legacyFrame = requestAnimationFrame(updateLegacy);
};
const updateLegacy = () => {
    legacyFrame = 0;
    if (pageHandlesFooter || document.querySelector('[data-native-footer-slot][data-native-footer-version="2"]')) {
        legacySequence += 1;
        pageHandlesFooter = true; legacyMutations.disconnect();
        legacyStyle?.remove(); legacyStyle = null; legacySizes.disconnect(); legacyFooter = null;
        return;
    }
    const shell = document.querySelector('[data-testid="app-shell"]');
    const bar = shell?.querySelector('footer[data-footer-width]');
    if (!shell || !bar || !document.head || footerMetrics.revision < 0) return;
    if (!legacyStyle) { legacyStyle = document.createElement('style'); document.head.appendChild(legacyStyle); }
    const css = `[data-testid="app-shell"]{padding-bottom:0!important} footer[data-footer-width]{height:${48 + footerMetrics.bottom}px!important;padding-bottom:${footerMetrics.bottom}px!important;padding-left:${footerMetrics.width}px!important;justify-content:flex-end} footer[data-footer-width] [data-footer-part="@version"]{display:none!important}`;
    if (legacyStyle.textContent !== css) { legacyStyle.textContent = css; window.dispatchEvent(new Event('resize')); }
    if (legacyFooter !== bar) { legacySizes.disconnect(); legacySizes.observe(bar); legacyFooter = bar; }
    const rect = bar.getBoundingClientRect();
    const { width, revision, generation } = footerMetrics;
    const slot = {x:rect.x, y:rect.y, width, height:48,
                  viewportWidth:innerWidth, viewportHeight:innerHeight, revision, generation};
    const value = JSON.stringify(slot);
    if (value !== legacyCandidate) { legacyCandidate = value; legacyLast = ''; legacyAttempts = 0; }
    if (value !== legacyLast && legacyAttempts < 10) {
        legacyAttempts += 1;
        legacyLast = value;
        const request = ++legacySequence;
        const expired = setTimeout(() => {
            if (request === legacySequence && legacyAttempts < 10) { legacySequence += 1; legacyLast = ''; scheduleLegacy(); }
        }, 1000);
        window.webkit.messageHandlers.heinzelFooter.postMessage(slot).then(ok => {
            clearTimeout(expired);
            if (request === legacySequence && ok !== true && legacyAttempts < 10) { legacyLast = ''; setTimeout(scheduleLegacy, 200); }
        }).catch(() => { clearTimeout(expired); if (request === legacySequence && legacyAttempts < 10) { legacyLast = ''; setTimeout(scheduleLegacy, 200); } });
    }
};
const legacyMutations = new MutationObserver(scheduleLegacy);
legacyMutations.observe(document, { childList:true, subtree:true, attributes:true,
    attributeFilter:['data-native-footer-version'] });
window.addEventListener('resize', scheduleLegacy);
window.addEventListener('scroll', scheduleLegacy, true);
window.addEventListener('hz:footer-relocated', scheduleLegacy);
const footer = Object.freeze({
    metrics: () => ({ ...footerMetrics }),
    reportSlot: slot => {
        // Older pages report without a stamp. The compatibility reporter measures their footer itself.
        if (slot.revision !== footerMetrics.revision || slot.generation !== footerMetrics.generation ||
            slot.revision < 0 || slot.generation < 0) return Promise.resolve(false);
        return window.webkit.messageHandlers.heinzelFooter.postMessage(slot);
    },
});
Object.defineProperty(window, "__heinzelUpdateFooter", { value: (width, bottom, revision, generation) => {
    footerMetrics = { width, bottom, revision, generation };
    legacyLast = '';
    legacyCandidate = '';
    legacyAttempts = 0;
    legacySequence += 1;
    scheduleLegacy();
    window.dispatchEvent(new Event("heinzel-native-footer-metrics"));
}});
