(function () {
	'use strict';

	var lastText = null;
	var timer = null;
	var running = false;

	function getEditorText() {
		if (window.wp && wp.data && wp.data.select) {
			var editor = wp.data.select('core/editor');
			if (editor && editor.getEditedPostContent) {
				return [
					editor.getEditedPostAttribute('title') || '',
					editor.getEditedPostAttribute('excerpt') || '',
					editor.getEditedPostContent() || ''
				].join('\n\n');
			}
		}

		var title = document.getElementById('title');
		var excerpt = document.getElementById('excerpt');
		var content = document.getElementById('content');
		var contentValue = content ? content.value : '';
		if (window.tinymce && window.tinymce.get('content')) {
			contentValue = window.tinymce.get('content').getContent();
		}

		return [title ? title.value : '', excerpt ? excerpt.value : '', contentValue].join('\n\n');
	}

	function escapeHtml(value) {
		var div = document.createElement('div');
		div.textContent = value == null ? '' : String(value);
		return div.innerHTML;
	}

	function render(data) {
		var panel = document.getElementById('claimprism-live-panel');
		if (!panel) return;

		var status = panel.querySelector('.cg-live-status');
		var summary = panel.querySelector('.cg-live-summary');
		var list = panel.querySelector('.cg-live-findings');
		var findings = data && Array.isArray(data.findings) ? data.findings : [];

		if (!findings.length) {
			status.textContent = ClaimPrism.strings.clear;
			status.className = 'cg-live-status cg-status-clear';
			summary.hidden = true;
			list.innerHTML = '';
			return;
		}

		var critical = findings.filter(function (f) { return f.severity === 'critical'; }).length;
		var high = findings.filter(function (f) { return f.severity === 'high'; }).length;
		status.textContent = findings.length + ' ' + ClaimPrism.strings.found;
		status.className = 'cg-live-status cg-status-risk';
		summary.hidden = false;
		summary.innerHTML = '<strong>' + findings.length + '</strong> total · <strong>' + critical + '</strong> critical · <strong>' + high + '</strong> high';

		list.innerHTML = findings.slice(0, 20).map(function (finding) {
			return '<article class="cg-live-finding cg-live-' + escapeHtml(finding.severity) + '">' +
				'<div><span class="cg-live-badge">' + escapeHtml(finding.severity) + '</span> <strong>' + escapeHtml(finding.matched_phrase) + '</strong></div>' +
				'<p>' + escapeHtml(finding.rule_label) + '</p>' +
				'<details><summary>Why review this?</summary><p>' + escapeHtml(finding.description) + '</p><a href="' + escapeHtml(finding.source_url) + '" target="_blank" rel="noopener noreferrer">Official source</a></details>' +
			'</article>';
		}).join('');
	}

	function check(force) {
		var panel = document.getElementById('claimprism-live-panel');
		if (!panel || running) return;

		var text = getEditorText();
		if (!force && text === lastText) return;
		lastText = text;
		if (!text.replace(/<[^>]+>/g, '').trim()) return;

		running = true;
		var status = panel.querySelector('.cg-live-status');
		status.textContent = ClaimPrism.strings.checking;

		wp.apiFetch({ path: ClaimPrism.endpoint, method: 'POST', data: { text: text } })
			.then(render)
			.catch(function () {
				status.textContent = ClaimPrism.strings.error;
				status.className = 'cg-live-status cg-status-error';
			})
			.finally(function () { running = false; });
	}

	function queueCheck() {
		window.clearTimeout(timer);
		timer = window.setTimeout(function () { check(false); }, 650);
	}

	function bindEvidenceRows() {
		var list = document.getElementById('claimprism-evidence-list');
		var add = document.querySelector('.cg-add-evidence');
		var template = document.getElementById('tmpl-claimprism-evidence-row');
		if (!list || !add || !template) return;

		add.addEventListener('click', function () {
			var index = Date.now();
			var html = template.innerHTML.replace(/\{\{INDEX\}\}/g, index);
			list.insertAdjacentHTML('beforeend', html);
		});

		list.addEventListener('click', function (event) {
			if (!event.target.classList.contains('cg-remove-evidence')) return;
			var row = event.target.closest('.cg-evidence-row');
			if (row) row.remove();
		});
	}

	wp.domReady(function () {
		var panel = document.getElementById('claimprism-live-panel');
		if (!panel) return;
		wp.apiFetch.use(wp.apiFetch.createNonceMiddleware(ClaimPrism.nonce));

		panel.querySelector('.cg-check-now').addEventListener('click', function () { check(true); });
		bindEvidenceRows();

		if (wp.data && wp.data.subscribe) {
			wp.data.subscribe(queueCheck);
		} else {
			document.addEventListener('input', queueCheck);
		}

		window.setTimeout(function () { check(true); }, 500);
	});
}());
