import './style.css';

const DEFAULT_SPEED = 2400;
const EXIT_DURATION = 260;

const initRotator = (rotator) => {
  if (!rotator || rotator.dataset.calioRotatorInit === 'yes') {
    return;
  }

  let words = [];

  try {
    words = JSON.parse(rotator.dataset.words || '[]');
  } catch (error) {
    words = [];
  }

  if (!Array.isArray(words) || words.length <= 1) {
    return;
  }

  const wordNode = rotator.querySelector('.calio-accent-headline-rotator-word');
  if (!wordNode) {
    return;
  }

  rotator.dataset.calioRotatorInit = 'yes';

  let index = 0;
  let isTransitioning = false;
  let intervalId = null;
  const speed = Math.max(parseInt(rotator.dataset.speed || `${DEFAULT_SPEED}`, 10) || DEFAULT_SPEED, 1200);
  const canPause = rotator.classList.contains('can-pause');

  const showNextWord = () => {
    if (isTransitioning) {
      return;
    }

    isTransitioning = true;
    rotator.classList.add('is-changing');

    window.setTimeout(() => {
      index = (index + 1) % words.length;
      wordNode.textContent = words[index];
      rotator.classList.remove('is-changing');
      isTransitioning = false;
    }, EXIT_DURATION);
  };

  const startTimer = () => {
    if (intervalId !== null) {
      return;
    }

    intervalId = window.setInterval(showNextWord, speed);
    rotator.dataset.calioRotatorTimer = `${intervalId}`;
  };

  const stopTimer = () => {
    if (intervalId === null) {
      return;
    }

    window.clearInterval(intervalId);
    intervalId = null;
    delete rotator.dataset.calioRotatorTimer;
  };

  startTimer();

  if (canPause) {
    rotator.addEventListener('mouseenter', stopTimer);
    rotator.addEventListener('mouseleave', startTimer);
    rotator.addEventListener('focusin', stopTimer);
    rotator.addEventListener('focusout', startTimer);
  }
};

const bootstrapAccentHeadline = (scope) => {
  const root = scope instanceof Element || scope instanceof Document ? scope : document;
  root.querySelectorAll('.calio-accent-headline-rotator').forEach(initRotator);
};

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

const bindElementorAccentHeadline = () => {
  if (bindElementorAccentHeadline._bound) {
    return true;
  }

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

  window.elementorFrontend.hooks.addAction('frontend/element_ready/global', (scope) => {
    bootstrapAccentHeadline(scope);
  });

  bindElementorAccentHeadline._bound = true;
  return true;
};

window.addEventListener('elementor/frontend/init', bindElementorAccentHeadline);

if (document.readyState === 'loading') {
  document.addEventListener('readystatechange', () => {
    if (document.readyState === 'interactive' || document.readyState === 'complete') {
      bindElementorAccentHeadline();
    }
  });
} else if (!bindElementorAccentHeadline()) {
  let attempts = 0;
  const timer = window.setInterval(() => {
    attempts += 1;
    if (bindElementorAccentHeadline() || attempts >= 40) {
      window.clearInterval(timer);
    }
  }, 250);
}
