import './style.css';

const toNumber = (value, fallback = 0) => {
  const parsed = Number.parseInt(String(value), 10);
  return Number.isFinite(parsed) ? parsed : fallback;
};

const isEnabled = (value) => value === 'yes' || value === 'true' || value === true || value === '1';

const initStylishList = (root) => {
  root.querySelectorAll('.calio-stylish-list').forEach((list) => {
    const items = Array.from(list.querySelectorAll('.calio-stylish-list-item'));
    if (!items.length) {
      return;
    }

    if (window.elementorFrontend?.isEditMode?.()) {
      items.forEach((item) => item.classList.add('is-visible'));
      return;
    }

    if (!isEnabled(list.dataset.useEntranceAnimation)) {
      items.forEach((item) => item.classList.add('is-visible'));
      return;
    }

    if (list.__calioStylishObserver && typeof list.__calioStylishObserver.disconnect === 'function') {
      list.__calioStylishObserver.disconnect();
      list.__calioStylishObserver = null;
    }

    if (typeof window.IntersectionObserver !== 'function') {
      items.forEach((item) => item.classList.add('is-visible'));
      return;
    }

    const stagger = Math.max(0, toNumber(list.dataset.animationStagger, 120));
    const observer = new window.IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (!entry.isIntersecting) {
            return;
          }

          const item = entry.target;
          if (!(item instanceof HTMLElement)) {
            return;
          }

          const fallbackDelay = Math.max(0, item.dataset.index ? toNumber(item.dataset.index, 0) * stagger : 0);
          if (!item.style.getPropertyValue('--calio-stylish-item-delay') && fallbackDelay > 0) {
            item.style.setProperty('--calio-stylish-item-delay', `${fallbackDelay}ms`);
          }

          item.classList.add('is-visible');
          observer.unobserve(item);
        });
      },
      {
        threshold: 0.18,
        rootMargin: '0px 0px -8% 0px',
      },
    );

    items.forEach((item, index) => {
      item.dataset.index = String(index);
      observer.observe(item);
    });

    list.__calioStylishObserver = observer;
  });
};

const boot = (scope = document) => {
  initStylishList(scope);
};

document.addEventListener('DOMContentLoaded', () => {
  boot(document);
});

let calioStylishListHookBound = false;
const bindElementorStylishList = () => {
  if (calioStylishListHookBound) {
    return true;
  }

  if (!window.elementorFrontend?.hooks) {
    return false;
  }

  window.elementorFrontend.hooks.addAction('frontend/element_ready/calio-stylish-list.default', ($scope) => {
    const root = $scope?.[0] || document;
    boot(root);
  });

  calioStylishListHookBound = true;
  return true;
};

window.addEventListener('elementor/frontend/init', bindElementorStylishList);
if (!bindElementorStylishList()) {
  let attempts = 0;
  const timer = window.setInterval(() => {
    attempts += 1;
    if (bindElementorStylishList() || attempts >= 40) {
      window.clearInterval(timer);
    }
  }, 250);
}
