(() => {
  'use strict';
  if (document.documentElement.dataset.scrollTheme !== 'sentiment-analysis') return;

  const force = (element, declarations) => {
    if (!element) return;
    for (const [property, value] of Object.entries(declarations)) {
      element.style.setProperty(property, value, 'important');
    }
  };

  const unlock = () => {
    const html = document.documentElement;
    const body = document.body;
    const root = document.querySelector('#root,#app,#__next,[data-reactroot]');
    if (!body || !root) return false;

    html.dataset.apuSentimentScroll = 'v5.3';
    body.dataset.apuSentimentScroll = 'v5.3';

    force(html, {
      height: 'auto', 'max-height': 'none', 'min-height': '100%',
      'overflow-x': 'hidden', 'overflow-y': 'auto'
    });
    force(body, {
      height: 'auto', 'max-height': 'none', 'min-height': '100dvh',
      'overflow-x': 'hidden', 'overflow-y': 'visible', position: 'relative'
    });
    force(root, {
      height: 'auto', 'max-height': 'none', 'min-height': '100dvh',
      overflow: 'visible', width: '100%'
    });

    const shell = root.firstElementChild;
    if (shell) {
      shell.dataset.apuSentimentShell = 'true';
      force(shell, {
        height: 'auto', 'max-height': 'none', 'min-height': '100dvh',
        overflow: 'visible', width: '100%'
      });
    }

    const sidebar = shell?.querySelector(':scope > aside') || root.querySelector('aside');
    if (sidebar) sidebar.dataset.apuSentimentSidebar = 'true';

    const main = shell?.querySelector(':scope > main') || root.querySelector('main,[role="main"]');
    if (main) {
      main.dataset.apuSentimentMain = 'true';
      force(main, {
        height: 'auto', 'max-height': 'none', 'min-height': '100dvh',
        overflow: 'visible', position: 'relative'
      });

      const content = [...main.children].find((node) => {
        if (!(node instanceof HTMLElement) || node.tagName === 'HEADER') return false;
        const classes = String(node.className || '');
        const style = getComputedStyle(node);
        return /overflow-(auto|y-auto)/.test(classes) ||
          style.overflowY === 'auto' || style.overflowY === 'scroll';
      }) || main.querySelector(':scope > div:last-child');

      if (content instanceof HTMLElement) {
        content.dataset.apuSentimentContent = 'true';
        const priorScroll = content.scrollTop;
        force(content, {
          flex: '0 0 auto', height: 'auto', 'max-height': 'none',
          'min-height': '0', 'overflow-x': 'visible', 'overflow-y': 'visible',
          width: '100%'
        });
        if (priorScroll > 0 && window.scrollY === 0) {
          requestAnimationFrame(() => window.scrollTo({top: priorScroll, behavior: 'auto'}));
        }
        content.scrollTop = 0;
      }
    }

    return true;
  };

  let queued = false;
  const queueUnlock = () => {
    if (queued) return;
    queued = true;
    requestAnimationFrame(() => {
      queued = false;
      unlock();
    });
  };

  const onRouteChange = () => {
    queueUnlock();
    requestAnimationFrame(() => window.scrollTo({top: 0, behavior: 'auto'}));
  };

  for (const method of ['pushState', 'replaceState']) {
    const original = history[method];
    if (typeof original !== 'function' || original.__apuSentimentPatched) continue;
    const patched = function (...args) {
      const result = original.apply(this, args);
      window.dispatchEvent(new Event('apu:sentiment-route'));
      return result;
    };
    patched.__apuSentimentPatched = true;
    history[method] = patched;
  }

  window.addEventListener('popstate', onRouteChange);
  window.addEventListener('apu:sentiment-route', onRouteChange);
  window.addEventListener('pageshow', queueUnlock);
  window.addEventListener('resize', queueUnlock, {passive: true});
  window.visualViewport?.addEventListener('resize', queueUnlock, {passive: true});

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', queueUnlock, {once: true});
  } else {
    queueUnlock();
  }

  const observer = new MutationObserver(queueUnlock);
  observer.observe(document.documentElement, {childList: true, subtree: true});
  setTimeout(() => observer.disconnect(), 20000);
})();
