// 功能：折叠大纲默认仅显示一级目录，滚动/光标自动定位中央标题并高亮
// version 0.0.4-neon
(async () => {
    /* ==========  1. 注入显眼样式（仅一次） ========== */
    if (!document.getElementById('outlineNeonStyle')) {
        const style = document.createElement('style');
        style.id = 'outlineNeonStyle';
        style.textContent = `
            .sy__outline .b3-list-item.outline-neon-focus {
                position: relative;
                background: linear-gradient(135deg, rgba(0,200,255,.15) 0%, rgba(0,255,180,.15) 100%);
                border-radius: 6px;
                transition: all .3s ease;
            }
            .sy__outline .b3-list-item.outline-neon-focus::before {
                content: '';
                position: absolute;
                left: 0;
                top: 4px;
                bottom: 4px;
                width: 4px;
                background: linear-gradient(180deg, #00c8ff 0%, #00ffb4 100%);
                border-radius: 2px;
                box-shadow: 0 0 6px #00c8ff, 0 0 12px #00ffb4;
            }
        `;
        document.head.appendChild(style);
    }

    /* ==========  2. 主逻辑（与原代码一致，仅替换高亮类） ========== */
    whenElementExist('.sy__outline > .fn__flex-1').then(async el => {
        observeChildAddition(el, node => {
            return node.tagName.toLowerCase() === 'ul' &&
                   node.classList.contains('b3-list') &&
                   node.querySelector('.b3-list-item');
        }, uls => {
            const ul = uls[0];
            Array.from(ul.children).forEach(item => {
                if (item.tagName === 'LI') {
                    const toggleBtn = item.querySelector('.b3-list-item__toggle');
                    const svg = toggleBtn?.querySelector('svg.b3-list-item__arrow');
                    if (svg && !svg.classList.contains('b3-list-item__arrow--open')) {
                        svg.classList.add('b3-list-item__arrow--open');
                    }
                }
                if (item.tagName === 'UL') {
                    item.classList.remove('fn__none');
                    itemsShow(item, false);
                }
                openCursorHeading();
                const ul = item.tagName === 'LI' ? item.nextElementSibling : item;
                item.addEventListener('mouseenter', () => {
                    if (ul && ul.tagName === 'UL') itemsShow(ul, true);
                });
                item.addEventListener('mouseleave', () => {
                    if (ul && ul.tagName === 'UL') {
                        itemsShow(ul, false);
                        openCursorHeading();
                    }
                });
            });

            const protyleContent = getProtyle()?.querySelector('.protyle-content');
            const wysiwyg = protyleContent?.querySelector('.protyle-wysiwyg');
            if (protyleContent && !protyleContent.scrollEventOutline) {
                protyleContent.scrollEventOutline = true;
                let ticking = false;
                protyleContent.addEventListener('scroll', () => {
                    if (!ticking) {
                        requestAnimationFrame(() => {
                            openCursorHeading('scroll', wysiwyg);
                            ticking = false;
                        });
                        ticking = true;
                    }
                });
            }
            openCursorHeading('load', wysiwyg);
        });

        document.addEventListener('selectionchange', () => {
            Array.from(el.firstElementChild.children).forEach(item => itemsShow(item, false));
            openCursorHeading();
        }, false);
    });

    /* --------- 中央标题检测 --------- */
    function getTopestHead(by = 'scroll', parentNode) {
        const center = window.innerHeight / 2;
        const headings = [...(parentNode || document).querySelectorAll('.h1,.h2,.h3,.h4,.h5,.h6')];
        let closest = null;
        let minDistance = Infinity;
        headings.forEach(h => {
            const distance = Math.abs(h.getBoundingClientRect().top - center);
            if (distance < minDistance) {
                minDistance = distance;
                closest = h;
            }
        });
        return closest;
    }

    /* --------- 展开 + 高亮 --------- */
    function openCursorHeading(by = 'cursor', parentNode) {
        const heading = by === 'cursor' ? isInHeading() : getTopestHead(by, parentNode);
        if (!heading) return;
        const headingNodeId = heading.dataset.nodeId;
        let node = document.querySelector('.sy__outline [data-node-id="' + headingNodeId + '"]');
        if (node && ['scroll', 'load'].includes(by)) {
            /* 去掉旧高亮 */
            document.querySelector('.sy__outline .outline-neon-focus')?.classList.remove('outline-neon-focus');
            /* 添加新高亮 */
            node.classList.add('outline-neon-focus');
            node.scrollIntoView({ block: 'center', behavior: 'smooth' });
        }
        while (node && !node.classList.contains('b3-list')) {
            if (node.tagName === 'UL' && node.classList.contains('fn__none')) {
                const li = node.previousElementSibling;
                if (li) {
                    const arrowSvg = li.querySelector('.b3-list-item__toggle svg.b3-list-item__arrow:not(.b3-list-item__arrow--open)');
                    if (arrowSvg) arrowSvg.classList.add('b3-list-item__arrow--open');
                }
                node.classList.remove('fn__none');
            }
            node = node.parentElement;
        }
    }

    /* --------- 工具函数 --------- */
    function isInHeading() {
        const el = getCursorElement();
        let heading = el?.closest('[data-type="NodeHeading"]');
        if (heading) return heading;
        const sibling = el?.closest('[data-node-index]');
        return findPreviousNodeHeading(sibling);
    }

    function findPreviousNodeHeading(el) {
        let s = el?.previousElementSibling;
        while (s) {
            if (s.getAttribute('data-type') === 'NodeHeading') return s;
            s = s.previousElementSibling;
        }
        return null;
    }

    function getCursorElement() {
        const sel = window.getSelection();
        if (sel.rangeCount > 0) {
            const container = sel.getRangeAt(0).startContainer;
            return container.nodeType === Node.TEXT_NODE ? container.parentElement : container;
        }
        return null;
    }

    function itemsShow(ul, isOpen) {
        if (isOpen) {
            ul.querySelectorAll('span.b3-list-item__toggle svg:not(.b3-list-item__arrow--open)')
              .forEach(svg => svg.classList.add('b3-list-item__arrow--open'));
            ul.querySelectorAll('ul.fn__none')
              .forEach(u => u.classList.remove('fn__none'));
        } else {
            ul.querySelectorAll('span.b3-list-item__toggle svg.b3-list-item__arrow--open')
              .forEach(svg => svg.classList.remove('b3-list-item__arrow--open'));
            ul.querySelectorAll('ul:not(.fn__none)')
              .forEach(u => u.classList.add('fn__none'));
        }
    }

    function observeChildAddition(el, filter, handler) {
        const obs = new MutationObserver(muts => {
            for (const m of muts) {
                if (m.type === 'childList') {
                    const added = Array.from(m.addedNodes)
                                       .filter(n => n.nodeType === Node.ELEMENT_NODE && filter(n));
                    if (added.length) handler(added);
                }
            }
        });
        obs.observe(el, { childList: true, subtree: false });
        return () => obs.disconnect();
    }

    function whenElementExist(selector, bySetTimeout = false, delay = 40) {
        return new Promise(resolve => {
            const check = () => {
                const el = typeof selector === 'function' ? selector() : document.querySelector(selector);
                if (el) resolve(el);
                else bySetTimeout ? setTimeout(check, delay) : requestAnimationFrame(check);
            };
            check();
        });
    }

    function getProtyle() {
        return document.querySelector('#editor') ||
               document.querySelector(`.protyle[data-id="` +
                   [...document.querySelectorAll('.layout-tab-bar [data-type="tab-header"]')]
                   .reduce((max, tab) => Number(tab?.dataset?.activetime) > Number(max?.dataset?.activetime || -1) ? tab : max, null)
                   ?.dataset?.id + `"]`);
    }
})();
