/**
 * DreamFast Commerce Float free frontend.
 */
(function () {
	'use strict';

	var config = window.dreamfastCfConfig || {};
	if (!config.showCart && !config.showContact) {
		return;
	}

	function findCartButton() {
		var selectors = config.cartSelectors || [
			'form.cart .single_add_to_cart_button',
			'.entry-summary .single_add_to_cart_button',
			'.single_add_to_cart_button',
			'button[name="add-to-cart"]',
		];

		for (var i = 0; i < selectors.length; i++) {
			var element = document.querySelector(selectors[i]);
			if (element) {
				return element;
			}
		}

		return null;
	}

	function initStickyCart() {
		var bar = document.getElementById('df-sf-sticky-cart');
		if (!bar) {
			return;
		}

		var target = findCartButton();
		if (!target || typeof IntersectionObserver === 'undefined') {
			bar.setAttribute('hidden', 'hidden');
			return;
		}

		var barIsBottom = function () {
			if (bar.classList.contains('df-sf-sticky-cart--bottom')) {
				return true;
			}
			if (bar.classList.contains('df-sf-sticky-cart--top')) {
				return false;
			}
			return !!(window.matchMedia && window.matchMedia('(max-width: 781px)').matches);
		};

		var observer = new IntersectionObserver(
			function (entries) {
				entries.forEach(function (entry) {
					var originalIsVisible = entry.isIntersecting;
					bar.classList.toggle('is-active', !originalIsVisible);
					document.body.classList.toggle('df-sf-sticky-cart-active', !originalIsVisible && barIsBottom());
					bar.setAttribute('aria-hidden', originalIsVisible ? 'true' : 'false');
				});
			},
			{ threshold: 0, rootMargin: '0px' }
		);

		observer.observe(target);
		bar.addEventListener('click', function (event) {
			var button = event.target.closest('[data-df-sf-action]');
			if (!button) {
				return;
			}

			var action = button.getAttribute('data-df-sf-action');
			if (action === 'add-to-cart') {
				event.preventDefault();
				var original = findCartButton();
				if (original) {
					original.click();
				}
			}

			if (action === 'scroll-to-form') {
				event.preventDefault();
				var form = document.querySelector('.variations_form, form.cart');
				if (form) {
					form.scrollIntoView({ behavior: 'smooth', block: 'center' });
				}
			}
		});
	}

	function boot() {
		if (config.showCart) {
			initStickyCart();
		}
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', boot);
	} else {
		boot();
	}
})();
