/* KBT SEO Assistant — Meta Box JS */
(function ($) {
	'use strict';

	var $btn      = $('#kbt-analyze-btn');
	var $keyword  = $('#kbt-focus-keyword');
	var $results  = $('#kbt-seo-results');
	var $score    = $('#kbt-score-number');
	var $circle   = $('#kbt-score-circle');
	var $checklist = $('#kbt-seo-checklist');

	var statusIcons = {
		good:    '✓',
		warning: '!',
		error:   '✕',
		info:    'i'
	};

	$btn.on('click', function () {
		var keyword = $keyword.val().trim();
		$btn.prop('disabled', true).text('Menganalisis...');

		// If in Gutenberg, save the post content first
		if (wp.data && wp.data.select('core/editor')) {
			wp.data.dispatch('core/editor').savePost();
		}

		// Small delay to let save complete
		setTimeout(function () {
			$.ajax({
				url: kbtSeo.ajax_url,
				type: 'POST',
				data: {
					action:  'kbt_seo_analyze',
					nonce:   kbtSeo.nonce,
					post_id: kbtSeo.post_id,
					keyword: keyword
				},
				success: function (res) {
					if (res.success) {
						renderResults(res.data);
					} else {
						$results.html('<p style="color:red;">Error: ' + (res.data || 'Unknown') + '</p>');
					}
				},
				error: function () {
					$results.html('<p style="color:red;">Gagal menghubungi server.</p>');
				},
				complete: function () {
					$btn.prop('disabled', false).text('Analisis SEO');
				}
			});
		}, 1500);
	});

	function renderResults(data) {
		var score = data.score || 0;
		var checks = data.checks || {};

		// Update score circle
		$score.text(score);
		$circle.removeClass('score-good score-ok score-bad');
		if (score >= 70) {
			$circle.addClass('score-good');
		} else if (score >= 40) {
			$circle.addClass('score-ok');
		} else {
			$circle.addClass('score-bad');
		}

		// Render check items — errors first, then warnings, then good
		var sorted = [];
		$.each(checks, function (key, check) {
			sorted.push(check);
		});
		sorted.sort(function (a, b) {
			var order = { error: 0, warning: 1, info: 2, good: 3 };
			return (order[a.status] || 3) - (order[b.status] || 3);
		});

		var html = '';
		$.each(sorted, function (i, check) {
			html += '<div class="kbt-check-item">';
			html += '<span class="kbt-check-icon status-' + check.status + '">' + (statusIcons[check.status] || '') + '</span>';
			html += '<div><span class="kbt-check-label">' + check.label + '</span><br>';
			html += '<span class="kbt-check-msg">' + check.msg + '</span></div>';
			html += '</div>';
		});

		$results.html(html);
		$checklist.show();
	}

	// Auto-analyze on page load if keyword exists
	$(function () {
		if ($keyword.val().trim()) {
			// Wait for Gutenberg to fully load
			setTimeout(function () {
				$btn.trigger('click');
			}, 3000);
		}
	});

})(jQuery);
