/* aieo-store-admin.js — Store Pages panel (DMM tab `store_pages`). Saves the
 * store-pages config card to seo.store_cpt_* via AIEO_DMM_Store::ajax_config_save,
 * then reloads so the CPT re-registers with the new base/labels. Admin-only. */
(function ($) {
	'use strict';

	var cfg  = window.aieoStore || {};
	var i18n = cfg.i18n || {};

	function status(msg, state) {
		var $s = $('#aieo-store-status');
		if (!$s.length) { return; }
		var color = state === false ? '#b91c1c' : (state === true ? '#15803d' : '#646970');
		$s.text(msg || '').css('color', color);
	}

	$(document).on('click', '#aieo-store-save', function () {
		var $b = $(this);
		$b.prop('disabled', true);
		status(i18n.saving);
		$.post(cfg.ajaxurl, {
			action:             'aieo_store_config_save',
			nonce:              cfg.nonce,
			store_cpt_enabled:  $('#aieo-store-cpt-enabled').is(':checked') ? '1' : '',
			store_cpt_base:     $('#aieo-store-cpt-base').val() || '',
			store_cpt_singular: $('#aieo-store-cpt-singular').val() || '',
			store_cpt_plural:   $('#aieo-store-cpt-plural').val() || ''
		}).done(function (j) {
			$b.prop('disabled', false);
			if (j && j.success) {
				status((j.data && j.data.message) || i18n.saved, true);
				// Reload so the CPT re-registers (labels/base) + permalinks flush.
				setTimeout(function () { window.location.reload(); }, 600);
			} else {
				status((j && j.data && j.data.message) || i18n.error, false);
			}
		}).fail(function () {
			$b.prop('disabled', false);
			status(i18n.error, false);
		});
	});
})(jQuery);
