/* ==========================================================================
   SEOvault AI — SEO Analyzer JavaScript
   ========================================================================== */

(function($) {
	'use strict';

	var app = $('#seovaultseo-analyzer-app');
	if (!app.length) {
		return;
	}

	var nonce    = app.data('nonce');
	var ajaxUrl  = app.data('ajax-url');
	var hasData  = app.data('has-data') === '1';
	var initData = app.data('initial-data');

	var $runBtn     = $('#seovaultseo-run-analyzer');
	var $clearBtn   = $('#seovaultseo-clear-analyzer');
	var $loading    = $('#seovaultseo-analyzer-loading');
	var $empty      = $('#seovaultseo-analyzer-empty');
	var $results    = $('#seovaultseo-analyzer-results');
	var $summary    = $('#seovaultseo-analyzer-summary');
	var $scoreNum   = $('#seovaultseo-score-number');
	var $scoreArc   = $('#seovaultseo-score-arc');
	var $grade      = $('#seovaultseo-analyzer-grade');
	var $lastRun    = $('#seovaultseo-analyzer-last-run');

	var categoryLabels = {
		'priority': (typeof seovaultseo_analyzer !== 'undefined' && seovaultseo_analyzer.category_priority) || 'Priority',
		'basic': (typeof seovaultseo_analyzer !== 'undefined' && seovaultseo_analyzer.category_basic) || 'Basic SEO',
		'advanced': (typeof seovaultseo_analyzer !== 'undefined' && seovaultseo_analyzer.category_advanced) || 'Advanced SEO'
	};

	var statusIcons = {
		'ok': '<span class="dashicons dashicons-yes"></span>',
		'fail': '<span class="dashicons dashicons-no"></span>',
		'warning': '<span class="dashicons dashicons-warning"></span>'
	};

	var gradeLabels = {
		'good': (typeof seovaultseo_analyzer !== 'undefined' && seovaultseo_analyzer.grade_good) || 'Excellent',
		'average': (typeof seovaultseo_analyzer !== 'undefined' && seovaultseo_analyzer.grade_average) || 'Needs Improvement',
		'bad': (typeof seovaultseo_analyzer !== 'undefined' && seovaultseo_analyzer.grade_bad) || 'Poor'
	};

	// Circle circumference: 2 * PI * 52 = ~327
	var CIRCUMFERENCE = 327;

	// ─── Init ──────────────────────────────────────────────────────

	if (hasData && initData) {
		renderResults(initData);
	}

	// ─── Run analyzer ──────────────────────────────────────────────

	$runBtn.on('click', function(e) {
		e.preventDefault();
		runAnalysis();
	});

	// ─── Clear results ─────────────────────────────────────────────

	$clearBtn.on('click', function(e) {
		e.preventDefault();

		$.ajax({
			url: ajaxUrl,
			method: 'POST',
			data: {
				action: 'seovaultseo_clear_analyzer',
				nonce: nonce
			},
			success: function() {
				$results.empty().hide();
				$summary.hide();
				$clearBtn.hide();
				$empty.show();
				$scoreNum.text('—');
				$scoreArc.css('stroke-dashoffset', CIRCUMFERENCE);
				$grade.removeClass('grade-good grade-average grade-bad').text('');
				$lastRun.text('');
			}
		});
	});

	// ─── Expand/collapse test cards ────────────────────────────────

	$(document).on('click', '.seovaultseo-test-card-header', function() {
		var $card = $(this).closest('.seovaultseo-test-card');
		$card.toggleClass('expanded');
	});

	// ─── Functions ─────────────────────────────────────────────────

	function runAnalysis() {
		$runBtn.prop('disabled', true);
		$runBtn.find('.dashicons').addClass('is-active');
		$empty.hide();
		$results.hide();
		$summary.hide();
		$loading.show();

		$.ajax({
			url: ajaxUrl,
			method: 'POST',
			data: {
				action: 'seovaultseo_run_analyzer',
				nonce: nonce
			},
			success: function(response) {
				$loading.hide();
				$runBtn.prop('disabled', false);
				$runBtn.find('.dashicons').removeClass('is-active');

				if (response.success && response.data) {
					renderResults(response.data);
				} else {
					var msg = (response.data && response.data.message) || ((typeof seovaultseo_analyzer !== 'undefined' && seovaultseo_analyzer.analysis_failed) || 'Analysis failed.');
					$empty.show();
					$empty.find('p').text(msg);
				}
			},
			error: function(xhr, status, error) {
				$loading.hide();
				$runBtn.prop('disabled', false);
				$runBtn.find('.dashicons').removeClass('is-active');
				$empty.show();
				$empty.find('p').text((seovaultseo_analyzer.ajax_error || 'AJAX error: ') + error);
			}
		});
	}

	function renderResults(data) {
		if (!data || !data.grouped) {
			return;
		}

		// Update score circle
		var percent = data.metrics.percent || 0;
		var grade = data.metrics.grade || 'bad';
		var offset = CIRCUMFERENCE - (CIRCUMFERENCE * percent / 100);

		$scoreNum.text(percent + '%');
		$scoreArc.css('stroke-dashoffset', offset);
		$scoreArc.removeClass('grade-good grade-average grade-bad').addClass('grade-' + grade);

		$grade.removeClass('grade-good grade-average grade-bad')
			.addClass('grade-' + grade)
			.text(gradeLabels[grade] || grade);

		// Last checked date
		if (data.date) {
			var prefix = (typeof seovaultseo_analyzer !== 'undefined' && seovaultseo_analyzer.last_checked) || 'Last checked:';
			$lastRun.text(prefix + ' ' + data.date.date + ' ' + data.date.time);
		}

		// Update summary
		var statuses = data.metrics.statuses || {};
		$('#seovaultseo-summary-ok').text(statuses.ok || 0);
		$('#seovaultseo-summary-fail').text(statuses.fail || 0);
		$('#seovaultseo-summary-warning').text(statuses.warning || 0);
		$summary.show();

		// Render test cards grouped by category
		var html = '';
		$.each(data.grouped, function(category, tests) {
			html += '<div class="seovaultseo-analyzer-category">';
			html += '<h3 class="seovaultseo-analyzer-category-title">' + (categoryLabels[category] || category) + '</h3>';

			$.each(tests, function(testId, test) {
				html += renderTestCard(test);
			});

			html += '</div>';
		});

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

	function renderTestCard(test) {
		var status = test.status || 'warning';
		var icon = statusIcons[status] || statusIcons.warning;
		var title = test.title || test.test_id || 'Test';
		var message = test.message || '';
		var howToFix = test.how_to_fix || '';
		var description = test.description || '';
		var info = test.info || [];

		var html = '<div class="seovaultseo-test-card">';
		html += '<div class="seovaultseo-test-card-header">';
		html += '<div class="seovaultseo-test-status-icon status-' + status + '">' + icon + '</div>';
		html += '<div class="seovaultseo-test-body">';
		html += '<p class="seovaultseo-test-title">' + escapeHtml(title) + '</p>';
		html += '<p class="seovaultseo-test-message">' + message + '</p>';
		html += '</div>';
		html += '<span class="dashicons dashicons-arrow-down-alt2 seovaultseo-test-toggle"></span>';
		html += '</div>';

		html += '<div class="seovaultseo-test-details">';
		if (description) {
			html += '<h4>Description</h4>';
			html += '<p>' + description + '</p>';
		}
		if (howToFix) {
			html += '<h4>How to Fix</h4>';
			html += '<p>' + howToFix + '</p>';
		}
		if (info && info.length > 0) {
			html += '<h4>Affected Posts</h4>';
			html += '<ul class="seovaultseo-test-info-list">';
			for (var i = 0; i < info.length; i++) {
				html += '<li>' + escapeHtml(info[i]) + '</li>';
			}
			html += '</ul>';
		}
		html += '</div>';

		html += '</div>';
		return html;
	}

	function escapeHtml(str) {
		if (!str) {
			return '';
		}
		return str
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#039;');
	}

})(jQuery);
