/**
 * AIEO Product Options — library admin JS. Drives group create/edit + options
 * CRUD on the DMM "Product Options" panel. Conditional price-rule editing is
 * layered on in a later step.
 */
(function ($) {
	'use strict';

	var cfg  = window.aieoOptionGroups || {};
	var i18n = cfg.i18n || {};
	var $root = $('#aieo-og-root');
	if (!$root.length) { return; }

	function status(msg, ok) {
		var $s = $('#aieo-og-status');
		$s.text(msg || '');
		$s.css('color', ok === false ? '#b91c1c' : (ok ? '#15803d' : '#646970'));
	}
	function post(action, data) {
		return $.post(cfg.ajaxurl, $.extend({ action: action, nonce: cfg.nonce }, data || {}));
	}
	function esc(s) { return $('<div>').text(s == null ? '' : String(s)).html(); }

	function openEditor(title) {
		$('#aieo-og-editor-title').text(title);
		$('#aieo-og-editor').removeClass('aieo-og-hidden');
		$('html,body').animate({ scrollTop: $('#aieo-og-editor').offset().top - 40 }, 200);
	}
	function resetGroupForm() {
		$('#aieo-og-group-id').val(0);
		$('#aieo-og-name').val('');
		$('#aieo-og-type').val('checkbox');
		$('#aieo-og-min,#aieo-og-max,#aieo-og-free').val(0);
		$('#aieo-og-policy').val('expensive_free');
		$('#aieo-og-desc').val('');
		$('#aieo-og-options-wrap').addClass('aieo-og-hidden');
		$('#aieo-og-options tbody').empty();
	}

	// --- Group editor open ---
	$('#aieo-og-new').on('click', function () {
		resetGroupForm();
		openEditor(i18n.newGroup || 'New group');
		status('');
	});
	$('#aieo-og-cancel').on('click', function () { window.location.reload(); });

	$(document).on('click', '.aieo-og-edit', function (e) {
		e.preventDefault();
		var id = $(this).closest('tr').data('id');
		post('aieo_og_get_group', { id: id }).done(function (r) {
			if (!r || !r.success) { return; }
			var g = r.data.group;
			$('#aieo-og-group-id').val(g.id);
			$('#aieo-og-name').val(g.name);
			$('#aieo-og-type').val(g.select_type);
			$('#aieo-og-min').val(g.min_select);
			$('#aieo-og-max').val(g.max_select);
			$('#aieo-og-free').val(g.included_free);
			$('#aieo-og-policy').val(g.free_policy);
			$('#aieo-og-desc').val(g.description || '');
			openEditor((i18n.editGroup || 'Edit') + ' — ' + (g.name || ''));
			$('#aieo-og-options-wrap').removeClass('aieo-og-hidden');
			renderOptions(r.data.options || []);
			status('');
		});
	});

	// --- Save group ---
	$('#aieo-og-save-group').on('click', function () {
		var name = $.trim($('#aieo-og-name').val());
		if (!name) { status(i18n.name || 'Name required', false); return; }
		status(i18n.saving || 'Saving…');
		post('aieo_og_save_group', {
			id:            $('#aieo-og-group-id').val(),
			name:          name,
			select_type:   $('#aieo-og-type').val(),
			min_select:    $('#aieo-og-min').val(),
			max_select:    $('#aieo-og-max').val(),
			included_free: $('#aieo-og-free').val(),
			free_policy:   $('#aieo-og-policy').val(),
			description:   $('#aieo-og-desc').val()
		}).done(function (r) {
			if (r && r.success) {
				$('#aieo-og-group-id').val(r.data.id);
				$('#aieo-og-options-wrap').removeClass('aieo-og-hidden');
				status(i18n.saved || 'Saved.', true);
			} else {
				status((r && r.data && r.data.message) || 'Error', false);
			}
		}).fail(function () { status('Request failed', false); });
	});

	// --- Options ---
	function renderOptions(opts) {
		var $tb = $('#aieo-og-options tbody').empty();
		(opts || []).forEach(function (o) { $tb.append(optRow(o)); });
	}
	function optRow(o) {
		var price = parseFloat(o.price_delta || 0).toFixed(2);
		var avail = o.availability === 'out_of_stock' ? 'Sold out'
			: (o.availability === 'in_stock' ? 'In stock' : ('Auto' + (o.sku ? (' · ' + o.sku) : '')));
		return $(
			'<tr class="aieo-og-opt-row" data-id="' + parseInt(o.id, 10) + '">' +
			'<td>' + esc(o.label) + '</td>' +
			'<td class="num">' + price + '</td>' +
			'<td>' + (parseInt(o.default_selected, 10) ? '✓' : '—') + '</td>' +
			'<td>' + (parseInt(o.exclude_from_allowance, 10) ? '✓' : '—') + '</td>' +
			'<td>' + esc(avail) + '</td>' +
			'<td class="num"><a href="#" class="aieo-og-rules-link">' + (i18n.rules || 'Rules') + '</a> · ' +
			'<a href="#" class="aieo-og-del" data-which="options">' + (i18n.del || 'Delete') + '</a></td>' +
			'</tr>'
		);
	}

	$('#aieo-og-add-option').on('click', function () {
		var gid = $('#aieo-og-group-id').val();
		if (!gid || gid === '0') { status('Save the group first.', false); return; }
		var label = $.trim($('#aieo-og-opt-label').val());
		if (!label) { status('Option label required.', false); return; }
		var payload = {
			group_id:               gid,
			label:                  label,
			price_delta:            $('#aieo-og-opt-price').val(),
			sku:                    $('#aieo-og-opt-sku').val(),
			availability:           $('#aieo-og-opt-avail').val(),
			default_selected:       $('#aieo-og-opt-default').is(':checked') ? 1 : 0,
			exclude_from_allowance: $('#aieo-og-opt-premium').is(':checked') ? 1 : 0
		};
		status(i18n.saving || 'Saving…');
		post('aieo_og_save_option', payload).done(function (r) {
			if (r && r.success) {
				$('#aieo-og-options tbody').append(optRow($.extend({ id: r.data.id }, payload)));
				$('#aieo-og-opt-label,#aieo-og-opt-sku').val('');
				$('#aieo-og-opt-price').val(0);
				$('#aieo-og-opt-default,#aieo-og-opt-premium').prop('checked', false);
				status(i18n.saved || 'Saved.', true);
			} else {
				status((r && r.data && r.data.message) || 'Error', false);
			}
		}).fail(function () { status('Request failed', false); });
	});

	// --- Delete (group or option) ---
	$(document).on('click', '.aieo-og-del', function (e) {
		e.preventDefault();
		if (!window.confirm(i18n.confirmDel || 'Delete?')) { return; }
		var $el = $(this), which = $el.data('which'), $row = $el.closest('tr'), id = $row.data('id');
		post('aieo_og_delete', { which: which, id: id }).done(function (r) {
			if (r && r.success) {
				if (which === 'groups') { window.location.reload(); }
				else { $row.remove(); $('#aieo-og-rules').addClass('aieo-og-hidden'); status(i18n.saved || 'Saved.', true); }
			} else {
				status('Error', false);
			}
		});
	});

	// --- Price rules editor (per option) ---
	function renderRulesList(rules) {
		var $tb = $('#aieo-og-rules-list tbody').empty();
		if (!rules || !rules.length) {
			$tb.append('<tr><td class="aieo-og-muted">' + (i18n.noRules || 'No rules yet — the flat price applies.') + '</td><td></td></tr>');
			return;
		}
		rules.forEach(function (rule) {
			$('<tr data-id="' + parseInt(rule.id, 10) + '"><td>' + esc(rule.desc) + '</td>' +
				'<td class="num"><a href="#" class="aieo-og-rule-del">' + (i18n.del || 'Delete') + '</a></td></tr>').appendTo($tb);
		});
	}
	function loadRules(oid) {
		post('aieo_og_get_rules', { option_id: oid }).done(function (r) {
			if (!r || !r.success) { return; }
			$('#aieo-og-rules-oid').val(oid);
			$('#aieo-og-rules-opt').text(r.data.option.label);
			var $wg = $('#aieo-og-rule-wgroup').empty().append('<option value="0">— ' + (i18n.any || 'any') + ' —</option>');
			(r.data.groups || []).forEach(function (g) { $('<option/>').val(g.id).text(g.name).appendTo($wg); });
			$('#aieo-og-rule-woption').empty().append('<option value="0">—</option>').prop('disabled', true);
			var $sc = $('#aieo-og-rule-scope').empty().append('<option value="0">' + (i18n.allProducts || 'All products') + '</option>');
			(r.data.assignments || []).forEach(function (a) { $('<option/>').val(a.assignment_id).text(a.name).appendTo($sc); });
			$('#aieo-og-rule-price').val(0);
			renderRulesList(r.data.rules);
			$('#aieo-og-rules').removeClass('aieo-og-hidden');
		});
	}

	$(document).on('click', '.aieo-og-rules-link', function (e) {
		e.preventDefault();
		var oid = $(this).closest('tr').data('id');
		loadRules(oid);
		$('html,body').animate({ scrollTop: $('#aieo-og-rules').offset().top - 40 }, 200);
	});
	$('#aieo-og-rules-close').on('click', function (e) { e.preventDefault(); $('#aieo-og-rules').addClass('aieo-og-hidden'); });

	// When a condition group is chosen, load its options into the "is" select.
	$('#aieo-og-rule-wgroup').on('change', function () {
		var gid = parseInt(this.value, 10) || 0;
		var $wo = $('#aieo-og-rule-woption').empty().append('<option value="0">—</option>');
		if (!gid) { $wo.prop('disabled', true); return; }
		post('aieo_og_get_group', { id: gid }).done(function (r) {
			if (!r || !r.success) { return; }
			(r.data.options || []).forEach(function (o) { $('<option/>').val(o.id).text(o.label).appendTo($wo); });
			$wo.prop('disabled', false);
		});
	});

	$('#aieo-og-rule-add').on('click', function () {
		var oid = $('#aieo-og-rules-oid').val();
		var wg = parseInt($('#aieo-og-rule-wgroup').val(), 10) || 0;
		var wo = parseInt($('#aieo-og-rule-woption').val(), 10) || 0;
		if (wg > 0 && wo <= 0) { status(i18n.pickWhen || 'Pick which option the condition is on.', false); return; }
		status(i18n.saving || 'Saving…');
		post('aieo_og_save_rule', {
			option_id:           oid,
			when_group_id:       wg,
			when_option_id:      wo,
			scope_assignment_id: parseInt($('#aieo-og-rule-scope').val(), 10) || 0,
			price_delta:         $('#aieo-og-rule-price').val()
		}).done(function (r) {
			if (r && r.success) { loadRules(oid); status(i18n.saved || 'Saved.', true); }
			else { status((r && r.data && r.data.message) || 'Error', false); }
		}).fail(function () { status('Request failed', false); });
	});

	$(document).on('click', '.aieo-og-rule-del', function (e) {
		e.preventDefault();
		var id = $(this).closest('tr').data('id'), oid = $('#aieo-og-rules-oid').val();
		post('aieo_og_delete', { which: 'prices', id: id }).done(function (r) {
			if (r && r.success) { loadRules(oid); }
		});
	});

})(jQuery);
