// Smartlink — scrollspy + smooth scroll para a página pública.
// Versão pública: sem section shells animados nem device preview (esses
// pertencem ao preview admin no Moon.Client). Apenas scrollspy + smooth scroll.

(function () {
    function findScroller(start) {
        var node = start && start.parentElement;
        while (node && node !== document.body) {
            var oy = getComputedStyle(node).overflowY;
            if (oy === 'auto' || oy === 'scroll') return node;
            node = node.parentElement;
        }
        return null;
    }

    /**
     * Regista um listener de scroll que notifica o dotnetHelper sempre que a
     * secção activa muda. Devolve um handle .dispose() para desregistar quando
     * o componente é desmontado ou a lista muda.
     */
    window.smartlinkReportScrollspy = function (sectionIds, dotnetHelper, methodName) {
        if (!Array.isArray(sectionIds) || !dotnetHelper) return null;

        var sections = sectionIds
            .map(function (id) { return document.getElementById(id); })
            .filter(function (el) { return !!el; });
        if (!sections.length) return null;

        var lastId = null;
        var scroller = findScroller(sections[0]);
        var emitter = scroller || window;

        var onScroll = function () {
            var offset = 160;
            var current = sections[0].id;
            for (var i = 0; i < sections.length; i++) {
                var rect = sections[i].getBoundingClientRect();
                if (rect.top - offset <= 0) current = sections[i].id;
            }
            if (current !== lastId) {
                lastId = current;
                dotnetHelper.invokeMethodAsync(methodName, current).catch(function () { /* swallow disposed errors */ });
            }
        };

        // primeira avaliação no próximo frame para garantir que o layout assentou
        requestAnimationFrame(onScroll);

        emitter.addEventListener('scroll', onScroll, { passive: true });
        if (emitter !== window) {
            window.addEventListener('scroll', onScroll, { passive: true });
        }

        return {
            dispose: function () {
                emitter.removeEventListener('scroll', onScroll);
                if (emitter !== window) {
                    window.removeEventListener('scroll', onScroll);
                }
            }
        };
    };

    /**
     * Smooth scroll para o elemento com `id`. Se houver scroll container,
     * scrolla esse; caso contrário scrolla o window. `offset` é a margem
     * superior (para a nav sticky não tapar o título).
     */
    window.smartlinkReportScrollTo = function (elementId, offset) {
        var el = document.getElementById(elementId);
        if (!el) return;
        offset = typeof offset === 'number' ? offset : 80;

        var scroller = findScroller(el);
        if (scroller) {
            var top = el.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop - offset;
            scroller.scrollTo({ top: top, behavior: 'smooth' });
        } else {
            var topW = el.getBoundingClientRect().top + window.scrollY - offset;
            window.scrollTo({ top: topW, behavior: 'smooth' });
        }
    };

    /**
     * Descarrega o PDF do informe na própria página (sem abrir novo separador).
     * Lança em erro/HTTP não-OK para o botão Blazor repor o estado de loading.
     */
    window.downloadSmartlinkPdf = async function (url) {
        var resp = await fetch(url, { headers: { 'Accept': 'application/pdf' } });
        if (!resp.ok) throw new Error('PDF render failed: ' + resp.status);

        var blob = await resp.blob();
        var name = 'informe.pdf';
        var cd = resp.headers.get('Content-Disposition');
        if (cd) {
            var m = /filename\*?=(?:UTF-8'')?["']?([^"';]+)/i.exec(cd);
            if (m && m[1]) name = decodeURIComponent(m[1]);
        }

        var objUrl = URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = objUrl;
        a.download = name;
        document.body.appendChild(a);
        a.click();
        a.remove();
        URL.revokeObjectURL(objUrl);
    };
})();
