import './style.css';

const clamp = (value) => Math.max(0, Math.min(100, value));

const setPosition = (widget, value) => {
  const nextValue = clamp(Number.parseFloat(String(value)));
  const position = Number.isFinite(nextValue) ? nextValue : 50;
  const input = widget.querySelector('.calio-comparison-range');

  widget.style.setProperty('--calio-comparison-position', `${position}%`);

  if (input && String(input.value) !== String(position)) {
    input.value = String(position);
  }
};

const updateFromPointer = (widget, event) => {
  const rect = widget.getBoundingClientRect();
  if (!rect.width) {
    return;
  }

  const clientX = event.touches?.[0]?.clientX ?? event.clientX;
  if (typeof clientX !== 'number') {
    return;
  }

  const isRtl = window.getComputedStyle(widget).direction === 'rtl';
  const raw = ((clientX - rect.left) / rect.width) * 100;
  setPosition(widget, isRtl ? 100 - raw : raw);
};

const initComparison = (scope = document) => {
  const root = scope instanceof Element || scope instanceof Document ? scope : document;

  root.querySelectorAll('[data-calio-image-comparison]').forEach((widget) => {
    if (widget.dataset.calioComparisonReady === '1') {
      return;
    }

    widget.dataset.calioComparisonReady = '1';
    const input = widget.querySelector('.calio-comparison-range');
    setPosition(widget, input?.value || widget.dataset.start || 50);

    input?.addEventListener('input', () => {
      setPosition(widget, input.value);
    });

    let isDragging = false;

    const stopDrag = () => {
      isDragging = false;
      widget.classList.remove('is-dragging');
    };

    widget.addEventListener('pointerdown', (event) => {
      if (event.button !== 0) {
        return;
      }

      isDragging = true;
      widget.classList.add('is-dragging');
      widget.setPointerCapture?.(event.pointerId);
      updateFromPointer(widget, event);
    });

    widget.addEventListener('pointermove', (event) => {
      if (!isDragging) {
        return;
      }

      updateFromPointer(widget, event);
    });

    widget.addEventListener('pointerup', stopDrag);
    widget.addEventListener('pointercancel', stopDrag);
    widget.addEventListener('lostpointercapture', stopDrag);
  });
};

const boot = (scope = document) => {
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => initComparison(scope), { once: true });
  } else {
    initComparison(scope);
  }
};

boot(document);

let elementorHooked = false;
const hookElementor = () => {
  if (elementorHooked || !window.elementorFrontend?.hooks) {
    return false;
  }

  window.elementorFrontend.hooks.addAction('frontend/element_ready/calio-image-comparison-slider.default', ($scope) => {
    boot($scope?.[0] || document);
  });
  elementorHooked = true;
  return true;
};

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