/**
 * Triggers FSLightbox refresh after dynamic content changes.
 */
import { flushPendingFsLightboxRefresh, requestFsLightboxRefresh } from '../core/app-fslightbox-bridge.js';
import { resolveHost } from '../core/app-dom.js';

export function initFsLightboxRefresh(root = document) {
  const host = resolveHost(root);
  const observerRoot = host === document ? document.body : host;

  let refreshTimer = 0;
  let observer = null;

  const scheduleRefresh = () => {
    if (refreshTimer) {
      return;
    }
    refreshTimer = window.setTimeout(() => {
      refreshTimer = 0;
      requestFsLightboxRefresh();
    }, 30);
  };

  if (!requestFsLightboxRefresh()) {
    scheduleRefresh();
  }
  requestFsLightboxRefresh();

  if (observerRoot && typeof MutationObserver !== 'undefined') {
    observer = new MutationObserver((mutations) => {
      for (const mutation of mutations) {
        for (const node of mutation.addedNodes) {
          if (!(node instanceof HTMLElement)) {
            continue;
          }
          if (node.matches?.('[data-fslightbox]') || node.querySelector?.('[data-fslightbox]')) {
            scheduleRefresh();
            return;
          }
        }
      }
    });
    observer.observe(observerRoot, { childList: true, subtree: true });
  }

  flushPendingFsLightboxRefresh();

  const destroy = () => {
    if (refreshTimer) {
      window.clearTimeout(refreshTimer);
      refreshTimer = 0;
    }
    if (observer) {
      observer.disconnect();
      observer = null;
    }
  };

  return { destroy };
}
