/* aieo-faq-admin.js — FAQ manager panel (DMM tab `faq`).
 * Connected jQuery-UI sortables (reorder + drag-between-groups), inline group
 * CRUD, inline question rename, add/delete entries — all via AJAX to the
 * AIEO_DMM_FAQ handlers. Order persists to menu_order, group to faq_group. */
(function ($) {
	'use strict';

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

	function post(action, data, cb) {
		data = data || {};
		data.action = action;
		data.nonce  = cfg.nonce;
		$.post(cfg.ajaxurl, data)
			.done(function (j) { cb && cb(j); })
			.fail(function () { cb && cb({ success: false }); });
	}

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

	function err(j) {
		status((j && j.data && j.data.message) || i18n.error || 'Error', false);
	}

	// ── Drag reorder + reassign ──────────────────────────────────────────
	function serializeOrder() {
		var order = [];
		$('.aieo-faq-list').each(function () {
			var gid = parseInt($(this).data('group-id'), 10) || 0;
			$(this).children('.aieo-faq-item').each(function (i) {
				var pid = parseInt($(this).data('post-id'), 10) || 0;
				if (pid > 0) { order.push({ post_id: pid, group_id: gid, menu_order: i }); }
			});
		});
		return order;
	}

	function updateCounts() {
		$('.aieo-faq-section').each(function () {
			var n = $(this).find('.aieo-faq-item').length;
			$(this).find('.aieo-faq-section-count').text('(' + n + ')');
		});
		$('.aieo-faq-group-chip').each(function () {
			var gid = $(this).data('group-id');
			var n = $('.aieo-faq-list[data-group-id="' + gid + '"]').children('.aieo-faq-item').length;
			$(this).find('.aieo-faq-group-count').text('(' + n + ')');
		});
	}

	function saveOrder() {
		status(i18n.saving);
		post('aieo_faq_reorder', { order: JSON.stringify(serializeOrder()) }, function (j) {
			if (j && j.success) { status((j.data && j.data.message) || i18n.saved, true); updateCounts(); }
			else { err(j); }
		});
	}

	function initSortable() {
		if (!$.fn || !$.fn.sortable) { setTimeout(initSortable, 200); return; }
		$('.aieo-faq-list').sortable({
			items: '> .aieo-faq-item',
			handle: '.aieo-faq-handle',
			connectWith: '.aieo-faq-list',
			placeholder: 'aieo-faq-placeholder',
			forcePlaceholderSize: true,
			tolerance: 'pointer',
			cursor: 'grabbing',
			stop: function () { saveOrder(); }
		});
	}

	// ── Groups ───────────────────────────────────────────────────────────
	$(document).on('click', '#aieo-faq-add-group', function () {
		var name = ($('#aieo-faq-new-group').val() || '').trim();
		if (!name) { return; }
		status(i18n.saving);
		post('aieo_faq_add_group', { name: name }, function (j) {
			if (j && j.success) { window.location.reload(); } else { err(j); }
		});
	});

	$(document).on('click', '.aieo-faq-group-rename', function () {
		var $chip = $(this).closest('.aieo-faq-group-chip');
		var gid   = $chip.data('group-id');
		var cur   = $chip.find('.aieo-faq-group-name').text();
		var name  = window.prompt(i18n.rename || 'Rename group', cur);
		if (name === null) { return; }
		name = name.trim();
		if (!name) { return; }
		status(i18n.saving);
		post('aieo_faq_rename_group', { group_id: gid, name: name }, function (j) {
			if (j && j.success) { window.location.reload(); } else { err(j); }
		});
	});

	$(document).on('click', '.aieo-faq-group-delete', function () {
		var gid = $(this).closest('.aieo-faq-group-chip').data('group-id');
		if (!window.confirm(i18n.delGroup || 'Delete this group?')) { return; }
		status(i18n.saving);
		post('aieo_faq_delete_group', { group_id: gid }, function (j) {
			if (j && j.success) { window.location.reload(); } else { err(j); }
		});
	});

	// ── Entries ──────────────────────────────────────────────────────────
	$(document).on('click', '#aieo-faq-add', function () {
		var q = ($('#aieo-faq-new-q').val() || '').trim();
		var a = $('#aieo-faq-new-a').val() || '';
		var g = parseInt($('#aieo-faq-new-group').val(), 10) || 0;
		if (!q) { status(i18n.needQ || 'Enter a question.', false); return; }
		status(i18n.saving);
		post('aieo_faq_create', { question: q, answer: a, group_id: g }, function (j) {
			if (j && j.success) { window.location.reload(); } else { err(j); }
		});
	});

	$(document).on('click', '.aieo-faq-delete', function () {
		var $it = $(this).closest('.aieo-faq-item');
		var pid = $it.data('post-id');
		if (!window.confirm(i18n.delFaq || 'Delete this FAQ?')) { return; }
		status(i18n.saving);
		post('aieo_faq_delete', { post_id: pid }, function (j) {
			if (j && j.success) { $it.slideUp(150, function () { $it.remove(); updateCounts(); status(i18n.saved, true); }); }
			else { err(j); }
		});
	});

	// Inline question rename.
	$(document).on('click', '.aieo-faq-q', function () {
		var $q = $(this);
		if ($q.find('input').length) { return; }
		var cur = $q.text();
		var $in = $('<input type="text" class="aieo-faq-q-input">').val(cur);
		$q.empty().append($in);
		$in.trigger('focus').select();
		var done = false;
		function save() {
			if (done) { return; } done = true;
			var val = ($in.val() || '').trim();
			if (!val) { $q.text(cur); return; }
			var pid = $q.closest('.aieo-faq-item').data('post-id');
			$q.text(val);
			post('aieo_faq_update_q', { post_id: pid, question: val }, function (j) {
				if (j && j.success) { status(i18n.saved, true); } else { err(j); $q.text(cur); }
			});
		}
		$in.on('blur', save).on('keydown', function (e) {
			if (e.which === 13) { e.preventDefault(); $in.trigger('blur'); }
			else if (e.which === 27) { done = true; $q.text(cur); }
		});
	});

	$(initSortable);
})(jQuery);
