/**
 * AIEO — "Used for variations" save guard (classic product editor).
 *
 * WooCommerce allows MORE THAN ONE attribute to be flagged "Used for variations".
 * Operators doing this by mistake produces variations with an "Any …" axis and a
 * broken catalogue. This blocks saving a product while >1 attribute is ticked
 * "Used for variations", and (when deep-linked from the Problematic Variations
 * report with `aieo_focus_attributes=1`) jumps straight to the Attributes tab.
 */
(function ($) {
	'use strict';
	$(function () {
		// Deep-link: open the Attributes tab when asked.
		if (new URLSearchParams(window.location.search).get('aieo_focus_attributes')) {
			$('.product_data_tabs li.attribute_options > a, a[href="#product_attributes"]').first().trigger('click');
		}

		var MSG = (window.AIEO_VAR_GUARD && AIEO_VAR_GUARD.msg)
			|| 'Only one attribute may be set as “Used for variations”.';

		// Only variable products have "Used for variations" — checked live so a
		// type switch (simple → variable) mid-edit is handled correctly.
		function isVariable() {
			var $t = $('#product-type');
			return $t.length ? ($t.val() === 'variable')
				: ($('input:checkbox[name^="attribute_variation"]').length > 0);
		}

		// Count ticked "Used for variations" checkboxes (name="attribute_variation[i]").
		function varAttrCount() {
			return $('input:checkbox[name^="attribute_variation"]:checked').length;
		}

		function openAttributesTab() {
			$('.product_data_tabs li.attribute_options > a, a[href="#product_attributes"]').first().trigger('click');
		}

		function showNotice() {
			var $n = $('#aieo-var-guard-notice');
			if (!$n.length) {
				$n = $('<div id="aieo-var-guard-notice" class="notice notice-error"><p></p></div>');
				$('.wrap').first().prepend($n);
			}
			$n.find('p').text(MSG);
			$('html, body').animate({ scrollTop: 0 }, 200);
		}

		function guard(e) {
			if (isVariable() && varAttrCount() > 1) {
				if (e) { e.preventDefault(); e.stopImmediatePropagation(); }
				showNotice();
				openAttributesTab();
				return false;
			}
		}

		// Block the classic product-form submit + the Publish/Update buttons.
		$('form#post').on('submit', guard);
		$(document).on('click', '#publish, #save-post', function (e) {
			if (isVariable() && varAttrCount() > 1) { guard(e); }
		});
	});
})(jQuery);
