import './style.css';

/**
 * Makes an Elementor wrapper clickable while preserving native interaction inside nested controls.
 */
const initWrapperLink = (element) => {
  if (!element || element.dataset.calioWrapperLinkInit === 'yes') {
    return;
  }

  element.dataset.calioWrapperLinkInit = 'yes';

  const url = element.dataset.calioWrapperLinkUrl || '';
  const openExternal = element.dataset.calioWrapperLinkExternal === 'yes';
  const excludeSelector = element.dataset.calioWrapperLinkExcludeSelector || '';
  const isEditMode = typeof window.elementorFrontend?.isEditMode === 'function'
    ? window.elementorFrontend.isEditMode()
    : document.body.classList.contains('elementor-editor-active');

  if (!url) {
    return;
  }

  element.classList.add('calio-wrapper-link-host');

  if (!element.hasAttribute('tabindex')) {
    element.setAttribute('tabindex', '0');
  }

  if (!element.hasAttribute('role')) {
    element.setAttribute('role', 'link');
  }

  const shouldIgnoreClick = (target) => {
    const nativeIgnore = target?.closest('a, button, input, textarea, select, option, summary, label, iframe, video, audio, [role="button"], [role="link"]');
    if (nativeIgnore) {
      return true;
    }

    if (excludeSelector.trim() !== '') {
      try {
        return Boolean(target?.closest(excludeSelector));
      } catch (error) {
        return false;
      }
    }

    return false;
  };

  const hasSelection = () => (window.getSelection?.().toString() || '').trim().length > 0;

  const navigate = () => {
    if (isEditMode) {
      return;
    }

    if (openExternal) {
      window.open(url, '_blank', 'noopener,noreferrer');
      return;
    }

    window.location.href = url;
  };

  element.addEventListener('click', (event) => {
    if (shouldIgnoreClick(event.target) || hasSelection()) {
      return;
    }

    navigate();
  });

  element.addEventListener('keydown', (event) => {
    if (event.key !== 'Enter' && event.key !== ' ') {
      return;
    }

    if (shouldIgnoreClick(event.target)) {
      return;
    }

    event.preventDefault();
    navigate();
  });
};

const initAllWrapperLinks = (scope = document) => {
  const hosts = scope.matches?.('[data-calio-wrapper-link="yes"]')
    ? [scope]
    : Array.from(scope.querySelectorAll('[data-calio-wrapper-link="yes"]'));

  hosts.forEach(initWrapperLink);
};

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

let calioWrapperLinkHookBound = false;
const bindElementorWrapperLink = () => {
  if (calioWrapperLinkHookBound) {
    return true;
  }

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

  window.elementorFrontend.hooks.addAction('frontend/element_ready/global', ($scope) => {
    const root = $scope?.[0] || null;
    if (root) {
      initAllWrapperLinks(root);
    }
  });

  calioWrapperLinkHookBound = true;
  return true;
};

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