/* =============================================================================
 * Storzen — Floating Cart (frontend)
 *
 * Behavior:
 *   • Open/close mini-cart drawer (reveal_action = mini_cart)
 *   • Show/hide hover preview (reveal_action = preview)
 *   • Listen for WooCommerce's `added_to_cart` event → trigger animation + reveal
 *   • Body scroll lock when drawer open + ESC closes it
 *   • Hide-when-empty toggle: show/hide the button based on the count badge
 *
 * Notes:
 *   • The cart count badge and total are auto-refreshed by WC's own fragment
 *     system — we don't fetch them ourselves.
 *   • This module uses jQuery only to listen for WC's `added_to_cart` event,
 *     which is dispatched via jQuery (so a native addEventListener won't catch it).
 * ========================================================================== */
(function ($) {
	'use strict';

	if (typeof szFloatingCart === 'undefined') { return; }

	var FC = {

		$fc:        null,
		$btn:       null,
		$drawer:    null,
		$preview:   null,
		hideEmpty:  false,
		revealMode: 'mini_cart',

		init: function () {
			this.$fc = $('.storzen-fc');
			if (!this.$fc.length) { return; }

			this.$btn       = this.$fc.find('.storzen-fc__btn').first();
			this.$drawer    = $('#storzen-fc-drawer');
			this.$preview   = this.$fc.find('.storzen-fc__preview').first();
			this.hideEmpty  = !!szFloatingCart.hideWhenEmpty;
			this.revealMode = szFloatingCart.revealAction || 'mini_cart';

			this.bindButton();
			this.bindDrawer();
			this.bindCartEvents();
			this.syncEmptyState();
		},

		/* ───── Button click — open drawer / preview ───── */
		bindButton: function () {
			var self = this;

			// "go_to_cart" mode is a plain <a>; nothing to bind.
			if (this.revealMode === 'go_to_cart') { return; }

			this.$btn.on('click', function (e) {
				if (self.revealMode === 'mini_cart') {
					e.preventDefault();
					self.openDrawer();
				} else if (self.revealMode === 'preview') {
					// On touch devices :hover doesn't work — tap toggles the preview.
					if (self.isTouch()) {
						e.preventDefault();
						self.togglePreview();
					}
				}
			});
		},

		/* ───── Drawer open/close ───── */
		bindDrawer: function () {
			var self = this;
			if (!this.$drawer.length) { return; }

			// Close on overlay / X button click.
			this.$drawer.on('click', '[data-storzen-fc-close]', function (e) {
				e.preventDefault();
				self.closeDrawer();
			});

			// Close on Escape.
			$(document).on('keydown.storzenFc', function (e) {
				if (e.key === 'Escape' && self.$drawer.hasClass('is-open')) {
					self.closeDrawer();
				}
			});
		},

		openDrawer: function () {
			if (!this.$drawer.length) { return; }
			this.$drawer.addClass('is-open').attr('aria-hidden', 'false');
			this.$btn.attr('aria-expanded', 'true').attr('aria-label', szFloatingCart.i18n.closeCart);
			$('body').addClass('storzen-fc-drawer-open');

			// Move focus inside the drawer for accessibility.
			var $closeBtn = this.$drawer.find('.storzen-fc__drawer-close').first();
			if ($closeBtn.length) {
				// Defer so the transition has started.
				window.setTimeout(function () { $closeBtn.trigger('focus'); }, 50);
			}
		},

		closeDrawer: function () {
			if (!this.$drawer.length) { return; }
			this.$drawer.removeClass('is-open').attr('aria-hidden', 'true');
			this.$btn.attr('aria-expanded', 'false').attr('aria-label', szFloatingCart.i18n.openCart);
			$('body').removeClass('storzen-fc-drawer-open');

			// Return focus to the floating button.
			this.$btn.trigger('focus');
		},

		togglePreview: function () {
			if (!this.$preview.length) { return; }
			this.$preview.toggleClass('is-open');
			var open = this.$preview.hasClass('is-open');
			this.$preview.attr('aria-hidden', open ? 'false' : 'true');

			// On touch devices, bind a one-shot outside-click handler so tapping
			// elsewhere closes the preview cleanly. (Hover-out doesn't fire on touch.)
			var self = this;
			if (open && this.isTouch()) {
				window.setTimeout(function () {
					$(document).one('click.storzenFcPreview', function (e) {
						if (!$(e.target).closest('.storzen-fc').length) {
							self.$preview.removeClass('is-open').attr('aria-hidden', 'true');
						}
					});
				}, 0);
			}
		},

		/* ───── WC cart event integration ───── */
		bindCartEvents: function () {
			var self = this;

			// Fires when WC's fragment system finishes refreshing.
			$(document.body).on('added_to_cart', function () {
				self.flashAnimation();
				self.syncEmptyState();

				// Auto-open the drawer on add-to-cart when in drawer mode.
				// Some stores prefer this UX; gated behind a class so themes
				// can opt out by removing it.
				if (self.revealMode === 'mini_cart' && self.$fc.hasClass('storzen-fc--auto-open')) {
					self.openDrawer();
				}
			});

			// WC also fires removed_from_cart / wc_fragments_refreshed — both
			// trigger fragment refresh which already updates our count/total.
			// We just need to re-evaluate the empty state.
			$(document.body).on('removed_from_cart wc_fragments_refreshed', function () {
				self.syncEmptyState();
			});
		},

		/* ───── Trigger the on-add animation ───── */
		flashAnimation: function () {
			var self = this;
			if (!this.$fc.length) { return; }

			// Remove first (so consecutive adds re-trigger the animation).
			this.$fc.removeClass('is-added');

			// Force a reflow so the next class addition starts a new animation.
			void this.$fc[0].offsetWidth;

			this.$fc.addClass('is-added');

			window.setTimeout(function () {
				self.$fc.removeClass('is-added');
			}, 800);
		},

		/* ───── Hide-when-empty toggle ───── */
		syncEmptyState: function () {
			if (!this.hideEmpty) { return; }
			var $count = this.$fc.find('.storzen-fc__count').first();
			if (!$count.length) {
				// No badge rendered (show_count_badge = false). Fall back to
				// reading the total's data-empty attr.
				var $total = this.$fc.find('.storzen-fc__total').first();
				if ($total.length && $total.attr('data-empty') === '1') {
					this.$fc.addClass('storzen-fc--empty');
				} else {
					this.$fc.removeClass('storzen-fc--empty');
				}
				return;
			}

			var count = parseInt($count.attr('data-count'), 10) || 0;
			if (count <= 0) {
				this.$fc.addClass('storzen-fc--empty');
			} else {
				this.$fc.removeClass('storzen-fc--empty');
			}
		},

		/* ───── Helpers ───── */
		isTouch: function () {
			return ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
		}
	};

	$(function () { FC.init(); });

	// Public namespace for debugging / external integrations.
	window.StorzenFloatingCart = FC;

})(jQuery);
